def test_do_not_move_piece_to_end_on_bigger_dice(monkeypatch): # Given we have started the game and a piece is in the safe zone board = Board.create(players=[0, 2], pieces_per_player=1) state = GameState.create(board) dice = Dice() monkeypatch.setattr(dice, "roll", lambda: 5) game = GameEngine(board, dice) state.board.pieces[0].progress = board.end_progress - 3 # When we roll the dice with 5 which is bigger then we need to # get to the goal new_state = game.play(GameMove.roll_dice(player=0)) # Then the piece should not go to the goal and it should be the # next player turn assert new_state == game.get_state() assert new_state.number == 1 assert new_state.dice == 5 assert new_state.valid_actions == [ GameMove.roll_dice(player=2), ] assert new_state.board.pieces == [ Piece(number=0, player=0, progress=board.end_progress - 3), Piece(number=0, player=2, progress=0), ] assert new_state.winners == []
def _fitnessEvaluations(self, pacmen, ghosts): totalGames = max(len(pacmen), len(ghosts)) pacManNumber = 0 ghostNumber = 0 for evaluation in range(totalGames): pacMan = None ghost = None if pacManNumber > len(pacmen) - 1: pacManNumber = 0 if ghostNumber > len(ghosts) - 1: ghostNumber = 0 pacMan = pacmen[pacManNumber] ghost = ghosts[ghostNumber] engine = GameEngine(self.configDict, pacMan.parseTree, ghost.parseTree) engine.runGame() pacMan, ghost = self._evaluateFitness(engine, pacMan, ghost) pacmen[pacManNumber] = pacMan ghosts[ghostNumber] = ghost pacManNumber += 1 ghostNumber += 1 return pacmen, ghosts
class Application: def __init__(self): self.process_stack = [] self.game_engine = GameEngine(self) self.state_continuous = True self.current_state = None self.ending_message = '' def run(self): game_state = GameState(self) self.current_state = game_state self.add_new_state(game_state) while len(self.process_stack) != 0: self.game_engine.handle_general_events() if not self.state_continuous: break self.current_state = self.process_stack[-1] self.current_state.run_loop_once() print(self.ending_message) def add_new_state(self, state): self.process_stack.append(state) self.current_state = state self.current_state.register_mouse_handlers(state.get_mouse_handlers()) self.current_state.register_button_handlers( state.get_button_handlers()) self.current_state.register_keyboard_handlers( state.get_keyboard_handlers()) # for keyboard def get_game_engine(self): return self.game_engine
def main(): board = Board() engine = GameEngine(board) cross_player = AIPlayer(1, "dude", engine) noughts_player = HumanPlayer(-1, "Rand", engine) view = BoardView(board) done = False view.update() while not done: try: cross_player.make_move() view.update() if engine.game_ended(): view.reset() continue noughts_player.make_move() view.update() if engine.game_ended(): view.reset() continue for event in pygame.event.get(): if event.type == pygame.QUIT: done = True except Exception: traceback.print_exc()
def test_play_to_leaf_with_sims(): d = Deal(seed=0) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) sims = sim.load_sims(0) d = e.play_to_leaf(d, sims, random=False) assert_equal(d.full_history[0][1], d.trick_tally)
def reinit(self): game = Application.GAMES[self._game_number] with open('public/' + game + '/ROOMS.json') as f: rooms = json.load(f) with open('public/' + game + '/OBJECTS.json') as f: objects = json.load(f) self._engine = GameEngine(objects, rooms) self._hardware.set_audio_path('public/' + game + '/audio/')
def __init__(self, size): """ Draw game's grid/universe Arguments: size {int tuple} -- size of grid to draw (x, y) """ # init self state as randomized binary value based on given tuple (size) self.state = RNG.integers(2, size=size) # init self access to GameEngine class self.gameEngine = GameEngine(self)
def application(environ, start_response): try: if environ['REQUEST_METHOD'] == 'POST': request_body_size = int(environ.get('CONTENT_LENGTH', '0')) request_body = environ['wsgi.input'].read(request_body_size) data = json.loads(request_body.decode()) WORLDS = {} world = data['world'] if world not in WORLDS: with open('public/' + world + '/OBJECTS.json') as f: objects = json.load(f) with open('public/' + world + '/ROOMS.json') as f: rooms = json.load(f) WORLDS['world'] = [objects, rooms] world = WORLDS['world'] game = GameEngine(world[0], world[1]) game.set_state(data['state']) cmd = game.decode_button_command(data['user_command']) prs = game.process_command(cmd) audio_prs = game.prompts_only(prs) text_prs = game.text_only(prs) ndata = { 'text': text_prs, 'audio': audio_prs, 'state': game.get_state() } start_response('200 OK', [('Content-Type', 'application/json')]) return [json.dumps(ndata).encode()] else: # If we are running alongside a web server then the server will handle static files. # This is for the stand-alone case (like running on the Farmer Says) fn = environ['PATH_INFO'] if fn == '/': fn = '/index.html' print('*', fn, '*') with open('public' + fn, 'rb') as f: data = f.read() if fn.endswith('.json'): start_response('200 OK', [('Content-Type', 'application/json')]) else: start_response('200 OK', [('Content-Type', 'text/html')]) return [data] except Exception: with open('ex.txt', 'w') as f: f.write(traceback.format_exc()) raise
class DrawGrid: def __init__(self, size): """ Draw game's grid/universe Arguments: size {int tuple} -- size of grid to draw (x, y) """ # init self state as randomized binary value based on given tuple (size) self.state = RNG.integers(2, size=size) # init self access to GameEngine class self.gameEngine = GameEngine(self) def animateGrid(self): """ "Animate" game's grid/universe using double-buffering. Yields: [self] -- enables while loop to re-up and draw new image data based on engine rules that were processed during previous pass, generating the illusion of animation """ start = 0 n = 0 plt.title(GAME_TITLE) while 1: if n == 0: # create image based on init state data image = plt.imshow(self.state) else: # update image based on yielded state from previous pass image.set_data(self.state) # increment n n += 1 self.gameEngine.rules() print( "life cycle: {}\t\t"\ "frame time: {:.3f}\t\t"\ "framerate: {:.2f}\t\t".format( n, (time.time() - start), (1 / (time.time() - start)), ), end= "\r", ) start = 0 start = time.time() plt.pause(DESIRED_FRAMERATE) yield self
def test_play_to_all_leaves(): d = Deal(seed=0) d.make_lead() # print(d.original_hands) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) e.play_to_all_leaves(d) assert_equal(d.trick_no, 5) assert_equal(d.card_no, 17) assert_equal(d.current_trick, []) # we save this number from a previous run. Good to check we always traverse the whole tree assert_equal(d.leaf_nodes, 832)
def _initializePopulation(self): newPacMen = [] numberOfPacMen = self.configDict["pacmanPopulationSize"] if self.totalEvals < numberOfPacMen: numberOfPacMen = self.totalEvals newGhosts = [] numberOfGhosts = self.configDict["ghostPopulationSize"] if self.totalEvals < numberOfGhosts: numberOfGhosts = self.totalEvals totalGames = max(numberOfPacMen, numberOfGhosts) for evaluation in range(totalGames): pacMan = None ghost = None # Random number passed to _generateSolution implements ramped half and half. if numberOfPacMen > 0: pacMan = self._generateSolution("pac-man", random.randint(0, 1)) numberOfPacMen -= 1 if numberOfGhosts > 0: ghost = self._generateSolution("ghost", random.randint(0, 1)) numberOfGhosts -= 1 reusedPacManInd = -1 reusedGhostInd = -1 if not pacMan: reusedPacManInd = random.randint(0, len(newPacMen) - 1) pacMan = newPacMen[reusedPacManInd] elif not ghost: reusedGhostInd = random.randint(0, len(newGhosts) - 1) ghost = newGhosts[reusedGhostInd] engine = GameEngine(self.configDict, pacMan.parseTree, ghost.parseTree) engine.runGame() pacMan, ghost = self._evaluateFitness(engine, pacMan, ghost)\ if reusedPacManInd != -1: newPacMen[reusedPacManInd] = pacMan else: newPacMen.append(pacMan) if reusedGhostInd != -1: newGhosts[reusedGhostInd] = ghost else: newGhosts.append(ghost) self.pacmanPopulation = newPacMen self.ghostPopulation = newGhosts
def test_roll(monkeypatch, client): # Given 4 players had joined in the previous tests and the game had starte # When we try to play with the correct user token rv = client.get("/play/roll", headers={"4oBe4e-user-token": player1_token}) game_state = json.loads(rv.data) board = Board.create(players=[0, 1, 2, 3]) dice = Dice() monkeypatch.setattr(dice, "roll", lambda: game_state["dice"]) game = GameEngine(board, dice) game.play(GameMove.roll_dice(player=0)) # Then we want the same state as the default for 4 players assert game_state == dataclasses.asdict(game.get_state())
def test_play_to_leaf(): deal = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D14', 'D13', 'H14', 'H13']), 'W': set(['D12', 'D11', 'S12', 'S11']) } d = Deal(deal=deal) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) e.play_to_leaf(d) assert_equal(d.trick_no, 5) assert_equal(d.card_no, 17) assert_equal(d.current_trick, []) assert_equal(d.leaf_nodes, 1)
def main(argv): engine = GameEngine() engine.check_file_integrity("../data/test_init.json") engine.initialize_from_file("../data/test_init.json") result = engine.compute() print(result)
def test_initial_gate_state(monkeypatch): # Given board = Board.create(players=[1, 3]) state = GameState.create(board) # When game = GameEngine(board) # Then assert game.state == state
def __init__(self, game, use_audio=True): if use_audio: print('Loading hardware ...') from farmer_says import FarmerSays print('... done') self._hardware = FarmerSays() self._hardware.start_audio_thread() else: self._hardware = None with open('public/' + game + '/ROOMS.json') as f: rooms = json.load(f) with open('public/' + game + '/OBJECTS.json') as f: objects = json.load(f) self._engine = GameEngine(objects, rooms) if self._hardware: self._hardware.set_audio_path('public/' + game + '/audio/')
def main(): """Main function to bootstrap the game.""" board_generator = BoardGenerator() config_parser = JSONConfigParser() config_loader = ConfigLoader(CONFIG_FILE_PATH, config_parser) console_input = ConsoleInput() console_output = ConsoleOutput() game_engine = GameEngine(board_generator) validator = StrToIntValidator() menu = Menu(config_loader, game_engine, console_input, console_output, validator) menu.run_main_menu()
def test_play_roll_dice_6(monkeypatch): # Given board = Board.create(players=[1, 3]) state = GameState.create(board) dice = Dice() monkeypatch.setattr(dice, "roll", lambda: 6) game = GameEngine(board, dice) # When new_state = game.play(GameMove.roll_dice(player=1)) # Then # assert new_state == game.get_state() assert new_state.number == 1 assert new_state.dice == 6 assert new_state.valid_actions == [ GameMove.piece_out(player=1, piece=0, dice=6), GameMove.piece_out(player=1, piece=1, dice=6), GameMove.piece_out(player=1, piece=2, dice=6), GameMove.piece_out(player=1, piece=3, dice=6), ]
def test_play_roll_dice_3(monkeypatch): # Given board = Board.create(players=[1, 3]) state = GameState.create(board) dice = Dice() monkeypatch.setattr(dice, "roll", lambda: 3) game = GameEngine(board, dice) # When new_state = game.play(GameMove.roll_dice(player=1)) # Then assert new_state == game.get_state() assert new_state.number == 1 assert new_state.dice == 3 assert new_state.valid_actions == [GameMove.roll_dice(player=3)] # And When new_state = game.play(GameMove.roll_dice(player=3)) # Then assert new_state == game.get_state() assert new_state.number == 2 assert new_state.dice == 3 assert new_state.valid_actions == [GameMove.roll_dice(player=1)]
def main(): """ Main entry function. Tries to run some tests for now. :returns: None. """ def print_field(field): """ Prints the field to console window. :field: a field to be printed. :returns: None. """ sys.stdout.write("== State ==\n") last_row = 0 for coord in field.cells_coords(): row = coord[0] if row > last_row: sys.stdout.write("\n") last_row = row if field.get_cell(coord): sys.stdout.write("*") else: sys.stdout.write(" ") sys.stdout.write("\n") sys.stdout.flush() # Make a simple test field field = StandardField(5, 5) field.set_cell((0,0), True) field.set_cell((0,1), True) field.set_cell((1,2), True) field.set_cell((2,0), True) field.set_cell((2,1), True) field.set_cell((1,3), True) field.set_cell((0,4), True) field.set_cell((2,4), True) # Run an engine engine = GameEngine(next_generation_std, field, print_field) engine.run_until_true(IterativeStopRule(6))
def game_loop(): engine = GameEngine() running = True while running: clock.tick(40) if pygame.event.get(pygame.QUIT): running = False return engine.scene.handle_events(pygame.event.get()) engine.scene.update() engine.scene.render(gameDisplay) pygame.display.update(engine.scene.rects_to_update) engine.scene.rects_to_update = [] """
def test_find_all_layouts_and_run_sims(): deal = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D14', 'D13', 'H14', 'H13']), 'W': set(['D12', 'D11', 'S12', 'S11']) } d = Deal(deal=deal) sim = Simulator() dec = Decisions() disp = Displayer() e = GameEngine(disp, dec, sim) d.make_lead('D12') layouts = sim.find_layouts(d) # This should be the case because west has played a card already and north/south haven't assert (len(layouts[2]) > len(layouts[0]))
def test_play_invalid_action_on_initial_state(monkeypatch): # Given board = Board.create(players=[1, 3]) state = GameState.create(board) game = GameEngine(board) # When we try to play an invalid action PieceOut with pytest.raises(Exception): game.play(GameMove.piece_out(1, 1)) # When we try to play valid action for an invalid Player with pytest.raises(Exception): game.play(GameMove.roll_dice(player=3))
def test_generate_possible_layouts(): d = Deal(seed=0) disp = Displayer() dec = Decisions() sim = Simulator() e = GameEngine(disp, dec, sim) layouts = sim.generate_layouts('NS', set(['D12', 'D11', 'S12', 'S11']), set(['C14', 'C13', 'C12', 'C11']), d.all_cards, lead=set([])) assert_equal(len(layouts), scipy.special.comb(8, 4)) my_layout = { 'N': set(['C14', 'C13', 'C12', 'C11']), 'E': set(['S14', 'S13', 'H12', 'H11']), 'S': set(['D12', 'D11', 'S12', 'S11']), 'W': set(['D14', 'D13', 'H14', 'H13']) }
def join(player: str): global engine # TODO Where shall we keep the curren running GameEngine/s ? if player in player_name_token: token = player_name_token[player] num = player_token_number[token] return jsonify({"player_token": token, "player_num": num}) if len(player_token_name) == 4: players: Dict[str, int] = dict( (name, player_token_number[token]) for name, token in player_name_token.items()) raise ValueError("Game is full. Players are ", players) player_uuid: str = str(uuid.uuid4()) player_token_name[player_uuid] = player player_number: int = len(player_token_number) player_name_token[player] = player_uuid player_token_number[player_uuid] = player_number if len(player_token_name) == 4: board = Board.create(list(player_token_number.values())) engine = GameEngine(board) __state_to_json(engine.state) return jsonify({"player_token": player_uuid, "player_num": player_number})
class TestGameEngine(TestCase): def setUp(self): pygame.init() self.engine = GameEngine() def tearDown(self): pygame.quit() def test_update(self): self.engine.update() self.assertEqual(1, self.engine.total_frames) def test_restart(self): self.engine.update() self.engine.game_over = True self.engine.restart() self.assertEqual(0, self.engine.total_frames) self.assertEqual(0, self.engine.total_frames_played)
__author__ = 'Nathan' """ This file is for testing only """ import pygame from engine import GameEngine from tribute import Tribute pygame.init() GameEngine.start()
import pygame, sys from renderer import GameCanvas from engine import GameEngine from pygame.locals import * import random pygame.init() FPS = 5 fpsClock = pygame.time.Clock() canvas = GameCanvas() gameengine = GameEngine() while True: canvas.renderBoard(gameengine) canvas.renderShip(gameengine.ship) #move the ship about gameengine.moveShip('Player',random.randint(0,7),random.randint(0,7)) for event in pygame.event.get(): if (event.type == KEYDOWN): pressed = pygame.key.name(event.key) print 'pressed ' + pressed elif event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() fpsClock.tick(FPS)
# coding:utf-8 __author__ = 'cupen' from resource import Assets import pygame from sprites import Plane from engine import GameEngine game = GameEngine() game.set_background(['bg_01.jpg', 'bg_02.jpg'], width=640, height=480) game.play_music('assets/Devil May Cry - Vergil Battle 2.mp3') playerImage = Assets.loadImage("player.png") player = Plane(playerImage, animConfig=((4,4), (12,13,14,15))) game.add_player(player) game.setEnemyCountPerSeconds(3) game.setPlayerBulletCountPerSeconds(10) game.listen_keyboard( pygame.K_w, lambda e:player.handleEvent(e) ) game.listen_keyboard( pygame.K_s, lambda e:player.handleEvent(e) ) game.listen_keyboard( pygame.K_a, lambda e:player.handleEvent(e) ) game.listen_keyboard( pygame.K_d, lambda e:player.handleEvent(e) ) # game.listen_keyboard( pygame.K_j, lambda e:game.handle_event(e) ) game.run(fps = 100) game.close()
def setUp(self): pygame.init() self.engine = GameEngine()
def __init__(self): self.process_stack = [] self.game_engine = GameEngine(self) self.state_continuous = True self.current_state = None self.ending_message = ''
import sys try: from engine import GameEngine from objects import * import pygame import gamestate as g except ImportError, e: print "Could not load: {}".format(e) sys.exit(2) """ #TODO: * Need: add delta time updating for FPS smoothing * Need: Ability to restart at game end * Bonus: make ball a circle instead of rectangle * Bonus: Add some music * Bonus: Add some sound fx * Bonus: Add Start screen """ if __name__ == "__main__": game = GameEngine() game.run()
def test_play_until_the_end_two_players_once_piece(monkeypatch): # Given we have started the game board = Board.create(players=[0, 2], pieces_per_player=1) state = GameState.create(board) dice = Dice() monkeypatch.setattr(dice, "roll", lambda: 6) game = GameEngine(board, dice) # When we roll the dice new_state = game.play(GameMove.roll_dice(player=0)) # Then the state should be as expected assert new_state == game.get_state() assert new_state.number == 1 assert new_state.dice == 6 assert new_state.valid_actions == [ GameMove.piece_out(player=0, piece=0, dice=6), ] # And When we play getting out with the first peice new_state = game.play(GameMove.piece_out(player=0, piece=0, dice=6)) # Then the first piece should be out assert new_state.current_player == 0 assert new_state.number == 2 assert new_state.dice == 6 assert new_state.board.pieces == [ Piece(number=0, player=0, progress=1), Piece(number=0, player=2, progress=0), ] assert new_state.valid_actions == [GameMove.roll_dice(player=0)] # And When we row the dice again with 6 new_state = game.play(GameMove.roll_dice(player=0)) # Then we should should be able to move the piece forward assert new_state.number == 3 assert new_state.dice == 6 assert new_state.valid_actions == [GameMove.move_piece(player=0, piece=0, dice=6)] # And When we move the piece new_state = game.play(GameMove.move_piece(player=0, piece=0, dice=6)) # Then it should go forward and we should be able to roll the dice again assert new_state.number == 4 assert new_state.winners == [] assert new_state.board.pieces == [ Piece(number=0, player=0, progress=7), Piece(number=0, player=2, progress=0), ] assert new_state.valid_actions == [GameMove.roll_dice(player=0)] # And When we roll the dice again with 6 new_state = game.play(GameMove.roll_dice(player=0)) # Then we should be able to move the piece forward assert new_state.dice == 6 assert new_state.number == 5 assert new_state.valid_actions == [GameMove.move_piece(player=0, piece=0, dice=6)] # And When we move the piece new_state = game.play(GameMove.move_piece(player=0, piece=0, dice=6)) # Then the piece should go forward and we should be able to roll the dice again assert new_state.number == 6 assert new_state.board.pieces == [ Piece(number=0, player=0, progress=13), Piece(number=0, player=2, progress=0), ] assert new_state.winners == [] assert new_state.valid_actions == [GameMove.roll_dice(player=0)] # And When we position the piece toward the end of the board new_state.board.pieces[0].progress = board.end_progress - 6 # And When we roll the dice again with 6 new_state = game.play(GameMove.roll_dice(player=0)) # Then we should be able to move the piece forward into the safe zone and to the goal assert new_state.dice == 6 assert new_state.number == 7 assert new_state.valid_actions == [GameMove.move_piece(player=0, piece=0, dice=6)] # And When we move the piece new_state = game.play(GameMove.move_piece(player=0, piece=0, dice=6)) # Then the piece should go forward and we should be able to roll the dice again assert new_state.number == 8 assert new_state.board.pieces == [ Piece(number=0, player=0, progress=board.end_progress), Piece(number=0, player=2, progress=0), ] assert new_state.winners == [0] assert new_state.valid_actions == []
import math from display import YELLOW, RED from engine import GameEngine from agents.human_agent import HumanAgent from agents.minimax_agent import MiniMaxAgent from agents.random_agent import RandomAgent from player1 import Player1 from player2 import Player2 if __name__ == "__main__": engine = GameEngine(YELLOW, RED) engine.init_display() # TODO: Separate AgentGlobalParams (HyperParams?) and AgentTurnParams human_agent = HumanAgent(params={'display': engine.display}) random_agent = RandomAgent() minimax_agent = MiniMaxAgent(params={ 'depth': 5, 'alpha': -math.inf, 'beta': math.inf, 'maximizingPlayer': True }) human_player1 = Player1(human_agent, "Human 1") human_player2 = Player2(human_agent, "Human 2") minimax_player1 = Player1(minimax_agent, "MiniMax 1") minimax_player2 = Player2(minimax_agent, "MiniMax 2") random_player1 = Player1(random_agent, "Random 1")
def createHeadless(self): """Create a headless game.""" gamemanager = self.createGameManager() engine = GameEngine() engine.updateables.append(gamemanager) return (engine, gamemanager)