コード例 #1
0
ファイル: gamestate.cpp プロジェクト: Jinxit/minimax_checkers
/**
 * Returns a list of all valid moves for \p pWho
 *
 * \param pMoves a vector where the list of moves will be appended
 * \param pWho the \ref ECell code (CELL_OWN or CELL_OTHER) of the
 * player making the move
 */
void GameState::findPossibleMoves(std::vector<GameState> &pStates) const
{
    pStates.clear();

    if (mLastMove.isEOG())
        return;

    if (mMovesUntilDraw <= 0)
    {
        pStates.push_back(GameState(*this, Move(Move::MOVE_DRAW)));
        return;
    }

    // Normal moves are forbidden if any jump is found
    bool lFound=false;
    int lPieces[cPlayerPieces];
    uint8_t lMoveBuffer[cPlayerPieces];
    std::vector<Move> lMoves;
    int lNumPieces=0;
    for (int i = 1; i <= cSquares; ++i)
    {
        // Is this a piece which belongs to the player making the move?
        if (at(i) & mNextPlayer)
        {
            bool lIsKing = at(i)&CELL_KING;

            if (tryJump(lMoves, cellToRow(i), cellToCol(i), lIsKing, lMoveBuffer))
                lFound=true;

            lPieces[lNumPieces++]=i;
        }
    }

    // Try normal moves if no jump was found
    if (!lFound)
    {
        for (int k = 0; k < lNumPieces; ++k)
        {
            int lCell = lPieces[k];
            bool lIsKing = at(lCell) & CELL_KING;
            tryMove(lMoves, lCell, lIsKing);
        }
    }

    // Convert moves to GameStates
    for (unsigned i = 0; i < lMoves.size(); ++i)
        pStates.push_back(GameState(*this, lMoves[i]));

    // Admit loss if no moves can be found
    if (pStates.size() == 0)
        pStates.push_back(GameState(*this, Move(mNextPlayer == CELL_WHITE ? Move::MOVE_RW : Move::Move::MOVE_WW)));
}
コード例 #2
0
ファイル: Utils.cpp プロジェクト: Jasonkatz/AI-Project-1
GameState GameState::ApplyMove(GameState originalState, std::vector<Location> pieces, int id) {
	GameState state = GameState(originalState.board);
	for (unsigned int i = 0; i < pieces.size(); ++i) {
		state.board[pieces[i].row][pieces[i].column] = id;
	}
	return state;
}
コード例 #3
0
bool GameStateHandler::execute( GameNet::Box * box )
{
    auto message = box->getData();
    state = GameState();
    state.ParseFromString(message);
    
    CCLOG("Game state change:");
    CCLOG("===========");
    CCLOG("%s", state.DebugString().c_str());
    
    if( state.has_name() )
    {
        updateName();
    }
    
    if( state.has_pitchsize() )
    {
        updateSize();
    }
    
    if( state.has_duration() )
    {
        updateDuration();
    }
    
    if( state.has_state() )
    {
        updateMatchState();
    }
    
    return false;
}
コード例 #4
0
//BUTTON FUNCTIONS
void GameScreen::MenuButton()
{
	_gravityReturn = _gravity;
	_jumpReturn = GameManager::sharedGameManager()->GetJump();

	_gravity = 0;
	GameManager::sharedGameManager()->SetJump(0);

	//Paused Text
	auto moveTo = MoveTo::create(0.5, Vec2(_winSizeW*0.5f,_winSizeH*0.5f)); // Take half a second to move off screen.
	_lblMessage->setString("Paused");
	_lblMessage->runAction(moveTo);

	//Return Button
	moveTo = MoveTo::create(0.5, Vec2(_winSizeW*0.5f, _winSizeH*0.4f)); // Take half a second to move off screen.
	_btnReturn->runAction(moveTo);

	//End Button
	moveTo = MoveTo::create(0.5, Vec2(_winSizeW*0.5f, _winSizeH*0.3f)); // Take half a second to move off screen.
	_btnEnd->runAction(moveTo);

	//Santa
	moveTo = MoveTo::create(0.5, Vec2(_winSizeW*0.5f, _winSizeH*0.7f)); // Take half a second to move off screen.
	_santaPaused->runAction(moveTo);

	GameManager::sharedGameManager()->isGameLive = false;
	GameState();

}
コード例 #5
0
ファイル: game.cpp プロジェクト: farys/Ball-Game
void Game::calculatePsychic(SceneActor *target){

    calculateCollisions(target);

    Point3f *p = target->getPosition();
    Point3f f = target->getForce();
    Point3f newF;

    //kalkulacja nowych sil
    newF.x = (f.x + target->gameState.force.x) * target->getFriction();
    newF.y = (f.y + target->gameState.force.y) * target->getFriction();

    //zdarzenie gdy sila na x przestala oddzialywac
    if(newF.x < 0.001f && newF.x > -0.001f){
        target->gameState.zeroForce = true;
        newF.x = 0;
    }

    //gdy sila na osi y przestala oddzialywac
    if(newF.y < 0.001f && newF.y > -0.001){
        newF.y = 0;
    }

    //maksymalna oddzialywana sila
    if(newF.x > 10){
        newF.x = 10;
    } else if(newF.x < -10) {
        newF.x = -10;
    }

    target->setPosition(new Point3f(p->x+newF.x, p->y+newF.y, 0));
    target->setForce(&newF);
    target->update();
    target->gameState = GameState();
}
コード例 #6
0
ファイル: player.cpp プロジェクト: marcbllv/checkers
GameState Player::play(const GameState &pState, const Deadline &pDue) {
    if(pState.getNextPlayer() == CELL_RED) {
        Player::color = CELL_RED;
    } else {
        Player::color = CELL_WHITE;
    }

    nodesSeen = 0;

    std::vector<GameState> lNextStates;
    pState.findPossibleMoves(lNextStates);

    if(lNextStates.size() == 0) {
        return GameState(pState, Move());
    } else if(lNextStates.size() == 1) {
        return lNextStates.front();
    }

    // Building tree
    Node root(pState);
    root.mkTree(1, true);

    // Computing minmax algorithm
    GameState bestGS = Heuristics::topMinmax(root, pDue);
    std::cerr << "Nodes seen: " << nodesSeen  << std::endl;
    return bestGS;
}
コード例 #7
0
void GameScreen::update(float delta)
{
	if (GameManager::sharedGameManager()->isGameLive)
	{
		GameState();

		GameManager::sharedGameManager()->SetSantaPos(_santa->getPositionX(), _santa->getPositionY());

		//Checked Paused
		if (GameManager::sharedGameManager()->isPaused == true)
		{
			MenuButton();
		}

		//Collide with Santa
		if (_platform->CheckDirtPlatformCol(_santa->getBoundingBox()))//Check santa collision with dirt platform
		{
			CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("Assets/Sounds/Jump.mp3");
			GameManager::sharedGameManager()->SetJump(20);
		}

		if (_platform->CheckIcePlatformCol(_santa->getBoundingBox())) //Check santa collision with ice platform
		{
			CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("Assets/Sounds/Jump.mp3");
			GameManager::sharedGameManager()->SetJump(10);
		}

		if (_powerUp->CheckPowerUpCol(_santa->getBoundingBox())) //Check santa collision with powerUp
		{
			CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("Assets/Sounds/Jump.mp3");
			GameManager::sharedGameManager()->SetJump(40);
		}

		Vec2 currentPos = _santa->getPosition();
		_santa->setPosition(currentPos.x, currentPos.y + GameManager::sharedGameManager()->GetJump());

		//Change jump to fall
		if (GameManager::sharedGameManager()->GetJump() > -20)
		{
			GameManager::sharedGameManager()->DecrementJump(1);
		}

		//Santa Death
		if ((_santa->getPosition().y - _santa->getContentSize().height / 5) <= _winSizeH * -0.01f)
		{
			DeathsScreen();
		}

		//Update Santa X Pos
		CCSize _winSize = CCDirector::sharedDirector()->getWinSize();
		float maxX = _winSize.width - (_santa->getContentSize().width / 4);
		float minX =_santa->getContentSize().width / 2;

		float diff = (_santaPointsPerSecX * delta);
		float newX = _santa->getPosition().x + diff;
		newX = MIN(MAX(newX, minX), maxX);
		_santa->setPosition(Vec2(newX, _santa->getPosition().y));
	}
}
コード例 #8
0
Controller::Controller()
{
    director = cocos2d::Director::getInstance();
    connector = GameNet::Connector::getInstance();
    
    admin = false;
    speedScale = 1;
    GameState state = GameState();
}
コード例 #9
0
bool
StarServer::GameLoop()
{
    if (active && paused) {
        UpdateWorld();
        GameState();
    }

    else if (!active) {
        UpdateWorld();
        GameState();
        Sleep(10);
    }

    Game::GameLoop();
    return false;  // must return false to keep processing
    // true tells the outer loop to sleep until a
    // windows event is available
}
コード例 #10
0
void MainWindow::resetGame() {
    score = 0;
    level = 1;
    numberOfRobots = MIN_ROBOTS;
    gameState = GameState(numberOfRobots);
    gameState.draw(scene);
    displayScore();
    displayLevel();
    gameOver = false;
    gameOverWindow.hide();
}
コード例 #11
0
void ServerNameUpdateHandler::execute(std::string name)
{
    // gameState difference
    GameState stateChange = GameState();
    stateChange.set_name(name);
    
    // update local game state object
    controller->gameState.set_name(name);
    
    // send to server
    BoxFactory::admin( connector->getServer(), stateChange)->send();
}
コード例 #12
0
void StopGameHandler::execute()
{
    
    // gameState difference
    GameState stateChange = GameState();
    stateChange.set_state(GameState_State_STATE_LOBBY);
    
    // update local game state object
    controller->gameState.set_state(GameState_State_STATE_LOBBY);
    
    // send to server
    BoxFactory::admin( connector->getServer(), stateChange)->send();
}
コード例 #13
0
IntermediateGameState IntermediateGameState::act(const std::vector<Action>& actions, GameStateObserver& observer) const {
    REQUIRE(state != GAME_OVER);  // iff get_predecessor().is_game_over()
    auto copy = *this;

    if (state == REVERSE_ALL_CHOICE) {
        if (!suppress_action) {
            for (unsigned int player_index = 0u; player_index < PLAYER_COUNT; ++player_index) {
                if (actions.at(player_index) == 1u) {
                    copy.successor.get_player(player_index).reverse();
                } else {
                    REQUIRE(actions.at(player_index) == 0u);
                }
            }
        }

        copy.successor.initial_movement(copy.predecessor, observer, copy.movement_excess);
        copy.suppress_action = false;
        copy.state = ABOUT_TO_ACT;
    }
    else if (state == ABOUT_TO_ACT) {
        ASSERT(!suppress_action);
        copy.suppress_action = !copy.successor.act(actions, predecessor, observer, movement_excess);
        copy.state = REVERSE_PACMAN_CHOICE;
    }
    else if (state == REVERSE_PACMAN_CHOICE) {
        copy.predecessor = copy.successor;

        if (successor.is_game_over()) {
            copy.successor = GameState();  // there is no successor
            copy.state = GAME_OVER;
        }
        else {
            if (!suppress_action) {
                if (actions.at(PLAYER_PACMAN) == 1u) {
                    copy.successor.get_player(PLAYER_PACMAN).reverse();
                } else {
                    REQUIRE(actions.at(PLAYER_PACMAN) == 0u);
                }
            }

            copy.successor.init_successor(copy.predecessor);
            copy.suppress_action = !copy.successor.progress_timers(copy.predecessor, observer);
            copy.state = REVERSE_ALL_CHOICE;
        }
    }

    return copy;
}
コード例 #14
0
int main() {
	feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
	GameState gamestate = GameState();
	ShibataBot bot = ShibataBot();

	bot.gamestate = &gamestate;
	bot.myShip = gamestate.myShip;

	while (bot.myShip != NULL) {
		gamestate.Update();
		bot.Update();
		gamestate.WriteData();
	}

	return 0;
}
コード例 #15
0
void State::preTurnUpdate(PlayerState playerStates[]) {
    if(turn > 0) {
        for (int i = 0; i < PLAYER_COUNT; i++) {
            playerStates[i].leadPodID = previous.playerStates[i].leadPodID;
            playerStates[i].lastPods[0] = previous.playerStates[i].pods[0];
            playerStates[i].lastPods[1] = previous.playerStates[i].pods[1];
            vector<int> passed;
            for (int p = 0; p < POD_COUNT; p++) {
                playerStates[i].pods[p].passedCheckpoints = previous.playerStates[i].pods[p].passedCheckpoints;
                playerStates[i].pods[p].turnsSinceCP = previous.playerStates[i].pods[p].turnsSinceCP;
                playerStates[i].pods[p].turnsSinceShield = previous.playerStates[i].pods[p].turnsSinceShield + 1;
                int previousCP = previous.playerStates[i].pods[p].nextCheckpoint;
                int currentCP = playerStates[i].pods[p].nextCheckpoint;
                int passedCount;
                if (currentCP != previousCP) {
                    // Passed a checkpoint. Progress.
                    playerStates[i].pods[p].turnsSinceCP = 0;
                    passedCount = ++playerStates[i].pods[p].passedCheckpoints;
                } else {
                    passedCount = playerStates[i].pods[p].passedCheckpoints;
                    playerStates[i].pods[p].turnsSinceCP++;
                }
                passed.push_back(passedCount);
            }
            // Update lead pod ID.
            if(passed[0] == passed[1]) {
                PodState& p0 = playerStates[i].pods[0];
                PodState& p1 = playerStates[i].pods[1];
                Vector& cp = race.checkpoints[p0.nextCheckpoint];
                playerStates[i].leadPodID = (cp - p0.pos).getLength() < (cp - p1.pos).getLength() ? 0 : 1;
            } else {
                playerStates[i].leadPodID = passed[0] > passed[1] ? 0 : 1;
            }
        }
    }
    current = GameState(race, playerStates, turn);
    if(turn == 0) {
        for(int i = 0; i < PLAYER_COUNT; i++) {
            for(int j= 0; j < POD_COUNT; j++) {
                current.playerStates[i].pods[j].angle = Physics::angleTo(current.playerStates[i].pods[j].pos, race.checkpoints[1]);
            }
        }
        // Get pod 0 to target enemy 0 so that there are no cross-overs in the path.
        current.ourState().leadPodID = 1;
        current.enemyState().leadPodID = 0;
    }
}
コード例 #16
0
/*
 * Process results of viable move
 */
void MainWindow::processMove(bool waiting) {
    gameState.moveRobots();
    score += gameState.countCollisions() * (POINTS_PER_ROBOT +
                                            (waiting ? WAIT_BONUS : 0));
    gameState.draw(scene);
    displayScore();

    if (!gameState.anyRobotsLeft()) { // won level
        numberOfRobots = std::min(MAX_ROBOTS, numberOfRobots + ROBOTS_INC);
        gameState = GameState(numberOfRobots);
        gameState.draw(scene);
        ++level;
        displayLevel();
    } else if (gameState.heroDead()) { // game over
        gameOver = true;
        gameOverWindow.show();
    }
}
コード例 #17
0
bool GameScreen::init()
{
	if (!Layer::init())
	{
		return false;
	}

	_rootNode = CSLoader::createNode("Screens/MainGame.csb");
	addChild(_rootNode);
	this->scheduleUpdate();

	_platform = (Platform*)_rootNode->getChildByName("platform");
	_platform = Platform::create();
	this->addChild(_platform);

	_powerUp = (PowerUp*)_rootNode->getChildByName("powerup");
	_powerUp = PowerUp::create();
	this->addChild(_powerUp);

	_menuBar = (MenuBar*)_rootNode->getChildByName("menuBar");
	_menuBar = MenuBar::create();
	this->addChild(_menuBar);

	//SPRITES
	InitSprites();
	//Animated Santa Sprite
	InitAnimation();
	//LABELS
	InitLabels();
	//TOUCHES
	InitControls();
	//BUTTONS
	InitButtons();


	// Game is not live until the start button is pressed.
	GameManager::sharedGameManager()->isGameLive = false;
	GameState();

	return true;
}
コード例 #18
0
ファイル: main.cpp プロジェクト: ZachHoefler/Text-Adventure
int main()
{
	// Load in game data
	std::unique_ptr<IDungeonBuilder> dungeonBuilder = 
		std::unique_ptr<IDungeonBuilder>(new StandardDungeonBuilder());

	std::shared_ptr<IDungeon> dungeon = CreateDungeonFromXml(L"Content\\adventure.xml", *dungeonBuilder);

	// Start up main game loop
	GameState gameState = GameState();
	gameState.Initialize();
	gameState.BeginDungeon(dungeon);

	bool stillPlaying = true;
	while (stillPlaying)
	{
		stillPlaying = gameState.RunGameLoopStep();
	}

	return 0;
}
コード例 #19
0
vector<AStarNode> AStarNode::getChildNodesForNode(AStarNode node){
    SudokuGameEngine engine = SudokuGameEngine();
    vector<Action> actions = engine.getPossibleActionsForState(node.getState());
    vector<AStarNode> children;
    
   
    
    for (Action action : actions) {
        children.push_back(AStarNode (node.getCorrectness(),
                                      GameState (engine.takeActionForState(action, node.getState()))
                                                 , &action, &node));
    }
    
    for (AStarNode child : children) {
        int correctness = 0;
        for (Action action : actions)
            if (action.getRow() == child.getAction().getRow() && action.getCol() == child.getAction().getCol())
                correctness++;
        child.setCorrectness(correctness + child.getPreviousNode().getCorrectness());

    }
    
    return children;
}
コード例 #20
0
IntermediateGameState IntermediateGameState::new_game() {
    return IntermediateGameState(GameState(PACMAN_NODES.get_spawn(), GHOST_NODES.get_spawns()));
}
コード例 #21
0
void BabylonCounter::start_counting()
{
	GameState root_game = GameState();
	explore_children(root_game, 0);
}
コード例 #22
0
ファイル: main.cpp プロジェクト: ricardaotsi/MultiplayerPong
int main(int argc, char* argv[])
{
	if(init()== false)
		clean_up();
	load_files();

	ClientTcp sock;
	sock.init();
	GameState gState = GameState();

	//variáveis para controle do tempo
	float deltaTime = 0.0;
    float thisTime = 0;
    float lastTime = 0;

	//chars para mostrar os pontos na tela
	char *msg ="Pontos: ";
	char *ponto="";

	//char para enviar mensagem pro servidor
	char buffer[512];

	char* ip=new CHAR();
	char* porta=new CHAR();
	bool quit = false;
	char bufferrecv[512];

	while (quit == false)
	{
		thisTime = SDL_GetTicks();
		deltaTime = (float)(thisTime - lastTime) / 1000;
		lastTime = thisTime;

		//controle para sair do jogo
		while( SDL_PollEvent( &event ) )
        {
            if( event.type == SDL_QUIT )
            {
                quit = true;
            } 
			if( event.type == SDL_KEYDOWN )
			{
				switch( event.key.keysym.sym )
				{
				case SDLK_ESCAPE:
						quit=true;
						break;
				}
			}
		}
		
		//loop principal
		switch (estadoAtual)
		{
		//menu do jogo
		case menu:
			message = TTF_RenderText_Solid( font, "Conecte pela linha de comando", textColor );
			desenhar(w/2-message->w/2,h/2-message->h/2,message,screen);
			SDL_Flip(screen);
			//recebe variáveis para conexão
			// Descomentar para ser possível digitar o ip e a porta
			/*printf("Digite o ip: \n");
			std::cin>> ip;
			printf("Digite a porta: \n");
			std::cin>> porta;*/
			// sock.criaSock(ip,porta);
			sock.criaSock("127.0.0.1", "2222");
			if(sock.recebeMsg(bufferrecv, sizeof(bufferrecv), gState) == 1)
			{
				estadoAtual = jogando;
				printf("Conexao feita jogo inicio \n");
				//sock.nBlock();
			}
			break;

		//loop  do jogo
		case jogando:
			/*message = TTF_RenderText_Solid( font, msg, textColor );
			desenhar(30,20,message,screen);
			desenhar(w-message->w-50,20,message,screen);
			message = TTF_RenderText_Solid( font, itoa(j1.ponto,ponto,10), textColor );
			desenhar(140,20,message,screen);
			message = TTF_RenderText_Solid( font, itoa(j2.ponto,ponto,10), textColor );
			desenhar(w-message->w-30,20,message,screen);*/
			if( event.type == SDL_KEYDOWN )
			{
				/*switch( event.key.keysym.sym )
				{
				case SDLK_UP:
					sprintf(buffer,"%f;%d;%s;",deltaTime, 200,"up");
					sock.mandaMsg(buffer);
					break;
				case SDLK_DOWN:
					sprintf(buffer,"%f;%d;%s;",deltaTime, 200,"down");
					sock.mandaMsg(buffer);
					break;
				}*/
				if(event.key.keysym.sym == SDLK_UP)
				{
					sprintf(buffer,"%f;%d;%s;",deltaTime, 200,"up");
					sock.mandaMsg(buffer);
				}else if(event.key.keysym.sym == SDLK_DOWN){
					sprintf(buffer,"%f;%d;%s;",deltaTime, 200,"down");
					sock.mandaMsg(buffer);
				}

			}
			sock.recebeMsg(bufferrecv, sizeof(bufferrecv), gState);
			desenhar(gState.j1->posP.x, gState.j1->posP.y, tileP, screen);
			desenhar(gState.j2->posP.x, gState.j2->posP.y, tileP, screen);
			desenhar(gState.bola->posB.x, gState.bola->posB.y, tileB, screen);
			break;

		//fim do jogo
		case fim:
			if(gState.j1->ponto == 10)
			{
				message = TTF_RenderText_Solid( font, "You Win!!", textColor );
				desenhar(w/2-message->w/2,h/2,message,screen);
			}else
				message = TTF_RenderText_Solid( font, "Game Over", textColor );
				desenhar(w/2-message->w/2,h/2,message,screen);
			break;
		}
		SDL_Flip(screen);
		SDL_FillRect(screen,0,0);
		
		//verificação de frames
		if(thisTime < 1000 / FRAMES_PER_SECOND )
		{
			SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - thisTime );
		}
	}
	clean_up();
	return 0;
}
コード例 #23
0
Multiplayer::Multiplayer(InjectionContainer * container)
    : GameScene(container), packetData(GameState(playerOne, playerTwo, pong))
{
    container->query(&client, &server);
}
コード例 #24
0
ファイル: Engine.cpp プロジェクト: robert1990/COMP345_risk
Engine::Engine()
{
    cout << "Assignment: creating engine and game state" << endl;
    gameState = GameState("Person"); // maybe ask the user for his name?
    startPhase();
}
コード例 #25
0
void Controller::setServerName( std::string name )
{
    GameState stateChange = GameState();
    stateChange.set_name(name);
}