void CPrivilagedInfoCallback::pickAllowedArtsSet(std::vector<const CArtifact*> &out) { for (int j = 0; j < 3 ; j++) out.push_back(VLC->arth->artifacts[VLC->arth->pickRandomArtifact(gameState()->getRandomGenerator(), CArtifact::ART_TREASURE)]); for (int j = 0; j < 3 ; j++) out.push_back(VLC->arth->artifacts[VLC->arth->pickRandomArtifact(gameState()->getRandomGenerator(), CArtifact::ART_MINOR)]); out.push_back(VLC->arth->artifacts[VLC->arth->pickRandomArtifact(gameState()->getRandomGenerator(), CArtifact::ART_MAJOR)]); }
void playGameAgainst(Agent *agent0, Agent *agent1) { GameRules rules(4); vector<Agent *> players{agent1, agent0}; unsigned curIndex = 0; // rand()%players.size(); uptr<State> gameState(GameState::NewEmptyGameState(4, 4)); while (true) { Agent *curPlayer = players[curIndex]; uptr<Action> action = curPlayer->ChooseAction(gameState.get()); uptr<State> successor = gameState->SuccessorState(*action); bool isWin = rules.IsWin(*successor); bool isFinished = rules.IsTerminalState(*successor); if (isWin || isFinished) { cout << "end of game!" << endl; if (isWin) { cout << "player" << curIndex << " is the winner" << endl; } else { cout << "its a draw" << endl; } successor->Output(cout); break; } gameState = successor->Clone(); static_cast<GameState *>(gameState.get())->FlipState(); // TODO: this is a bit hacky. curIndex = (curIndex + 1) % players.size(); } }
void Dealer::showDiscardedToPlayers() { GameState gstat = gameState(); for (int i = 1; i < numberOfPlayingPlayers; i++) { players[(turn + i) % numberOfPlayingPlayers]->approve(gstat); } return; }
void GameScene::advance() { if(gameState() == GameRunning) { currentTime = time.elapsed(); if(firstStep) { m_dt = 0; firstStep = false; } else { m_dt = timeFactor() * (currentTime - lastFrameTime) / 1000.0; } if(m_dt > 0.01) { m_dt = 0.01; } if(gameMode() == ModeParty) { checkAddSpecialParticle(); } #ifdef BENCHMARK dtSum += realDt; if(frameNumber == 99) { qDebug() << "FPS: " << frameNumber / dtSum; dtSum = 0; frameNumber = 0; } frameNumber++; #endif QGraphicsScene::advance(); lastFrameTime = currentTime; } }
const Process::Return GameLoadingProcess::update(const float deltaTime) { StateManager& stateManager(StateManager::instance()); GameState* gameState(stateManager.getState<GameState>("GameState")); assert(gameState); EntitySystem& entitySystem(EntitySystem::instance()); PlayerShip* playerShip(entitySystem.add<PlayerShip>("Player")); playerShip->setGraphicObject(new SDLGraphicObject); playerShip->writeGraphicObject<SDLGraphicObject>().load("data/playership.bmp"); playerShip->setInputObject(new SDLInputObject(playerShip)); playerShip->writeInputObject<SDLInputObject>().setup(); playerShip->writePosition() = Vector2D(300.0F, 200.0F); playerShip->setMass(3.0F); //playerShip->writeVelocity() = Vector2D(100.0F, 300.0F); entitySystem.addToList(playerShip, "Renderable"); entitySystem.addToList(playerShip, "Collidable"); entitySystem.addToList(playerShip, "Movable"); entitySystem.addToList(playerShip, "Ship"); Bullet* enemyShip(entitySystem.add<Bullet>("Renderable")); enemyShip->setGraphicObject(new SDLGraphicObject); enemyShip->writeGraphicObject<SDLGraphicObject>().load("data/enemy.bmp"); enemyShip->writePosition() = Vector2D(150.0F, 300.0F); enemyShip->setMass(3.0F); entitySystem.addToList(enemyShip, "Movable"); //entitySystem.addToList(enemyShip, "Ship"); GrappleHook* grapple(entitySystem.add<GrappleHook>("Renderable")); grapple->setGraphicObject(new SDLGraphicObject); grapple->writeGraphicObject<SDLGraphicObject>().load("data/hook.bmp"); grapple->setSource(playerShip); grapple->setTarget(enemyShip); for (Uint segment(0U); segment < 10U; ++segment) { HookSegment* hookSegment(entitySystem.add<HookSegment>("Renderable")); hookSegment->setGraphicObject(new SDLGraphicObject); hookSegment->writeGraphicObject<SDLGraphicObject>().load("data/segment.bmp"); grapple->addSegment(hookSegment); } entitySystem.addToList(grapple, "Grapple"); grapple->setSpeed(100.0F); grapple->writePosition() = playerShip->readPosition(); grapple->fire(); std::vector<Process*> processList; processList.push_back(new GameInputProcess); processList.push_back(new GamePhysicsProcess); processList.push_back(new GameRenderProcess); gameState->setProcessor(new Processor(processList)); return Process::STOP; }
void GameScene::pauseGame() { qDebug() << "Game paused"; if(gameState() == GameRunning) { menuTime.restart(); // start the timer that will avoid clicking on the quit button after level up or failed } // pause timer levelTimer->stop(); // Stop the timer to save CPU power (hopefully this won't lock up anything else) advanceTimer.stop(); // end animation }
void GameScene::continueGame() { if(gameState() == GameOver) { setLevel(m_level); } // start timer levelTimer->start(); // start the main timer as well (start using CPU again) advanceTimer.start(); qDebug() << "Game continued"; }
score EvaluationModule::aimAtTeamMate(Robot::robotID shootingRobotID, Robot::robotID goalRobotID, double * rotationToTarget){ GameStatePtr gameState( new GameState() ); if( video.updateGameState( gameState ) < 0){ std::ostringstream s; s<<__FILE__<<":"<<__LINE__; throw SimulationException( s.str() ); } score score_ = 0; Pose shootingRobotPose=gameState->getRobotPos( shootingRobotID ); Pose goalRobotPose=gameState->getRobotPos( goalRobotID ); //obliczam wspolrzedna srodka robota do ktorego kierowane jest podanie w ukladzie wsp zw z robotem strzelajacym RotationMatrix rm( shootingRobotPose.get<2>() ); Pose recvPassRelPos = goalRobotPose.transform( shootingRobotPose.getPosition() , rm ); if( rotationToTarget ) *rotationToTarget = calculateProperAngleToTarget( shootingRobotPose, goalRobotPose ); //jesli wsp x jest bliska 0 i roboty maja przeciwna rotace to mozna zrealizowac podanie if( pow(recvPassRelPos.get<0>(),2) < 0.05*recvPassRelPos.get<1>() ){ //roboty maja rotacje odpowiednia do siebie gdy roznica jest rowna -M_PI //double deviation = pow( fabs( shootingRobotPose.get<2>() - goalRobotPose.get<2>() ) - M_PI, 2 ) ; double deviation = fabs( shootingRobotPose.get<2>() - goalRobotPose.get<2>() ) - M_PI ; double threshold = 0.1*recvPassRelPos.get<1>(); if( deviation < threshold ){// 4 stopnie LOG_DEBUG( log," mozna podac deviation="<<deviation<<" threshold "<<threshold ); //std::cout<<" mozna podac deviation="<<deviation<<std::endl; score_ = 1.0 - deviation; } else{ LOG_INFO(log, "deviation "<<deviation ); LOG_INFO(log, "shootingRobotPose.get<2>() "<<shootingRobotPose.get<2>()<<" goalRobotPose.get<2>() "<< goalRobotPose.get<2>() ); } } else{ if(rotationToTarget){ LOG_INFO(log, "!!!!!!!!! bad recvPassRelPos "<<recvPassRelPos<<" rotationToTarget "<<*rotationToTarget<<" currRotation "<<shootingRobotPose.get<2>() ); } else{ LOG_INFO(log, "!!!!!!!!! bad recvPassRelPos "<<recvPassRelPos<<" currRotation "<<shootingRobotPose.get<2>() ) } } return score_; }
int UltimateTicTacToeMontecarloAI::simulate(Board board, int const previousMove, int const player) const { int turn = previousMove > 0 ? otherPlayer(board.grids.at(previousMove)) : player; GameState state = gameState(board, player); Move prev = previousMove; while(state == GameState::UNRESOLVED) { Moves options = movementOptions(board, prev); Move option = options.at(qrand() % options.size()); playMove(board, option, turn); turn = otherPlayer(turn); state = gameState(board, player); prev = option; } switch(state) { case GameState::WIN: return 1; case GameState::LOSE: return -1; default: return 0; } }
void GameManager::Run() { while(m_window.isOpen()) { switch(m_state) { case State::GAME: { GameState gameState(m_window, m_state); gameState.Run(); break; } case State::END: { m_window.close(); } } } }
bool Board::makeMove(int xCoord, int yCoord, char player) { // check if location is unoccupied and game is not a draw if(gameBoard[xCoord][yCoord] == '.' && gameState() == in_progress) { // check whose turn it is if(player == 'x' || player == 'X') { gameBoard[xCoord][yCoord] = 'x'; } else if(player == 'o' || player == 'O') { gameBoard[xCoord][yCoord] = 'o'; } return true; } // location is occupied return false; }
void CGameEngine::initGame() { try{ boost::property_tree::ptree levelRoot; read_info("data\\test_level.info", levelRoot); CLevelLoader::load(levelRoot, m_level,m_resourceEngine); } catch(boost::property_tree::ptree_error &e){ CLog::error(e.what()); } m_level->setSpeed(100.0f); boost::shared_ptr<CPlayGameState> gameState(new CPlayGameState()); pushState(gameState); boost::shared_ptr<CWaitState> waitState(new CWaitState()); pushState(waitState); m_isRunning=true; }
int main(int argc, char *argv[]) { int width = 640; int height = 480; if (SDL_Init(SDL_INIT_VIDEO) != 0) { return 1; } if (TTF_Init() == -1) { printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError()); return 2; } atexit(SDL_Quit); const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo(); if (videoInfo) { width = videoInfo->current_w; height = videoInfo->current_h; } SDL_Surface* screen = SDL_SetVideoMode(width, height, 0, SDL_HWSURFACE | SDL_FULLSCREEN | SDL_DOUBLEBUF); reflexgame::Renderer renderer(screen); reflexgame::GameState gameState(width, height); if (screen == NULL) return 2; SDL_ShowCursor(0); SDL_WM_GrabInput(SDL_GRAB_ON); Uint32 nextTime = 0; time_left(nextTime); gameState.start(); while(true) { gameState.handleTick(); if (gameState.gameEnded()) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_ESCAPE: return 0; break; default: break; } case SDL_QUIT: return 0; default: break; } } renderer.drawEndGame(gameState); } else { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type){ case SDL_MOUSEBUTTONDOWN: { if (event.button.button == SDL_BUTTON_LEFT) { int x = event.button.x; int y = event.button.y; printf("Click at (%d, %d)\n", x, y); gameState.attackAt(x, y); } break; } case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_ESCAPE: return 0; break; default: break; } case SDL_QUIT: return 0; default: break; } } renderer.draw(gameState); } SDL_Flip(screen); SDL_Delay(time_left(nextTime)); } return 0; }
int main(int argc, char* argv[]) { // Parse arguments // First param is the name of the program being run // (due to call: mpirun -np 2 program-name // tmp bs std::unordered_map<std::string, std::string> test = Mcts::Parsers::ChessGame::LoadChessBoard( "/home/agondek/GUT/GUT_Manycore_Architectures_MCTS/distributed-implementation/example_input.txt"); Mcts::GameStates::ChessGameState gameState(2, test); // Initialize the MPI environment MPI_Init(NULL, NULL); // Get the number of processes int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); // Get the rank of the process int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); // IMPORTANT!: if number of _chips mod (k + 1) == 0, second player should win (optimal) // Where k is the maximum number of _chips allowed to draw at once // Uncomment to present a valid game // Mcts::GameStates::NimGameState gameState(2,400); // Mcts::GameStates::NimGameState gameState(MCTS_PLAYER_TWO_ID, 400); bool finished = false; while (!gameState.getAvailableActions().empty()) { if(world_rank == 0) { std::cout << "Board before taking move:" << std::endl; std::cout << gameState.getGameRepresentation() << std::endl; } std::string action; if (gameState.getLastActivePlayer() == MCTS_PLAYER_ONE_ID) { // Last player was no 1, so it's player 2 turn action = Mcts::Playouts::getBestMoveUsingUtcSort(&gameState, 20, false, finished); } else { // Last player was no 2 so it's player 1 turn action = Mcts::Playouts::getBestMoveUsingUtcSort(&gameState, 20, true, finished); } if(world_rank == 0) { std::cout << "Player: " << 3 - gameState.getLastActivePlayer() << " takes his best move: " << action << std::endl; } if(action != MCTS_ACTION_NOT_AVAILABLE) { gameState.performAction(action); if(world_rank == 0) { std::cout << "Board after taking move:" << std::endl; std::cout << gameState.getGameRepresentation() << std::endl; } } } if(world_rank == 0) { if (gameState.getStateValue(gameState.getLastActivePlayer()) == MCTS_PLAYER_ONE_ID) { std::cout << gameState.getLastActivePlayer() << " wins" << std::endl; } else { std::cout << 3 - gameState.getLastActivePlayer() << " wins" << std::endl; } } // Finalize the MPI environment. MPI_Finalize(); return 0; }
int UltimateTicTacToeMontecarloAI::realThink(const UltimateTicTacToeMontecarloAI::Board &board, const int previousMove, const int player) const { //printBoard(board); if(maxIterations == 0) { Moves options = movementOptions(board, previousMove); return options.at(qrand() % options.size()); } //qint64 now = QDateTime::currentMSecsSinceEpoch(); //qDebug() << "c: " << c << ", maxIterations: " << maxIterations << ", maxChildren: " <<maxChildren; Nodes nodes; nodes.reserve(maxIterations * maxChildren); nodes.append(Node { 0, 1, board, previousMove, -1, Node::Children() }); int i; for(i = 0; i < maxIterations; ++i) { int leafIndex = select(nodes); Node const& leaf = nodes.at(leafIndex); GameState leafState = gameState(leaf.board, player); if(leafState == GameState::WIN) { /* qDebug() << "---"; printBoard(leaf.board); */ break; } else if(leafState == GameState::LOSE) { backpropagate(leafIndex, nodes, -10); } else if(leafState == GameState::TIE) { backpropagate(leafIndex, nodes, -5); } else if(leafState == GameState::UNRESOLVED) { int nodeIndex = expand(leafIndex, nodes, player); Node const& node = nodes.at(nodeIndex); int score = simulate(node.board, node.previousMove, player); backpropagate(nodeIndex, nodes, score); } } //qDebug() << "Found solution in " << i + 1 << " iterations"; Node const& root = nodes.at(0); int bestChildIndex = pickBestChild(root, nodes, false); Node const& bestChild = nodes.at(bestChildIndex); //qDebug() << "AI took " << (QDateTime::currentMSecsSinceEpoch() - now) << " ms"; /*for(int childIndex : root.children) { Node const& child = nodes.at(childIndex); qDebug() << child.previousMove << ":" << child.v << child.n; }*/ //qDebug() << bestChild.previousMove / 9 << bestChild.previousMove %9; return bestChild.previousMove; }
void check_mouse(XEvent *e, Game *game) { static int savex = 0; static int savey = 0; static int n = 0; Audio *a; a = &game->sounds; if (e->type == ButtonRelease) { return; } if (e->type == ButtonPress && lvlState(game) < 0) { //LEFT-CLICK if (e->xbutton.button==1) { //Left button was pressed int y = WINDOW_HEIGHT - e->xbutton.y; //Check game state when LEFT-clicking if (gameState(game) == 1 || gameState(game) == 2) { a->playAudio(30); menuClick(game); a->playAudio(32); } else if (gameState(game) == 0) { // JBC Added 5/30 to only make defense // missiles and play sound when enemy // missiles are present if ((game->nmissiles > 0 || game->nsmissiles > 0) && game->defMissilesRemaining > 0) { makeDefenseMissile(game, e->xbutton.x, y); a->playAudio(20); game->defMissilesRemainingAfterLevel = game->defMissilesRemaining; } } return; } //RIGHT-CLICK if (e->xbutton.button==3) { //Check game state when RIGHT-clicking if (gameState(game) == 1) { //Menu functions } else if (gameState(game) == 0) { //Game Functions // fireDefenseMissile(game); // JBC idea to add menu pop up for right-click game->gState ^= 1; } return; } } //Did the mouse move? if (savex != e->xbutton.x || savey != e->xbutton.y) { savex = e->xbutton.x; savey = e->xbutton.y; int y = WINDOW_HEIGHT - e->xbutton.y; if (++n < 10) return; if (gameState(game) == 1 || gameState(game) == 2) { //Menu Functions mouseOver(savex, y, game); } else if (gameState(game) == 0) { //Game Functions if (game->lcm) lastCityMode(savex, y, game); // JBC note 5/13 // moved the "particle" stuff out of here // makeParticle(game, e->xbutton.x, y); } } }
int main(void) { int done=0; srand(time(NULL)); initXWindows(); init_opengl(); //declare game object Game game; game.numberDefenseMissiles=0; //JG game.nparticles=MAX_PARTICLES; game.numberDefenseMissiles=0; // JBC 5/19/16 // added globally accesible defMissileSpeed so that we can // change it dynamically game.defMissileSpeed = 10; initStruc(&game); //Structures sh; //Changed call for function prototype 5-17-16 -DT createEMissiles(&game, 0, 0); initRadar(&game); initUFO(&game); initHighScores(&game); //JR - Menu Object Shapes and Locations drawMenu(&game); drawSettings(&game); game.sounds.loadAudio(); //start animation while (!done) { int state = gameState(&game); while (XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); check_mouse(&e, &game); done = check_keys(&e, &game); } if (state == 1) { render_menu(&game); } else if (state == 2) { drawSettings(&game); render_settings(&game); } else if (state == 3) { render_newgame(&game); } else if (state == 0 || state == 5) { if (lvlState(&game) < 0) { movement(&game); render(&game); } if (lvlState(&game) == 1) { levelEnd(&game); } } else { render_gameover(&game); } glXSwapBuffers(dpy, win); } cleanupXWindows(); return 0; }
BallState::ballState EvaluationModule::getBallState(Robot::robotID id, bool * iAmCloserToBall ){ GameStatePtr gameState( new GameState() ); if( video.updateGameState( gameState ) < 0){ std::ostringstream s; s<<__FILE__<<":"<<__LINE__; throw SimulationException( s.str() ); } const std::vector<std::string> blueTeam=Config::getInstance().getBlueTeam(); BallState::ballState bs=BallState::free; BallState::ballState ballState_=BallState::free; Pose p; Pose ballPose = gameState->getBallPos(); //pobierz ostatni stan z servera wideo, //wazne w przypadku autu badz zdobycia bramki ballState_ = gameState->getBallState();//getBallState( ballPose.getPosition() ); if( ballState_ != BallState::free){ //LOG_FATAL( log,"Ball state is "<<ballState_ ); LOG_FATAL( log,"Ball 123position is "<<ballPose<<" ballState "<<ballState_ ); return ballState_; } if( Robot::isBlue( id ) ){ bs = BallState::occupied_our; } else bs = BallState::occupied_theirs; double distanceToBall; double angleToBall; //dla kazdego robota z naszej druzyny sprawdz czy nie jest posiadaczem pilki //dla kazdego robota z druzyny przeciwnej sprawdz czy nie jest posiadaczem pilki //odleglosc najblizszego robota do pilki double shortestDistance = numeric_limits<double>::max( ); Robot::robotID closerToBallRobotID; Robot::robotID robotID; BOOST_FOREACH(std::string modelName,blueTeam){ robotID = Robot::getRobotID( modelName); p = gameState->getRobotPos( robotID ); //if( p.distance(ballPose) < ( Config::getInstance().getRobotMainCylinderRadious() + 0.04 ) ){ if( this->isRobotOwnedBall( Robot::getRobotID( modelName ), gameState , distanceToBall, angleToBall ) ){ ballState_ = bs; if( Robot::getRobotID( modelName) == id ) return BallState::mine; else return ballState_; } if( distanceToBall < shortestDistance ){ shortestDistance=distanceToBall; closerToBallRobotID = robotID; } }