filter valid moves for "in check"

This commit is contained in:
Stefan Bühler 2009-01-07 15:27:31 +01:00
parent 910626b3c7
commit cf8fc3cedc
3 changed files with 41 additions and 7 deletions

View File

@ -84,11 +84,11 @@ namespace toruschess {
return Pos(p.x() + d.x, p.y() + d.y);
}
QList<Move> Field::validMoves(const Pos &from) const {
QList<Move> Field::simpleValidMoves(const Pos &from) const {
QList<Move> moves;
int thePlace = place(from);
Piece thePiece = (Piece) qAbs(thePlace);
qDebug("validMoves: %i", thePiece);
// qDebug("simpleValidMoves: %i", thePiece);
switch (thePiece) {
case NOPIECE:
break;
@ -131,10 +131,42 @@ namespace toruschess {
}
break;
}
qDebug("validMoves: found %i", moves.size());
// qDebug("simpleValidMoves: found %i", moves.size());
return moves;
}
QList<Move> Field::validMoves(const Pos &from) const {
QList<Move> moves = simpleValidMoves(from);
int thePlace = place(from);
Pos pking(0,0);
/* find king */
for (int x = 0; x < 8; x++) for (int y = 0; y < 8; y++) {
if (piece(Pos(x, y)) == KING && 0 < place(Pos(x, y)) * thePlace) {
pking = Pos(x, y);
goto foundking;
}
}
return QList<Move>(); /* error, no king found */
foundking:
QList<Move> resMoves;
Field testField(*this);
testField.place(from) = 0;
bool movedKing = (from == pking);
foreach(Move m, moves) {
testField.place(m.to()) = thePlace;
for (int x = 0; x < 8; x++) for (int y = 0; y < 8; y++) {
Pos curp(x, y);
if (0 > testField.place(curp) * thePlace && testField.simpleValidMoves(curp).contains(Move(&testField, curp, movedKing ? m.to() : pking))) {
goto invalidmove;
}
}
resMoves.push_back(m);
invalidmove:
testField.place(m.to()) = m.prevTo();
}
return resMoves;
}
bool Field::validMove(const Move &m) const {
QList<Move> moves = validMoves(m.from());
return moves.contains(m);

View File

@ -42,7 +42,7 @@ namespace toruschess {
int x() const { return m_x; }
int y() const { return m_y; }
bool operator==(const Pos &other) {
bool operator==(const Pos &other) const {
return m_x == other.m_x && m_y == other.m_y;
}
@ -60,7 +60,7 @@ namespace toruschess {
int prevTo() const { return m_prevTo; }
Player player() const { return m_player; }
bool operator==(const Move &other) {
bool operator==(const Move &other) const {
return m_from == other.m_from
&& m_to == other.m_to
&& m_prevFrom == other.m_prevFrom
@ -92,6 +92,8 @@ namespace toruschess {
bool undo(const Move &m);
private:
QList<Move> simpleValidMoves(const Pos &from) const;
int m_places[8][8];
};

View File

@ -152,13 +152,13 @@
<autokdesu>false</autokdesu>
<envvars/>
<runarguments>
<toruschess></toruschess>
<toruschess/>
</runarguments>
<cwd>
<toruschess>/home/stefan/studium/7. semester/fapra_vis/src/toruschess/..</toruschess>
</cwd>
<debugarguments>
<toruschess></toruschess>
<toruschess/>
</debugarguments>
</run>
<general>