Exemple #1
0
CORE_USE_NAMESPACE

ButtonSprite::ButtonSprite(std::string const &buttonSprite,
			   std::string const &buttonSelectedSprite,
			   std::string const &buttonClickedSprite)
  : _defaultName(buttonSprite), _selected(buttonSelectedSprite), _clicked(buttonClickedSprite), _state(ButtonSprite::DEFAULT)
{
  GameState *gameState = &(GameStateManager::get().getCurrentState());

  this->_defaultSprite = gameState->getSprite(buttonSprite);
  this->_selectedSprite = gameState->getSprite(buttonSelectedSprite);
  this->_clickedSprite = gameState->getSprite(buttonClickedSprite);

  gameState->getGUI().registerButtonSprite(*this);
}
Exemple #2
0
Game::~Game()
{
	activeStates.clear();
	std::map<StateId, GameState*>::iterator itr;
	for (itr = states.begin(); itr != states.end(); itr++){
		GameState* state = itr->second;
		std::cout << "deleting " << state->ToString() << std::endl;
		delete state;
	}
	states.clear();


	system("PAUSE");

}
void GameStateManager::update()
{
	if( !stateStack.empty() )
	{
		GameState* state = stateStack.front();
		state->onUpdate();
	}

	// Remove any dead states
	for( auto state : deadStates )
	{
		delete state;
	}
	deadStates.clear();
}
void ProcessTimer::execute()
{
    ORWELL_LOG_TRACE("ProcessTimer::execute : broadcast Gamestate");

    GameState aGameState;
    aGameState.set_playing(m_game->getIsRunning());

    if (m_game->getWinner())
    {
        aGameState.set_winner(*m_game->getWinner());
    }

    RawMessage aMessage("all_clients", "GameState", aGameState.SerializeAsString());
    m_publisher->send( aMessage );
}
Exemple #5
0
int startGame()
{
	Timer fpsTimer;
	if (initializeSDL() == -1) 
	{
		exit(-1);
	}
	else
	{
		//Create window
		if (GameEngine::getInstance().init() == Mario::STATUS_FATAL) 
		{
			exit(Mario::STATUS_FATAL);
		}
		else
		{
			while( GameEngine::getInstance().getStateId() != STATE_EXIT ) 
			{		
				fpsTimer.start();
				
				GameState* state = GameEngine::getInstance().getState();
				
				state->handle_events();

				state->logic();
				
				state->render();
				
				GameEngine::getInstance().changeState();

				refreshScreen();

				if (fpsTimer.getTicks() < Mario::UPDATE_RATE )
				{
					SDL_Delay ( Mario::UPDATE_RATE - fpsTimer.getTicks() );
				}
			}
		}
	}

	GameEngine::getInstance().shutdown();
	
	//Quit SDL subsystems
	IMG_Quit();
	SDL_Quit();

	return 0;
}
Exemple #6
0
  StateResult ActionWield::doPreBeginWorkNVI(GameState& gameState, Systems::Manager& systems, json& arguments)
  {
    std::string message;
    auto subject = getSubject();
    auto object = getObject();
    auto& components = gameState.components();
    auto& narrator = systems.narrator();

    /// @todo Support wielding in other prehensile limb(s). This will also include
    ///       shifting an already-wielded weapon to another hand.
    m_bodyLocation = { BodyPart::Hand, 0 };
    EntityId currentlyWielded = components.bodyparts[subject].getWieldedEntity(m_bodyLocation);

    std::string bodypartDesc = narrator.getBodypartDescription(subject, m_bodyLocation);

    // If it is us, or it is what is already being wielded, it means to unwield whatever is wielded.
    if ((object == subject) || (object == currentlyWielded) || (object == EntityId::Void))
    {
      std::unique_ptr<Action> unwieldAction(NEW ActionUnwield(subject));
      systems.director().queueEntityAction(subject, std::move(unwieldAction));

      return StateResult::Failure();
    }
    else if (currentlyWielded != EntityId::Void)
    {
      arguments["bodypart"] = bodypartDesc;
      putMsg(narrator.makeTr("YOU_MUST_UNWIELD_FIRST", arguments));
      return StateResult::Failure();
    }

    return StateResult::Success();
  }
int explore_game(const GameState &starting)
{
   // If the starting condition is not in the game, abort 
   if (starting.isValid()==false) return 0;
   
   std::set<GameState> known; // states already visited
   std::set<GameState> to_explore; // states to play 
   std::set<GameState> leafs; // novel states reached from states in to_explore
   
   to_explore.insert(starting); // add the starting state to the states to explore
   
   bool useful = true;
   int rounds = 0;
   
   while (true)
   {
      useful = explore_game2(known,to_explore,leafs,rounds); // make one iteration
      rounds++; 
      if (useful==false) break;
      
      known.insert(to_explore.begin(),to_explore.end()); // add explored states to known states
      
      std::swap(to_explore,leafs); // swap leafs into to_explore for next round
      std::set<GameState> empty;
      std::swap(leafs,empty); // empty the list of leaf states      
   }
   
   // the number of iterations before we reached an end-game state
   return rounds;
}
Exemple #8
0
void StateHandler::setupGui(void){

	GameState * titleScreen = new GuiTitleScreen(this, window);
	states.push_back(titleScreen);

	GameState * matchSetup = new MatchSetup(this, window);
	states.push_back(matchSetup);

	GameState * battleState = new BattleState(this, window);
	states.push_back(battleState);

	currentState = titleScreen;

	std::vector<int> args;
	titleScreen->callState(args);
}
Exemple #9
0
vector<Point> GetReachableSquares(
    const GameState& game_state, const Point& start, int n, int k) {
  vector<Point> result;
  unordered_set<Point> visited{start};
  unique_ptr<vector<Point>> queue(new vector<Point>{start});
  for (int i = 0; i < k; i++) {
    unique_ptr<vector<Point>> next(new vector<Point>);
    for (const Point& square : *queue) {
      for (const Point& move : kKingMoves) {
        const Point neighbor = square + move;
        if (visited.find(neighbor) == visited.end()) {
          visited.insert(neighbor);
          if (!game_state.map->IsSquareBlocked(neighbor) &&
              !game_state.IsSquareOccupied(neighbor)) {
            result.push_back(neighbor);
            next->push_back(neighbor);
          }
        }
      }
    }
    queue = std::move(next);
    if (result.size() > n) {
      break;
    }
  }
  return result;
}
Exemple #10
0
IDriverDependantBitmap* prepare_screen_for_transition_in()
{
    if (saved_viewport_bitmap == NULL)
        quit("Crossfade: buffer is null attempting transition");

    saved_viewport_bitmap = ReplaceBitmapWithSupportedFormat(saved_viewport_bitmap);
    const Rect &viewport = play.GetMainViewport();
    if (saved_viewport_bitmap->GetHeight() < viewport.GetHeight())
    {
        Bitmap *enlargedBuffer = BitmapHelper::CreateBitmap(saved_viewport_bitmap->GetWidth(), viewport.GetHeight(), saved_viewport_bitmap->GetColorDepth());
        enlargedBuffer->Blit(saved_viewport_bitmap, 0, 0, 0, (viewport.GetHeight() - saved_viewport_bitmap->GetHeight()) / 2, saved_viewport_bitmap->GetWidth(), saved_viewport_bitmap->GetHeight());
        delete saved_viewport_bitmap;
        saved_viewport_bitmap = enlargedBuffer;
    }
    else if (saved_viewport_bitmap->GetHeight() > viewport.GetHeight())
    {
        Bitmap *clippedBuffer = BitmapHelper::CreateBitmap(saved_viewport_bitmap->GetWidth(), viewport.GetHeight(), saved_viewport_bitmap->GetColorDepth());
        clippedBuffer->Blit(saved_viewport_bitmap, 0, (saved_viewport_bitmap->GetHeight() - viewport.GetHeight()) / 2, 0, 0, saved_viewport_bitmap->GetWidth(), saved_viewport_bitmap->GetHeight());
        delete saved_viewport_bitmap;
        saved_viewport_bitmap = clippedBuffer;
    }
    saved_viewport_bitmap->Acquire();
    IDriverDependantBitmap *ddb = gfxDriver->CreateDDBFromBitmap(saved_viewport_bitmap, false);
    return ddb;
}
Exemple #11
0
void current_fade_out_effect () {
    if (pl_run_plugin_hooks(AGSE_TRANSITIONOUT, 0))
        return;

    // get the screen transition type
    int theTransition = play.fade_effect;
    // was a temporary transition selected? if so, use it
    if (play.next_screen_transition >= 0)
        theTransition = play.next_screen_transition;

    if ((theTransition == FADE_INSTANT) || (play.screen_tint >= 0)) {
        if (!play.keep_screen_during_instant_transition)
            set_palette_range(black_palette, 0, 255, 0);
    }
    else if (theTransition == FADE_NORMAL)
    {
        my_fade_out(5);
    }
    else if (theTransition == FADE_BOXOUT) 
    {
        gfxDriver->BoxOutEffect(true, 16, 1000 / GetGameSpeed());
        play.screen_is_faded_out = 1;
    }
    else 
    {
        get_palette(old_palette);
        const Rect &viewport = play.GetMainViewport();
        saved_viewport_bitmap = CopyScreenIntoBitmap(viewport.GetWidth(), viewport.GetHeight());
    }
}
Exemple #12
0
ScriptUserObject* Screen_ScreenToRoomPoint(int scrx, int scry)
{
    VpPoint vpt = play.ScreenToRoom(scrx, scry);
    if (vpt.second < 0)
        return NULL;
    return ScriptStructHelpers::CreatePoint(vpt.first.X, vpt.first.Y);
}
// todo: also have an acceleration phase to allow for more precise, smaller
// movements
void SpecialMoveDetectionAspect::step(GameState & gs, float deltaT) {
	// store a list of recent moves and compare them with the possible patterns uha...

	// iterate all players
	for (PlayerData & pd : gs.getPlayers()) {

		util::initMap(m_inputs, pd.Id);
		if (util::initMap(m_reports, pd.Id)) {
			// has been newly added, initialize it !
			initReport(m_reports[pd.Id]);
		}

		PlayerInput & inp = m_inputs[pd.Id];
		PlayerReport & rep = m_reports[pd.Id];

		if (inp.m_inputRecord.size() != 0)
			inp.m_inputRecord.get(0).Duration += deltaT;

		while (true) {
			InputItem newIt = extractInputItem(gs, rep, pd.Id);

			if (!newIt.isDefined())
				break;

			//logging::Info() << "Got new input pattern: " << newIt;
			inp.m_inputRecord.push(newIt);
			analyzeRingBuffer(gs, inp.m_inputRecord, pd.Id);

			inp.m_activeInputItem = newIt;
		}
	}

}
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;
}
void UnitScriptData::calculateMoves(const IDType & player, MoveArray & moves, GameState & state, std::vector<Action> & moveVec)
{
    // generate all script moves for this player at this state and store them in allScriptMoves
    for (size_t scriptIndex(0); scriptIndex<_scriptVec[player].size(); ++scriptIndex)
    {
        // get the associated player pointer
        const PlayerPtr & pp = getPlayerPtr(player, scriptIndex);

        // get the actual script we are working with
        const IDType actualScript = getScript(player, scriptIndex);

        // generate the moves inside the appropriate vector
        getMoves(player, actualScript).clear();
        pp->getMoves(state, moves, getMoves(player, actualScript));
    }

    // for each unit the player has to move, populate the move vector with the appropriate script move
    for (size_t unitIndex(0); unitIndex < moves.numUnits(); ++unitIndex)
    {
        // the unit from the state
        const Unit & unit = state.getUnit(player, unitIndex);

        // the move it would choose to do based on its associated script preference
        Action unitMove = getMove(player, unitIndex, getUnitScript(unit));

        // put the unit into the move vector
        moveVec.push_back(unitMove);
    }
}
Input AIManager::getInput(unsigned int playerNum, GameState state)
{
	indexOfGoldenBuggy = state.getGoldenBuggyID();

	return getInput(playerNum);

}
Exemple #17
0
int Game::run() {
	int v = 0;
	while(states.size() > 0) {
		GameState* gs = states.back();
		states.pop_back();
		//cout << "Loading " << gs->getName() << "...";
		//if( gs->load(this) == 0) {
		//	cout << "done!" << endl;
			v = gs->run();
			if(v)
				return v;
		//} else
		//	cout << "Failed!" << endl;
	}
	return 0;
}
Exemple #18
0
  StateResult ActionPutInto::doBeginWorkNVI(GameState& gameState, Systems::Manager& systems, json& arguments)
  {
    /// @todo Handle putting a certain quantity of an item.
    StateResult result = StateResult::Failure();
    std::string message;
    auto subject = getSubject();
    auto object = getObject();
    auto container = getTargetThing();
    auto& lua = gameState.lua();
    auto& narrator = systems.narrator();

    if (lua.doSubjectActionObject(subject, *this, container))
    {
      printMessageDo(systems, arguments);

      if (systems.geometry().moveEntityInto(object, container))
      {
        /// @todo Figure out action time.
        result = StateResult::Success();
      }
      else
      {
        arguments["preposition"] = tr("PREPOSITION_INTO");
        putMsg(narrator.makeTr("YOU_CANT_VERB_FOO_PREPOSITION_TARGET_UNKNOWN", arguments));

        CLOG(ERROR, "Action") << "Could not move Entity into Container even though beObjectOf returned Success";
      }
    }

    return result;
  }
Exemple #19
0
/*
 * The returned struct tells the client if the click is valid and if so
 * what's the server answer to the move
 */
gameAnswer notifyClick(int x, int y) [[server]]
{
	if(x < 0 || x > 2 || y < 0 || y > 2)
		return gameAnswer(0,0,false);

	if(gameState.get(x,y)) //Already set
		return gameAnswer(0,0,false);

	gameState.set(x,y);

	int retX;
	int retY;
	gameState.getFirstEmpty(retX,retY);
	gameState.set(retX,retY);
	return gameAnswer(retX,retY,true);
}
Exemple #20
0
 size_t UCTSearch::getChildNodeType(UCTNode & parent, const GameState & prevState) const
{
    if (!prevState.bothCanMove())
    {
        return SearchNodeType::SoloNode;
    }
    else
    {
        if (parent.getNodeType() == SearchNodeType::RootNode)
        {
            return SearchNodeType::FirstSimNode;
        }
        else if (parent.getNodeType() == SearchNodeType::SoloNode)
        {
            return SearchNodeType::FirstSimNode;
        }
        else if (parent.getNodeType() == SearchNodeType::SecondSimNode)
        {
            return SearchNodeType::FirstSimNode;
        }
        else if (parent.getNodeType() == SearchNodeType::FirstSimNode)
        {
            return SearchNodeType::SecondSimNode;
        }
    }

    return SearchNodeType::Default;
}
Exemple #21
0
int main()
{
    srand(time(NULL));

    bool playingGame = true;
    GameState game;

    while (playingGame)
    {
        game.CallCurrentState();

        if (game.GetExit() == true) playingGame = false;
    }

    return 0;
}
Exemple #22
0
bp::list GetScoresWrap(const GameState& gameState) {
	bp::list result;
	for (uint32_t score : gameState.GetScores()) {
		result.append(score);
	}
	return result;
}
Exemple #23
0
/* drawSprites()
 * - this function is what actually draws the sprites
 *   onto the screen at their appropriate location
 * - it actually loops through a list of active sprites
 *   and then sorts them by their layerID and then draws them
 * - the sorting has to happen so that you draw from back to front
 *   just like a painter and a canvas.
 */
void Game::drawSprites()
{
	/* we could just do the following to draw the three sprites
	   but that would be silly since we have a list of sprites to draw
	   stored, so all we need to do is go through the list and draw eaach 
	   sprite in the list */
	/* // silly way 
	testSprite->draw();
	animatedSprite->draw();
	animatedSprite2->draw();
	*/
	
	/* better way */
	/* this is better because it doesn't matter how many sprites we have, they will always be drawn */

	//tassos says:

	// instead of this list, just tell the current game class to draw
	// give it a draw call

	//void GameState::Draw()
	//{


	/*std::vector<Sprite*>::iterator it; 
	for(it=spriteListToDraw.begin(); it != spriteListToDraw.end(); it++)
	{
		Sprite *s = (*it);
		s->draw();
	}*/
//===========================================================================================
//								 SPRITE ITERATOR
//===========================================================================================
	std::vector<GameState*>::iterator it;
	for (it = states.begin(); it != states.end(); it++)
	{
		if (*it)
		{  
			  GameState* s = (*it);
			  if(s->active==true)
			  s->Draw();
		}

	}


}
int NegamaxAlphaBetaSearcher::SearchBestPlay(const GameState& state, int depth)
{
    std::vector<int> bestCell;
    int bestValue = -INFINITY;
    int bestPos = 0;
#ifdef _DEBUG
    _searcherCounter = 0;
#endif

    ResetTranspositionTable();

    GameState tryState = state;
    int player_id = state.GetCurrentPlayer();

    std::vector<MOVES_LIST> moves;
    int mc = tryState.FindMoves(player_id, moves);
    if(mc == 0) //遇到无路可走的情况,比如被对方逼着走禁手,可放弃一步
    {
        return -1;
    }
    SortMoves(moves);
    for(int i = 0; i < mc; i++)
    {
        tryState.DoPutChess(moves[i].cell, player_id);
        int value = NegaMax(tryState, depth - 1, -INFINITY, INFINITY, player_id);
        tryState.UndoPutChess(moves[i].cell);
        if(value > bestValue)
        {
            bestValue = value;
            bestCell.clear();
            bestCell.push_back(moves[i].cell);
        }
        else if(value == bestValue)
        {
            bestCell.push_back(moves[i].cell);
        }
    }

    if(bestCell.size() > 0)
        bestPos = rand() % bestCell.size();

#ifdef _DEBUG
    std::cout << "NegamaxSearcher " << _searcherCounter << " (with Alpha-Beta)" << std::endl;
#endif

    return bestCell[bestPos];
}
Board adj_friendly(const GameState& gs, const uint8_t for_color)
{
  Board res;
  const Board& color_board = gs.get_color_board(for_color);
  for(unsigned int direction = NORTH; direction < num_directions(); ++direction)
    res |= is_adjacent(color_board, color_board, direction);
  return res;
}
void generate_steps(const GameState& gs, std::vector<Delta> *steps)
{
  const Board& not_frozen = ~frozen_pieces(gs, gs.get_color());

  for (unsigned int dir_empty = NORTH; dir_empty < num_directions(); ++dir_empty) {

    Board pieces_with_step = adj_step(gs, gs.get_color(), dir_empty) & not_frozen;

    assert((pieces_with_step & gs.get_color_board(gs.get_color())) == pieces_with_step);

    while(!pieces_with_step.is_empty()) {
      uint8_t mobile_idx = pieces_with_step.idx_and_reset();
      assert(gs.get_all_const().contains(mobile_idx));
      steps->push_back(Delta(step_from_gs(gs, mobile_idx, dir_empty)));
    }
  }
}
void generate_pushes(const GameState& gs, std::vector<Delta> *pushes)
{
  const uint8_t pushing_color = gs.get_color();
  const uint8_t pushed_color = other_color(gs.get_color());
  const Board& pushing_mobile = ~frozen_pieces(gs, gs.get_color());

  Board pushed_with_adj_empty[4];

  // The body of generate_pushes() takes the perspective of the pushed piece.  
  // dir_pushed_from is the direction from which the pushing piece comes from.
  // dir_pushed is the direction the pushed piece is pushed to.

  for (unsigned int dir = NORTH; dir < num_directions(); ++dir) {
    pushed_with_adj_empty[dir] = adj_empty(gs, pushed_color, dir);
  }

  for (unsigned int dir_pushed_from = NORTH; dir_pushed_from < num_directions(); ++dir_pushed_from) {

    // the mobile pushing pieces with an adjacent weaker piece.
    // We use the opp_dir(dir_pushed_from) here since we are talking about the pushing piece.
    const Board& pushing_pieces_with_adj_lt = 
      adj_enemy_lt(gs, pushing_color, opp_dir(dir_pushed_from)) & pushing_mobile;

    for (unsigned int dir_pushed = NORTH; dir_pushed < num_directions(); ++dir_pushed) {
      if (dir_pushed_from == dir_pushed) continue;

      // TODO: Try and make symmetric with generate_pulls() -- simplify inner loop here...
      Board pushing_pieces = 
        is_adjacent(pushing_pieces_with_adj_lt, pushed_with_adj_empty[dir_pushed],
            opp_dir(dir_pushed_from));

      Board pushed_pieces = 
        is_adjacent(pushed_with_adj_empty[dir_pushed], pushing_pieces_with_adj_lt, dir_pushed_from);

      while(!pushed_pieces.is_empty()) {
        assert(!pushing_pieces.is_empty());
        uint8_t pushed_idx = pushed_pieces.idx_and_reset();
        uint8_t pusher_idx = pushing_pieces.idx_and_reset();
        assert(gs.get_all_const().contains(pushed_idx));
        assert(gs.get_all_const().contains(pusher_idx));
        pushes->push_back(Delta(step_from_gs(gs, pushed_idx, dir_pushed),
              step_from_gs(gs, pusher_idx, opp_dir(dir_pushed_from))));
      }
    }
  }
}
static int gen_monster(lua_State* L) {
	GameState* gs = lua_get_gamestate(L);
	MTwist& mt = gs->rng();
	int nargs = lua_gettop(L);

	GeneratedLevel* level = lua_togenlevel(L, 1);
	enemy_id etype = enemy_from_lua(L, 2);
	Region r = lua_toregion(L, 3);
	int amount = nargs >= 4 ? lua_tointeger(L, 4) : 1;

	bool success = generate_enemy(*level, mt, etype, r,
			gs->teams().default_enemy_team(), amount);

	lua_pushboolean(L, success);

	return 1;
}
Exemple #29
0
void		BulletCommand::managePaused(GameState &state)
{
  if (_paused)
    {
      Command* cmd = new Command("increasePaused");
	  state.pushCommand(*cmd);
    }
}
Exemple #30
0
void UCTSearch::updateState(UCTNode & node, GameState & state, bool isLeaf)
{
    // if it's the first sim move with children, or the root node
    if ((node.getNodeType() != SearchNodeType::FirstSimNode) || isLeaf)
    {
        // if this is a second sim node
        if (node.getNodeType() == SearchNodeType::SecondSimNode)
        {
            // make the parent's moves on the state because they haven't been done yet
            state.makeMoves(node.getParent()->getMove());
        }

        // do the current node moves and call finished moving
        state.makeMoves(node.getMove());
        state.finishedMoving();
    }
}