Exemplo n.º 1
0
/*Wrapper function, adds legal Pawn Moves from Location to Linked List*/
int getPawnMoves(Game *game, Location *loc, ListNode *temp){
	int flag = 0;
	if (canMoveUK(game->board, loc, 1) && isEmpty(game->board[loc->column][loc->row + shiftUp(game->board, loc)])){
		Move *move = setMove(loc, setLocation(loc->column, loc->row + shiftUp(game->board, loc)), NONETYPE);
		if (isValidMove(game, move)){
			getPawnSingleMove(game->board, loc, temp, move);
			flag = 1;
		}
		else{
			freeMove(move);
		}
	}
	if (canMoveULK(game->board, loc, 1) && isOpposite(game->board[loc->column + shiftLeft(game->board, loc)][loc->row + shiftUp(game->board, loc)], game->board, loc)){
		Move *move = setMove(loc, setLocation(loc->column + shiftLeft(game->board, loc), loc->row + shiftUp(game->board, loc)), NONETYPE);
		if (isValidMove(game, move)){
			getPawnSingleMove(game->board, loc, temp, move);
			flag = 1;
		}
		else{
			freeMove(move);
		}
	}
	if (canMoveURK(game->board, loc, 1) && isOpposite(game->board[loc->column + shiftRight(game->board, loc)][loc->row + shiftUp(game->board, loc)], game->board, loc)){
		Move *move = setMove(loc, setLocation(loc->column + shiftRight(game->board, loc), loc->row + shiftUp(game->board, loc)), NONETYPE);
		if (isValidMove(game, move)){
			getPawnSingleMove(game->board, loc, temp, move);
			flag = 1;
		}
		else{
			freeMove(move);
		}
	}
	return flag;
}
Exemplo n.º 2
0
void GEngine::gameLoop(){
	bool endgame = false;
	while (!endgame) {
		//print the board:
		board.printBoard();
		
		//ask move to p1
		std::string move = "invalid";
		do{
			//check if move is valid
			std::cout<< "Player 1 ";
			move = p1->mkMove();
		}while (!isValidMove(move, p1));
		board.movePiece(move);
		
		//ask move p2
		move = "invalid";
		board.printBoard();
		do {
			std::cout<< "Player 2 ";
			move = p2->mkMove();
		} while (!isValidMove(move, p2));
		board.movePiece(move);
		
		//end turn
		std::cout<< "END TURN\n\n"<<std::endl;
	}
}
bool SmartCrawler::move(){
    turnsLeft = 20;

    if (atDiscoBall(oldPos,1)){
        attackDiscoBall(1);
        turnsLeft = 5;
        return true;
    }

    if (! m_map->hasBox[oldPos.x][oldPos.y-1][oldPos.z]){
        if(!movingUp){
        turnsLeft = 5;
        newPos.y -= 1;
        return true;
        }
        movingUp = false; 
    }

    IntVec3 dir(0,0,0);

    int distX = m_map->discoBallLoc.x - oldPos.x;
    int distZ = m_map->discoBallLoc.z - oldPos.z;
    
    if (abs(distX) > abs(distZ)){
        if (distX > 0){
            dir.x += 1;
        } else{
            dir.x -= 1;
        }
    } else{
        if (distZ > 0){
            dir.z += 1;
        } else{
            dir.z -= 1;
        }
    }
    
    if (isValidMove(oldPos+dir)){
        newPos = newPos + dir;
    } else{
        if (isValidMove(oldPos+dir,0,1,0) && hasBox(oldPos+dir)){
            newPos = newPos + dir;
            newPos.y += 1;
            turnsLeft = 100; 
        } else{
            newPos.y += 1; 
            movingUp = true; 
            turnsLeft = 100; 
            //attack(oldPos+dir,10);
            //turnsLeft = 5;
        }
    }
    return true;
}
Exemplo n.º 4
0
Arquivo: game.cpp Projeto: devkaz/niya
string Game::makeMove(Player player, string lastTile) {
    int x, y;
    while (true) {
        cout << "Your turn: " << player.name << endl;
        cout << "x: ";
        cin >> x;
        cout << "y: ";
        cin >> y;
        if (!lastTile.empty()) {
            if (isValidMove(x, y, lastTile)) {
                lastTile = board[x][y];
                board[x][y] = player.color;
                cout << "\nLast tile: " << lastTile << endl;
                printBoard();
                return lastTile;
            } else {
                cout << "\n" << x << " and " << y << " are not valid: " <<
                "The tile you choose should contain one symbol of the previous tile." << endl;
            }
        } else {
            lastTile = board[x][y];
            board[x][y] = player.color;
            cout << "\nLast tile: " << lastTile << endl;
            printBoard();
            return lastTile;
        }
    }
}
Exemplo n.º 5
0
/**
 * Play moves on move at a time
 */
void Board::playMoves() {
    std::list<Coords>::const_iterator iterator;
    bool allMovesGood = true;
    for (iterator = moves.begin(); iterator != moves.end(); ++iterator) {
        Coords move = *iterator;
        if (legalCoord(move)) {
            if (move.isStartMove()) {
                cmatrix[move.m_y][move.m_x].m_pointType = PointType::Start;
                currentMove = move;
                printBoardBasic();
                continue;
            } else if (move.isEndMove()) {
                cmatrix[move.m_y][move.m_x].m_pointType = PointType::End;
            } else {
                cmatrix[move.m_y][move.m_x].m_pointType = PointType::Normal;
            }
            if (!isValidMove(currentMove, move)) {
                allMovesGood = false;
                cout << "Move " << move << " is invalid" << endl;
            } else {
                cout << "Move " << move << " is valid" << endl;
            }
            currentMove = move;
            printBoardBasic();
        } else {
            allMovesGood = false;
            cout << "Move " << move << " is invalid" << endl;
        }
    }
    if (allMovesGood) {
        cout << "Summary: All moves are valid" << endl;
    } else {
        cout << "Summary: There are some invalid moves in the sequence" << endl;
    }
}
Exemplo n.º 6
0
/*Add legal Moves for Bishop/Rook/Queen/King at Location to Linked List*/
int getBRQKMoves(Game *game, Location *loc, ListNode *temp){
	int killflag, blockedflag, i, j, dist, len;
	int flag = 0;
	MoveType type;
	MoveType *list = getMoveTypeList(game->board, loc);
	len = getMoveTypeListLength(game->board, loc);
	for (i = 0; i < len; i++){
		killflag = 0;
		blockedflag = 0;
		type = list[i];
		dist = distFrom(game->board, loc, type);
		if (isKing(game->board, loc) && dist>0){
			dist = 1;
		}
		for (j = 1; j <= dist&&!killflag&&!blockedflag; j++){
			Location *tLoc = setLocation(loc->column + shiftCol(game->board, loc, type)*j, loc->row + shiftRow(game->board, loc, type)*j);
			if (legalMoveToKing(game, loc, tLoc)){
				Move *move = setMove(loc, tLoc, NONETYPE);
				if (isValidMove(game, move)){
					addMoveToList(temp, move);
					flag = 1;
				}
				else{
					freeMove(move);
				}
			}
			else{
				free(tLoc);
			}
		}
	}
	return flag;
}
Exemplo n.º 7
0
//move
Card *HumanPlayer::makeMove (Card *lMove, Card *rMove, Player *aLeftPlayer, Player *aRightPlayer, bool isPassOut) {
  Q_UNUSED(aLeftPlayer)
  Q_UNUSED(aRightPlayer)
  Q_UNUSED(isPassOut)
  Q_ASSERT(mDeskView);
  qDebug() << type() << "("<< mPlayerNo << ") moves";
  Card *res = 0;
  mClickX = mClickY = 0; mWaitingForClick = true;
  m_model->showMoveHint();
  draw();
  int cNo = -1;
  while (!res) {
    mDeskView->mySleep(-2);
    cNo = cardAt(mClickX, mClickY, !invisibleHand());
    if (cNo == -1) {
      mClickX = mClickY = 0;
      continue;
    }
    const int koz = mDeskView->model()->trumpSuit();
    res = mCards.at(cNo);
    // check if move accords with rules
    if (!isValidMove(res, lMove, rMove, koz)) {
      res = 0;
    }
  }
  clearCardArea();
  mPrevHiCardIdx = -1;
  mCards.remove(res);
  mCardsOut.insert(res);
  mClickX = mClickY = 0; mWaitingForClick = false;
  m_model->emitClearHint();
  draw();
  return res;
}
Exemplo n.º 8
0
//move the sprite
bool Sprite::move(float x, float y)
{
    vector nextpos;
    nextpos.x = (int)(pos.x + x);
    nextpos.y = (int)(pos.y + y);
    
    //if we can move to our next/future position
    if(isValidMove(nextpos.x, nextpos.y))
    {
        //erase the current sprite
        erase(pos.x, pos.y);
        
        pos.x += x;
        pos.y += y;
        
        //update the facing dir so we know which way we are facing
        //im not sure this is needed for the pong stuff but lets see
        facingDir.x = x;
        facingDir.y = y;
        
        draw(pos.x, pos.y);
        return true;
    }
    return false;
}
Exemplo n.º 9
0
int TicTacToe::play(bool _xTurn, int pos) {
	bool win;
	
	if(!isRightTurn(_xTurn)) {
		return INVALID_TURN;
	}
	
	if(!isValidMove(pos)) {
		return INVALID_MOVE;
	}
	
	placeMove(_xTurn,pos);
	
	plotGame();
	
	win = won(_xTurn);
	xTurn = !xTurn;
	
	if(win) {
		resetGame();
		return WIN;
	}
	else if(isFull()){
		resetGame();
		return OVER;
	}
	else {
		return NO_WIN;
	}
}
Exemplo n.º 10
0
/*
*    Algorithm
*        If all spaces are visited then return true
*        ELse,
*            Go through the list of all possible moves (8 total)
*            Pick one move and check if it's valid
*                If it is then mark it as visited and move on to the next step
*                Keep going until all spaces are filled
*            If a move doesn't work then backtrack to the last valid move and try a different next move
*        If none of the moves work and the board isn't complete then return false
*/
bool KnightsTour::search(int currRow, int currCol, int currStep, int** board)
{
    int nextRowPos;
    int nextColPos;

    // return true when all spaces have been visited
    if (currStep == maxSteps)
        return true;

    // go through all 8 possible moves
    for (int i = 0; i < 8; i++)
    {
        // pick a move from the list of moves
        nextRowPos = currCol + movesX[i];
        nextColPos = currRow + movesY[i];

        if (isValidMove(nextRowPos, nextColPos, board))
        {
            // move is valid so mark as visited and move to next step
            board[nextRowPos][nextColPos] = currStep + 1;

            // keep going and return true once all spaces are visited
            if (search(nextRowPos, nextColPos, currStep + 1, board))
                return true;
            else
                board[nextRowPos][nextColPos] = -1; // backtrack and move on to next move if invalid
        }
    }

    // If nothing works, then return false
    return false;
}
Exemplo n.º 11
0
Board moveBoard(Board b, int direction){
    // direction = UP, DOWN, LEFT or RIGHT
    // returns NULL if direction not possible
    // fatal error if no BLANK on board
    Board retVal = NULL;
    int *blankPos = malloc(sizeof(int)*2);
    if (blankPos == NULL){
        printf("Out of memory\n");
        exit(1);
    }   
    if (isValidMove(b, direction) == TRUE){
        retVal = copyBoard(b);
        getBlankPos(b, blankPos);
        if (direction == UP){
            swap(&retVal->array[blankPos[0]-1][blankPos[1]],
            &retVal->array[blankPos[0]][blankPos[1]]);
        } else if (direction == DOWN){
            swap(&retVal->array[blankPos[0]+1][blankPos[1]],
            &retVal->array[blankPos[0]][blankPos[1]]);
        } else if (direction == LEFT){
            swap(&retVal->array[blankPos[0]][blankPos[1]-1],
            &retVal->array[blankPos[0]][blankPos[1]]);
        } else if (direction == RIGHT){
            swap(&retVal->array[blankPos[0]][blankPos[1] + 1],
            &retVal->array[blankPos[0]][blankPos[1]]);
        }
    } else {
        retVal = NULL;
    }
    free(blankPos);
    return retVal;
}
Exemplo n.º 12
0
void isValidMove_test(void)
{
        WorldMap wm;
        XYPos pos;
        bool test;

        wm.xlen = 3;
        wm.ylen = 3;
        initWorldMap(&wm);

        pos.x = 1;
        pos.y = 1;
        addToWorldMap(&wm, pos, N, OPEN);
        addToWorldMap(&wm, pos, S, OPEN);
        addToWorldMap(&wm, pos, E, OPEN);
        addToWorldMap(&wm, pos, W, OPEN);

        pos.x = 0;
        pos.y = 1;
        markSquareAsDead(&wm, pos);

        pos.x = 1;
        pos.y = 0;
        markSquareAsDead(&wm, pos);

        pos.x = 2;
        pos.y = 1;
        markSquareAsDead(&wm, pos);

        pos.x = 1;
        pos.y = 2;
        markSquareAsDead(&wm, pos);

        pos.x = 1;
        pos.y = 1;
        test = isValidMove(wm, pos, N, true);
        assert(test == false);
        test = isValidMove(wm, pos, W, true);
        assert(test == false);
        test = isValidMove(wm, pos, S, true);
        assert(test == false);
        test = isValidMove(wm, pos, E, true);
        assert(test == false);

        return;
}
Exemplo n.º 13
0
/*Add legal Moves for Knight at Location to Linked List*/
int getKnightSingleMove(Game *game, Location *loc, ListNode *temp, MoveType type){
	MoveType col;
	MoveType row;
	char c;
	int flag = 0;
	switch (type)
	{
	case UR:col = R; row = U; break;
	case UL:col = L; row = U; break;
	case DL:col = L; row = D; break;
	case DR:col = R; row = D; break;
	case U:row = U;
	case D:row = D;
	case L:col = L;
	case R:row = R;
	}
	if (canMoveK(game->board, loc, 1, col) && canMoveK(game->board, loc, 2, row)){
		c = game->board[loc->column + shiftCol(game->board, loc, col)][loc->row + shiftRow(game->board, loc, row) * 2];
		if (isEmpty(c) || isOpposite(c, game->board, loc)){
			Move *move = setMove(loc, setLocation(loc->column + shiftCol(game->board, loc, col), loc->row + shiftRow(game->board, loc, row) * 2), NONETYPE);
			if (isValidMove(game, move)){
				addMoveToList(temp, move);
				flag = 1;
			}
			else{
				freeMove(move);
			}
		}
	}
	if (canMoveK(game->board, loc, 2, col) && canMoveK(game->board, loc, 1, row)){
		c = game->board[loc->column + shiftCol(game->board, loc, col) * 2][loc->row + shiftRow(game->board, loc, row)];
		if (isEmpty(c) || isOpposite(c, game->board, loc)){
			Move *move = setMove(loc, setLocation(loc->column + shiftCol(game->board, loc, col) * 2, loc->row + shiftRow(game->board, loc, row)), NONETYPE);
			if (isValidMove(game, move)){
				addMoveToList(temp, move);
				flag = 1;
			}
			else{
				freeMove(move);
			}
		}
	}
	return flag;
}
Exemplo n.º 14
0
int Position::generateMoves(Square moves[]) const
{
    int total = 0;

    for (Square sq = 0; sq < BOARD_SIZE; ++sq, sq += (Square)notInRange(sq) << 3) {
        if (isValidMove(sq))
            moves[total++] = sq;
    }

    return total;
}
void Board::makeRandomMove()
{
	Move m(-1, -1);
	do
	{
		m.r = rand() % BOARD_SIZE;
		m.c = rand() % BOARD_SIZE;
	} while(!isValidMove(m));

	makeMove(m);
}
Exemplo n.º 16
0
bool Position::isValidMove(Square sq) const
{
    if (!isEmpty(sq))
        return false;

    for (int d = 0; d < TOT_DIR; ++d) {
        if (isValidMove(sq, DIR[d]))
            return true;
    }

    return false;
}
Exemplo n.º 17
0
/**
 * Called after piece is selected
 * Determines if move is valid
 */
bool Piece::selectCell(int _row, int _col){
	//change first_time
	if(active && isValidMove(_row,_col)){
		movePiece(_row,_col);
		//g_debug("moved piece!");
		//std::cout << "moved piece!" << std::endl;
		//first_move=0;
		return true;
	}
	return false;

}
Exemplo n.º 18
0
Vertex *updateNeighborhood(Graph *g,Vertex *u)
{
   int i,j;
   Vertex *v;
   Pilot *np, *p;
   Vect *nextAcc;
   int boost=((Vect4D *)u->e)->b;
   int l=boost>0?2:1;

   p=createPilotFromVertex(u);

   for(i=-l;i<=l;i++)
      {
	 for(j=-l;j<=l;j++)
	    {  
	       np=createEmptyPilot();
	       nextAcc=createVect(i,j); 
	       np->speed=vectSum(p->speed,nextAcc); 
	       np->pos=vectSum(p->pos,np->speed);
		     
	       if(isValidMove(p,np,g->field))
		  {
		     boost=(i==-2||i==2||j==-2||j==2)?((Vect4D *)u->e)->b-1:((Vect4D *)u->e)->b;
		     
		     v=g->vertices[np->pos->x][np->pos->y][getSpeedIndex(np->speed)][boost];
		     
		     if(v->distance>u->distance+1)
			{
			   v->previous=u;
			   v->distance=u->distance+1;
			   fh_insertkey(g->heap,v->distance,v);
			}

		     if(g->field->cell[np->pos->x][np->pos->y]=='=')
			{
			   return v;
			}
		  }
	       else 
		  {
		     destroyPilot(np);
		     destroyVect(nextAcc);
		     continue;
		  }

	       destroyVect(nextAcc);
	    }
      }

   return NULL;
}
Exemplo n.º 19
0
void Game::startGame()
{
	initNewDeal();
	while (state.total_score[TEAM1] < SCORE_LIMIT && state.total_score[TEAM2] < SCORE_LIMIT)
	{
		if (deal())
		{
			// Fill State structure
			clearTurn();
			createNewRoundStates();
			printBoard();
			
			for (int turn = 0; turn < NB_TURNS; turn++)
			{
				state.turn_number = turn;
				for (int i = 0; i < NB_PLAYERS; i++)
				{
					int player = (state.first_to_play + i) % NB_PLAYERS;
					updateTurnState(player);
					Card c = players[player]->playCard();
					state.turn[player] = c;
					if (!isValidMove(player, c))
					{
						looseByCheating(player);
						turn = NB_TURNS;
						break;
					}
					hands[player].remove(c);
				}
				printBoard();
				
				updateEndTurnStates();
				for (int i = 0; i < NB_PLAYERS; i++)
					players[i]->endRound();
				state.first_to_play = state.playerWinningFold();
				clearTurn();
			}
			
			updateEndRoundStates();
			printRoundScore();
			printGameScore();
			if (cheater != INVALID_PLAYER)
			{
				std::cout << "The player " << cheater << " made his team loose by doing an invalid move." << std::endl;
			}
		}
		
		initNewDeal();
	}
}
Exemplo n.º 20
0
void Position::applyMove(Square sq)
{
    place(sq, currentPlayer());

    for (int d = 0; d < TOT_DIR; ++d) {
        if (isValidMove(sq, DIR[d]))
            reverse(sq, DIR[d]);
    }

    ++count[currentPlayer()];
    nullMoveCount = 0;

    changePlayer();
}
Exemplo n.º 21
0
vector< pair<int,int> > AIEngine::getValidMoves(pair<int,int> piece) {
	vector< pair<int,int> > validMoves;
	
	// For that piece, check all valid moves and store in vector of pairs
    int sX = get<0>(piece),
		sY = get<1>(piece);
    
	// Case piece type is X
    if(pieceType == 'X') {
		if(sY > 0 && sX < 7) {
			if (isValidMove(sX + 1, sY - 1, false)) {
                pair<int,int> p(sX + 1, sY - 1);
                validMoves.push_back(p);
            }
        }
		
		if (sY < 7 && sX < 7) {
			if (isValidMove(sX + 1, sY + 1, false)) {
                pair<int,int> p(sX + 1, sY + 1);
                validMoves.push_back(p);
            }
        }
		
		if (sX < 7) {
			if (isValidMove(sX + 1, sY, true)) {
				pair<int,int> p(sX + 1, sY);
				validMoves.push_back(p);
			}
		}
	}
	
	// Case piece type is O 
    else {
        if(sY > 0 && sX > 0) {
			if (isValidMove(sX - 1, sY - 1, false)) {
                pair<int,int> p(sX - 1,sY - 1) ;
                validMoves.push_back(p);
            }
        }
		
		if (sY < 7 && sX > 0) {
			if (isValidMove(sX - 1, sY + 1, false)) {
                pair<int,int> p(sX - 1,sY + 1);
                validMoves.push_back(p);
            }
        }
		
		if (sX > 0) {
			if (isValidMove(sX - 1, sY, true)) {
				pair<int, int> p(sX - 1, sY);
				validMoves.push_back(p);
			}
		}
    }
	
	return validMoves;
}
Exemplo n.º 22
0
Position& Position::move( const Track& track )
{
    if ( isValidMove( track) )
    {
        // increase of ASCII characters one at a time is equivalent to moving one space
        m_horizontal += track.horizontal;
        m_vertical += track.vertical;
    }
    else
    {
        throw invalid_argument( "Move is out of range." );
    }

    return *this;
}
Exemplo n.º 23
0
bool AIEngine::isValidPiece(int i, int j) {
	char piece = board->getIndex(i, j);
	
	// Case your piece is X
	if(pieceType == 'X') {
		// If the given position has an X piece, consider movements down
        if(piece == 'X') {
            // Diagonal left
			if(j > 0 && i < 7) {
				if (isValidMove(i + 1, j - 1, false))
                    return true;
            }
			
			// Diagonal right
			if (j < 7 && i < 7) {
				if (isValidMove(i + 1, j + 1, false))
                    return true;
            }
			
			// Forward
			if (i < 7) {
				if (isValidMove(i + 1, j, true))
					return true;
			}
            
			return false;
        }
    }
	
	// Case your piece is O
    else {
        // If the given position has an O piece, consider movements up
		if(piece == 'O') {
            // Diagonal left
			if(j > 0 && i > 0) {
				if (isValidMove(i - 1, j - 1, false))
                    return true;
            }
			
			// Diagonal right
			if (j < 7 && i > 0) {
				if (isValidMove(i - 1, j + 1, false))
                    return true;
            }
			
			// Forward
			if (i > 0) {
				if (isValidMove(i - 1, j, true))
					return true;
			}
            return false;
        }
    }
    return false;
}
Exemplo n.º 24
0
/*This method is used to validate loops*/
int isValidLoop(FILE* inputFile)
{
    /*Used to keep track of tokens, and store lines and tokens*/
    char tokens[1][20], line[100], lineCopy[100], *token;

    /*Used to keep track of current position within text file*/
    fpos_t currentPosition;

    /*Stores current position within text file so the location can be read from again*/
    fgetpos (inputFile,&currentPosition);

    /*This loop is almost the same as the one in the isValidMove() function*/
    /*The only difference is that it checks for an endloop statement and then resets the position in the file after validation*/
    while ( !feof(inputFile) )
    {
        fgets( line, 99, inputFile );
        toLowercase(line);
        strcpy(lineCopy, line);

        token = removeWhiteSpace(strtok( lineCopy, " \t\n" ));

        if (strcmp(token, "\0") == 0 || strncmp(token, "#", 1) == 0)
            continue;

        strcpy(tokens[0], token);
        token = removeWhiteSpace(strtok( NULL, " \t\n" ));

        /*Check for endloop command*/
        if (strcmp(tokens[0], "endloop") == 0 && token == NULL)
        {
            /*Go back to position in file before validation*/
            fsetpos (inputFile,&currentPosition);
            return true;
        }

        /*Check if moves within file are valid*/
        if (isValidMove(line, inputFile) == false)
            return false;
    }

    return false;
}
Exemplo n.º 25
0
//main function
int main()
{
char turntracker='W';
initialize(arr); //a function called in beginning to initialize the chess pieces their required positions

while(1)
{
	process=0;

printf("\n        CHESS PLAYING ROBOT CONSOLE\n");
printf("        Indian Institute of Technology Kanpur\n\n");
display(arr);
printf("\n");

//getmove merged here
printf("\nMake your move [For ending game, type -1 and press enter]\t");
int initrow, initcol, finrow, fincol,temp;
if(turntracker=='B')
{ process=0;
	getch();
printf("\n\t\tBlack's Turn.  Move is played automatically:\n");
makeBestMove(arr,'B',1);
turntracker='W';
}
else if(turntracker=='W')
{
printf("\n\t\tWhite's Turn.:");
printf("\nFormat: InitialRow InitialColumn FinalRow FinalColumn\t" );
cin>>initrow;
if(initrow==-1)
exit(0);
cin>>initcol>>finrow>>fincol;
temp=isValidMove(initrow,initcol,finrow,fincol,arr,turntracker);
if (temp==1)
{makeMove(initrow,initcol,finrow,fincol,arr,turntracker);
turntracker='B';
}
else if(temp==0)
printf("\n** INVALID MOVE ** Please try again.\n"); //loop iteration
}  

}
void MazeWalker::storeValidMoves(){
	if(m_isDFS){
		if(isValidMove(m_curPos.getRow()+1, m_curPos.getCol()))
			m_moveStack.push(Position(m_curPos.getRow()+1,m_curPos.getCol()));
		if(isValidMove(m_curPos.getRow()-1, m_curPos.getCol()))
			m_moveStack.push(Position(m_curPos.getRow()-1,m_curPos.getCol()));
		if(isValidMove(m_curPos.getRow(), m_curPos.getCol()+1))
			m_moveStack.push(Position(m_curPos.getRow(),m_curPos.getCol()+1));
		if(isValidMove(m_curPos.getRow(), m_curPos.getCol()-1))
			m_moveStack.push(Position(m_curPos.getRow(),m_curPos.getCol()-1));
	}
	else{
		if(isValidMove(m_curPos.getRow()+1, m_curPos.getCol()))
			m_moveQueue.push(Position(m_curPos.getRow()+1,m_curPos.getCol()));
		if(isValidMove(m_curPos.getRow()-1, m_curPos.getCol()))
			m_moveQueue.push(Position(m_curPos.getRow()-1,m_curPos.getCol()));
		if(isValidMove(m_curPos.getRow(), m_curPos.getCol()+1))
			m_moveQueue.push(Position(m_curPos.getRow(),m_curPos.getCol()+1));
		if(isValidMove(m_curPos.getRow(), m_curPos.getCol()-1))
			m_moveQueue.push(Position(m_curPos.getRow(),m_curPos.getCol()-1));
	}
}
Exemplo n.º 27
0
bool ChineseCheckersState::undoMove(Move m) {
  // Ensure the from and to are reasonable
  if (m.from > 80 || m.to > 80 || m.from == m.to)
    return false;

  // Undo the move
  std::swap(board[m.from], board[m.to]);
  swapTurn();

  // Check the move is valid from this state that is back one step
  if (!isValidMove(m)) {
    // Woops, it was not valid, undo our changes
    swapTurn();
    std::swap(board[m.from], board[m.to]);

    return false;
  }

  return true;
}
Exemplo n.º 28
0
/*
 * Add an available move for the player to the list of moves.
 * - Move is expected to be valid in terms of piece type constraints (e.g: a peon can only move to 3 possible squares).
 * - Additional validation will be done in this function (moves that result in a check status for the current player are
 *	 illegal).
 * --> If the move is legal, it is added to the list of possibleMoves. Otherwise nothing happens.
 * Input:
 *		board ~ The chess game board.
 *		possibleMoves ~ A list of possible moves by the current player, we aggregate it as we check
 *						possible eat / position change moves.
 *		isMovesForBlackPlayer ~ True if current player is black. False if white.
 *		startPos ~ Where the piece is currently located.
 *		targetX, targetY ~ Coordinates of where the piece will move to.
 *		kingPos ~ Current position of the current player's king (following the execution of the move).
 */
bool addPossibleMove(char board[BOARD_SIZE][BOARD_SIZE], LinkedList* possibleMoves, bool isMovesForBlackPlayer,
					 Position* startPos, int targetX, int targetY, Position* kingPos)
{
	// Check if the move doesn't cause the current player a check. If it does, we don't count it.
	if (!isValidMove(board, isMovesForBlackPlayer, startPos, targetX, targetY, kingPos))
		return false;

	Position targetPos = { targetX, targetY };

	Move* newMove = createMove(startPos, &targetPos);
	if (g_memError)
		return false;

	insertLast(possibleMoves, newMove);
	if (g_memError)
	{
		deleteMove((void*)newMove);
		return false;
	}

	return true;
}
Exemplo n.º 29
0
std::list<Move*> Piece::getValidMoves( const Board* board ) const
{
    // Check if each space is a valid move for the piece
    std::list<Move*> moves;
    for ( unsigned int iRow = 0; iRow < 8; ++iRow )
    {
        for ( unsigned int iCol = 0; iCol < 8; ++iCol )
        {
            Move* currMove = new Move( color, col, row, iCol, iRow );
            if ( isValidMove( board, *currMove ) )
            {
                moves.push_back( currMove );
            }
            else
            {
                delete currMove;
            }
        }
    }

    return moves;
}
Exemplo n.º 30
0
State onPlayersTurn(Game* game) {
  /* added clear screen -Cesar 1/27 */
  char cmd[255];
  char choice = 0;
  char userInput[255];
  char promotionChoice;
  char maxTurnUserInput;
  int result;
  int ox, oy, dx, dy;
  clearScreen();
  assert(game);
  printBoard(game);
  printf("Turn number: %d, ", game->turn+1);
  if(game->turn%2 == 0)
	  printf("WHITE's turn\n");
  else
	  printf("BLACK's turn\n");
  printUserMenu(game);
  getGameInput(cmd);
  choice = cmd[0];
  
  if(check500Turns(game))
	  return MainMenu;


  /* added by Cesar 1/26 */
  switch(choice)
    {
    case '0':
      return MainMenu;
    case '1':
      printHints(game);
      return TurnPlayer;
    case '2':
      redo(game);
      return TurnPlayer;
	case '3':
	  printLog(game);
	  return TurnPlayer;
    case '4':
      replay(game);
      return TurnPlayer;
    case '5':
	  printf("Enter the file name you want to save \n");
	  scanf("%s", userInput);
      saveLog(game, userInput);
      fseek(stdin,0,SEEK_END);
	  return TurnPlayer;
	case '6':
	  printf("Enter the file name you want to save: ");
	  scanf("%s", userInput);
	  printf("\n");
      fseek(stdin,0,SEEK_END);
	  saveGame(game, userInput);
	  return TurnPlayer;
	case '7':
		gameOptions(game);
		return TurnPlayer;
    default:
      break;
    }
  
  
	ox = cmd[0] - 97;
	oy = cmd[1] - 49;
	dx = cmd[2] - 97;
	dy = cmd[3] - 49;
	if((!checkBoarder(ox, oy))||(!checkBoarder(dx, dy)) || (isValidMove(game, ox, oy, dx, dy) <= 0))
	{
		printf("INVALID MOVE DETECTED");
		if(game->setting->allowIllegalMove == 1)
		{
			printf(", TRY AGAIN\n\n");
			return TurnPlayer;
		}
		else
		{
			printf(", GAME OVER!\n\n");
			return MainMenu;
		}
	}

  
  result = gameLogic(game, cmd);
  if(result == 9 || result == 10)
  {
	  promotionChoice = ' ';
	  while(promotionChoice != 'Q' && promotionChoice != 'R' && promotionChoice != 'N' && promotionChoice != 'B')
	  {
		  printf("Pawn promotion, enter the promotion choice (char to represent piece): ");
		  scanf("%c", &promotionChoice);
		  fseek(stdin,0,SEEK_END);
		  if(promotionChoice=='q') promotionChoice='Q';
		  else if(promotionChoice=='r') promotionChoice='R';
		  else if(promotionChoice=='n') promotionChoice='N';
		  else if(promotionChoice=='b') promotionChoice='B';
		  printf("%c\n",promotionChoice);
		  if(promotionChoice != 'Q' && promotionChoice != 'R' && promotionChoice != 'N' && promotionChoice != 'B')
			  printf("Invalid input, try again.\n");
	  }
      result = promotion(game, cmd, promotionChoice);
  }
  if(result == 7)
  {
	  printf("CHECKMATE\n");
	  getchar();
	  return MainMenu;
  }
  else if(result == 8)
  {
	  printf("STALEMATE\n");
	  getchar();
	  return MainMenu;
  }

  if(game->setting->gameMode == 0)
    return TurnAI;
  else if(game->setting->gameMode == 1)
    return TurnPlayer;
  else
    return MainMenu; /* game logic returns 0 meaning the game is end */
}