def send_game_state(self): GameEngine().acquire() s = GameEngine().get_player_state(self._player_id) kills = [] # TODO: Call the right GameEngine method to get the new # kills to display. terminals = [] # TODO: Call the right GameEngine method to get the # terminal pirating progressions. terminals = [[1, 100], [2, 100], [3, 100]] events = [] # TODO: Call the right GameEngine method to get the new # events. time = GameEngine().get_remaining_time() GameEngine().release() self.send({ 'type': 'update', 'l': s['hp'], 'p': (s['x'], s['y']), 'd': s['d'], 's': s['s'], 'v': s['v'], 'k': kills, 'vp': s['vp'], 'pi': terminals, 'vo': s['vo'], 'ao': s['ao'], 'ev': events, 'ti': time })
def shutdown(self, force=False): print 'Shutting down server{}...'.format( ' (the hardcore way)' if force else '') GameEngine().end_of_game() self._tcp_server.shutdown(force) GameEngine().stop_auto_mode(force) print 'Good bye.'
def run(self): force = False sleep_time = GameEngine().config.end_game_poll_time try: while GameEngine().loop: sleep(sleep_time) except KeyboardInterrupt: force = True self.shutdown(force)
def __init__(self, width: int, height: int, title: str): """ :param width: :param height: :param title: """ super().__init__(width, height, title, antialiasing=False) # Main game engine, where the game is managed self.game_engine = GameEngine() # Track the current state of what key is pressed self.left_pressed = False self.right_pressed = False self.up_pressed = False self.down_pressed = False self.up_left_pressed = False self.up_right_pressed = False self.down_left_pressed = False self.down_right_pressed = False # Used for auto-repeat of moves self.time_since_last_move_check = 0 # Where is the mouse? self.mouse_position: Optional[Tuple[float, float]] = None self.mouse_over_text: Optional[str] = None # These are sprites that appear as buttons on the character sheet. self.character_sheet_buttons = arcade.SpriteList() arcade.set_background_color(colors['background'])
def run(self): game = GameEngine(self) while game.run(): pygame.display.flip() self.clock.tick(60) self.destroy() return self
def start_game(self, players): """ (1) initialize and start game engine (2) send START to everyone with players in turn order as value (3) send TURN to everyone with first to play as value (4) send face up cards (hand) separately to each player (5) send face down sprite once to everyone (6) send discard pile card to everyone """ self.game_engine = GameEngine(players) self.game_engine.start() # send START and players ordered by turn as value: self.send_to_all({"START": [i.name for i in self.game_engine.players]}) # send current turn: player_turn = self.game_engine.players[self.game_engine.turn].name self.send_to_all({"TURN": player_turn}) # send face down sprite to everyone: self.send_card(('reverso', ''), '2') # send discard pile card to everyone: self.send_card(self.game_engine.discard_pile, '1') # send hand to each player: for socket_, player_name in self.players.items(): cards = [p.cards for p in self.game_engine.players if p.name == player_name][0] opponents_sock = [sock for sock, name in self.players.items() if name != player_name] for card in cards: self.send_card(card, '0', client_socket=socket_) for opponent_sock in opponents_sock: # send OPPONENT_CARD command to each opponent of player message = {"OPPONENT_CARD": [player_name, True]} self.send(message, opponent_sock)
def __init__(self): global escrever self.screen = None self.atraso = 350 # quanto tempo entre os movimentos self.game = GameEngine() self.novoJogo() pass
def start_game(self): if len(self.players_sessions) < 4: raise HTTPException(401, "At least 4 players needed") self.state = STATE_STARTED for session in self.players_sessions: session.state = STATE_PLAYING self.engine = GameEngine(self)
def send_end_stats(self): GameEngine().acquire() gs = GameEngine().get_game_statistics() ps = GameEngine().get_player_state(self._player_id) GameEngine().release() data = { 'type': 'end', 'winners': gs['winners'], 'ttime': gs['ttime'], 'lifes': ps['l'] } if self._player_team == MERC_TEAM: data['kills'] = ps['kills'] elif self._player_team == SPY_TEAM: data['recap'] = ps['recap'] self.send(data)
def handle_shoot(self, data): try: angle = data['v'] if not isinstance(angle, float) or angle < 0 or angle > 360: print 'Wrong input received: invalid message field `v`' self.update_status(self.CONNECTION_STOP) return except KeyError: print 'Wrong input received: missing field(s) in message of type \ `shoot`' self.update_status(self.CONNECTION_STOP) return GameEngine().acquire() GameEngine().shoot(self._player_id, angle) GameEngine().release()
def __init__(self, chessboard): self.chessboard = chessboard self.player_piece = { Player.HUMAN: ChessBoard.WHITE_PAWN, Player.AI: ChessBoard.BLACK_PAWN } self.move_validator = MoveValidator(self) self.turn = Player.HUMAN self.was_last_move_a_two_step_move = True self.position_of_two_steps_pawn = (4, 'C') self.game_engine = GameEngine(self) self.mini_max = MinMax(self, self.move_validator)
def init_game(): game = GameEngine() game.put_player(1, 0) game.put_box(4, 6) game.put_box(4, 7) game.add_goal(1, 3) game.add_goal(9, 9) game.build_wall(2, 2, 1, 3) game.build_wall(0, 4, 3, 1) game.build_wall(5, 3, 2, 1) game.build_wall(4, 2, 1, 2) game.build_wall(4, 0, 1, 1) return game
def play(): store = pydux.create_store(reducer) game_engine = GameEngine(store) game_engine.request({'type': 'create_state'}) response = game_engine.request({ 'type': 'play_creature', 'card_index': 0, 'player': 'p1', 'lane': 'field_lane' }) print(pprint(response))
def main(): '''The main programme (to run first)''' # create the game engine 'pygame' game_engine = GameEngine() # create controllers for objects to construct inside the game labyrinth_ctrl = LabyrinthController(game_engine) guard_ctrl = GuardController(labyrinth_ctrl, game_engine) hero_ctrl = HeroController(labyrinth_ctrl, guard_ctrl, game_engine) ObjectController(labyrinth_ctrl, hero_ctrl, guard_ctrl, game_engine) hero_ctrl.setting_collisions() # start the game game_engine.start()
def handle_move(self, data): try: angle = data['d'] speed = data['s'] if not isinstance(angle, float) or angle < 0 or angle > 360: print 'Wrong input received: invalid message field `d`' self.update_status(self.CONNECTION_STOP) return elif not isinstance(speed, float) or speed < 0 or speed > 1: print 'Wrong input received: invalid message field `s`' self.update_status(self.CONNECTION_STOP) return except KeyError: print 'Wrong input received: missing field(s) in message of type \ `move`' self.update_status(self.CONNECTION_STOP) return GameEngine().acquire() GameEngine().set_movement_angle(self._player_id, angle) GameEngine().set_movement_speedx(self._player_id, speed) GameEngine().set_movement_speedy(self._player_id, speed) GameEngine().release()
def play_game(self): print('Welcome to Game of Life !') try: rows_input = int(input('How many rows for your grid ? ')) columns_input = int(input('How many columns for your grid ? ')) rounds_input = int(input('How many rounds for your game ? ')) except Exception as e: print(e) else: game_engine = GameEngine(rows_input, columns_input) while self.rounds_number <= rounds_input: print(game_engine) game_engine.update_grid() print('\n\n') self.rounds_number += 1
def __init__(self, width, height, title): """ Args: width = 画面の幅 height = 画面の高さ title = タイトル antialiasing = 画像にアンチエイリアスを掛けるかどうか """ super().__init__(width, height, title, antialiasing=False) self.engine = GameEngine() self.player_direction = None self.viewports = None self.choice = 0 # messagewindowの選択 self.game_dict = None# saveファイルの格納に使う
def handle_init(self, data): try: if not data['team'] in (MERC_TEAM, SPY_TEAM): print 'Wrong input received: invalid message field `team`' self.update_status(self.CONNECTION_STOP) return elif not set(data['nick']).issubset(printable_chars): print 'Wrong input received: invalid message field `nick`' self.update_status(self.CONNECTION_STOP) return except KeyError: print 'Wrong input received: missing field(s) in message of type \ `init`' self.update_status(self.CONNECTION_STOP) return self._player_id = GameEngine().connect_to_player( data['team'], data['nick']) if self._player_id is None: print 'Initialisation failed: team full' self.update_status(self.CONNECTION_STOP) return self._player_team = data['team'] player_state = GameEngine().get_player_state(self._player_id) pos_x, pos_y, max_hp = (player_state[k] for k in ('x', 'y', 'hp')) GameEngine().all_players_connected.wait() self.send({ 'type': 'init', 'id': self._player_id, 'pos': (pos_x, pos_y), 'max_hp': max_hp, 'team': data['team'], 'map': GameEngine().get_map_name(), 'map_hash': GameEngine().get_map_hash(), 'players': GameEngine().get_players_info() }) self.setup_sender(GameEngine().config.send_state_interval) self.update_status(self.CONNECTION_RUN)
def setup(self): print 'New client connected:', self.client_address[0], \ self.client_address[1] super(SpylightRequestHandler, self).setup() self._player_id = None self._player_team = None self._sender_busy = Event() self._sender_interval = -1 self._sender = None self.status = self.CONNECTION_INIT if GameEngine().all_players_connected.is_set(): print 'Connection will be closed: game already launched (both \ teams are full)' self.update_status(self.CONNECTION_STOP)
def main(): # possible to change the player's names, or even ask the user to input them game = GameEngine(p1_name="Player 1", p2_name="Player 2") game.start() # main loop while True: # round loop while game.round_in_progress(): game.print_board() game.next_move() # condition to break out of main game loop print("Do you want to play another round? (y/n)") if input("> ").lower() == "n": break # else start a new round game.new_round() # print the final score game.print_score(final=True) print("\nGoodbye.")
def submit_entry(user_id: str, entry: Decimal) -> bool: "submit a bet" return GameEngine().submit_entry(user_id, entry)
def game_state() -> dict: "Get the current game state" return GameEngine().get_game_state()
#!/usr/bin/env python3 import sys import rospy from game_engine import GameEngine from game_engine_competition import GameEngineCompetition # useful sudo apt-get install -y python3-rospy _IN_ROS = True if __name__ == '__main__': if _IN_ROS: rospy.init_node("soccer_strategy") g = GameEngineCompetition() g.run() else: g = GameEngine() g.run_loop()
def __init__(self): self.game_engine = GameEngine()
""" PROJECT: CuriosityJar - The Humble-Nishiyama Randomness Game DESCRIPTION: Explore and Experiment on Penney's game concepts AUTHOR: Nuttaphat Arunoprayoch DATE: 09-SEP-2020 """ # Import libraries import pandas as pd import matplotlib.pyplot as plt from game_engine import GameEngine # Load Core GameEngine game_engine = GameEngine() # Main function def main() -> None: # Without a winning method without_winning_method_res = game_engine.start_experiment( is_winning_method_used=False) # With a winning method with_winning_method_res = game_engine.start_experiment( is_winning_method_used=True) # Prepare DataFrame df_without_winning_method = pd.DataFrame([without_winning_method_res]) df_without_winning_method['cat'] = 'without' df_with_winning_method_res = pd.DataFrame([with_winning_method_res]) df_with_winning_method_res['cat'] = 'with' df_final = pd.concat(
def reset(self): if self._engine is None: self._engine = GameEngine() obs, info = self._engine.get_obs()
def get_request(self): sock, addr = super(ThreadingTCPServer, self).get_request() sock.settimeout(GameEngine().config.handle_timeout) return sock, addr
"Mediator Pattern Example Code" from game_engine import GameEngine from game_client import GameClient from player import Player from scheduler import Scheduler # The concrete GameEngine process that would run on a dedicated server GAMEENGINE = GameEngine() # 3 Hypothetical game clients, all running externally on mobile phones # calling the GAMEENGINE mediator across a network proxy MOBILECLIENT1 = GameClient(GAMEENGINE) PLAYER1 = Player("Sean", 100) MOBILECLIENT1.add_player(PLAYER1) MOBILECLIENT2 = GameClient(GAMEENGINE) PLAYER2 = Player("Cosmo", 200) MOBILECLIENT2.add_player(PLAYER2) MOBILECLIENT3 = GameClient(GAMEENGINE) PLAYER3 = Player( "Emmy", 300, ) MOBILECLIENT3.add_player(PLAYER3) # A scheduler is a separate process that manages game rounds and # triggers game events at time intervals SCHEDULER = Scheduler(GAMEENGINE) SCHEDULER.new_game()
import pickle import time import numpy as np import config config.init() # import resource # creating an NN for now #nn = ValueEstimator(2, 42, 50) # running_train_time = 600 train_start_time = time.time() # creating a new game and two ais: ai1 = AI(1) ai2 = AI(2) game = GameEngine() # loading database from pickle file try: new_file = open("database_dump.pkl", "rb") database = pickle.load(new_file) new_file.close() except: database = [] new_file = open("database_dump.pkl", "wb") pickle.dump(database, new_file) new_file.close() batch = [] while time.time() - train_start_time < running_train_time: game.reset_game() batch.clear()
def init_game_engine(self, config_file): print 'Loading game engine...' GameEngine().init(config_file)