Exemple #1
0
    def onGameStarted(self, goingFirst=True):
        self.isFirstPlayer = goingFirst

        # Set up game state information
        if goingFirst:
            self.game = Game(self.faction, self.enemyFaction)
            self.player, self.enemy = self.game.players
        else:
            self.game = Game(self.enemyFaction, self.faction)
            self.enemy, self.player = self.game.players

        self.hasMulliganed = False
        self.bothPlayersMulliganed = False
        self.toMulligan = []

        # Set up the game UI
        if isinstance(self.player, templars.Templar):
            self.guiScene = templarHud.TemplarHud()
        elif isinstance(self.player, mariners.Mariner):
            self.guiScene = marinerHud.MarinerHud()
        elif isinstance(self.player, thieves.Thief):
            self.guiScene = thiefHud.ThiefHud()
        elif isinstance(self.player, fae.Faerie):
            self.guiScene = faerieHud.FaerieHud()
        else:
            self.guiScene = hud.GameHud()
        self.zoneMaker = ZoneMaker()

        self.hasFirstPlayerPenalty = goingFirst
Exemple #2
0
def main():
    game = Game("Game", 320, 240, 3)

    game.assets_manager.load_images({
        "bg": "assets/background.png",
        "player": "assets/player.png",
        "wall": "assets/wall.png"
    })

    level = Level("wall", GRID_SIZE)
    player = Player(game, "player", 150, 50)
    player.keyboard = game.keyboard
    player.level_colliders = level.get_colliders()

    def update(delta_time):
        player.update(delta_time)

        draw()

    def draw():
        for bg_x in range(int(game.width / GRID_SIZE)):
            for bg_y in range(int(game.height / GRID_SIZE)):
                game.display.draw("bg", bg_x * GRID_SIZE, bg_y * GRID_SIZE)
        game.draw(level)
        game.draw(player)

    game.update = update
    game.run()
Exemple #3
0
    def run_game(self):
        """
        Run the game.

        Will run the game this program is all about. After the game it will
        collect results and possibly list the player in the Highscores list.

        """

        g = Game(self.args.level, self.args.questions)
        start_time = time()

        try:
            g.run()
        except StopGame:
            print '\nbye!'
            exit()

        endtime = time() - start_time

        r = Results(self.args.level, self.args.questions,
        g.mistakes, endtime)
        r.print_results()

        Highscores().new(r)
Exemple #4
0
def main():
    """
		Entry part of game
	"""

    game = Game()
    game.start()
Exemple #5
0
    def test_game_result(self):
        '''
        This test will simulate n games between a computer and a human where 
        n is determing by the NUMBER_OF_GAMES settings and make sure that the computer never loses
        '''
        for i in xrange(NUMBER_OF_GAMES):
            board = [0] * 9
            game = Game(board)
            while True:
                available_moves = game.get_blank_boxes()
                # Make a random player move
                box = choice(available_moves)
                game.make_move(box, PLAYER)

                result, winning_combination = game.check_game_over()
                if result:
                    break

                # Make computer's move
                box = game.best_next_move(COMPUTER)
                game.make_move(box, COMPUTER)

                result, winning_combination = game.check_game_over()
                if result:
                    break

            self.assertIsNot(result, PLAYER)
Exemple #6
0
 def test_policy2(self):
     game = Game()
     game.make_move((6, 2), (4, 2))
     move = ((1, 2), (3, 2))
     self.assertEqual(
         NNet._get_policy(NNet._to_policy_vector(move, 'black'),
                          game.state)[move], 1)
Exemple #7
0
 def start_game(self, player, first_turn, **kwargs):
     """ starts a new game """
     self.game = Game(human=player)
     if first_turn:
         self.status = self.GAME_STATUS_HUMAN_MOVE_REQUIRED
         return self.check_status(self.game.human, {'status': True, 'info': ''})
     else:
         self.status = self.GAME_STATUS_COMP_MOVE_REQUIRED
         return self._play_comp_move()
Exemple #8
0
    def test_007(self):
        """Test game evaluation - minimax."""

        Game.reset()
        self.board.take('human', 0)
        self.board.take('human', 4)
        self.board.take('machine', 8)
        move = self.board.next_move()
        self.assertTrue(move == 2 or move == 6, 'Expected to choose position 2 or 6 to lead to a draw')
Exemple #9
0
    def test_006(self):
        """Test game evaluation -- Blocking move"""

        Game.reset()
        self.board.take('human', 4)
        self.board.take('human', 2)
        self.board.take('machine', 0)
        self.board.take('machine', 1)
        move = self.board.eval_tree('machine')
        self.assertTrue(move == 6, 'Expected to choose position 6 for the block')
Exemple #10
0
    def test_game_result(self):
        '''
        This test will simulate n games between a computer and a human where 
        n is determing by the NUMBER_OF_GAMES settings and make sure that the computer never loses
        '''
        for i in xrange(NUMBER_OF_GAMES):
            board = [0] * 9
            game = Game(board)
            while True:
                available_moves = game.get_blank_boxes()
                # Make a random player move
                box = choice(available_moves)
                game.make_move(box, PLAYER)

                result, winning_combination = game.check_game_over()
                if result:
                    break

                # Make computer's move
                box = game.best_next_move(COMPUTER)
                game.make_move(box, COMPUTER)

                result, winning_combination = game.check_game_over()
                if result:
                    break

            self.assertIsNot(result, PLAYER)
Exemple #11
0
 def _do_new_game(self, move_tree=None, analyze_fast=False):
     self.engine.on_new_game()  # clear queries
     self.game = Game(self,
                      self.engine,
                      self.config("game"),
                      move_tree=move_tree,
                      analyze_fast=analyze_fast)
     self.controls.select_mode("analyze" if move_tree and
                               len(move_tree.nodes_in_tree) > 1 else "play")
     self.controls.graph.initialize_from_game(self.game.root)
     self.update_state(redraw_board=True)
Exemple #12
0
 def run_game(self, game: Game) -> str:
     game_result = ''
     # Wait a second for startup
     time.sleep(1)
     while not game_result:
         time.sleep(1)  # Give other threads a chance
         with self.lock:
             game.take_turn()
             game_result = game.result
         if self.kill == True:
             return self, game.game_id
     return self, game.game_id
Exemple #13
0
    def setUp(self):
        self.game = Game()
        self.state = State(c.EMPTY_BOARD)

        self.state.board[1][2] = 'white_knight'
        self.state.board[5][7] = 'black_knight'
        self.state.board[3][3] = 'white_pawn'
        self.state.board[3][4] = 'black_king'

        self.state.pieces['white_knight'].add((1, 2))
        self.state.pieces['black_knight'].add((5, 7))
        self.state.pieces['white_pawn'].add((3, 3))
        self.state.pieces['black_king'].add((3, 4))
Exemple #14
0
def main():
    juego = Game(WIN)
    clock = pygame.time.Clock()
    run = True

    WIN.blit(OPENING, (0, 0))
    print(OPENING.get_width())
    pygame.display.flip()
    sleep(5)

    while run:

        clock.tick(FPS)

        for event in pygame.event.get():

            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                col, row = piece_position(event.pos)
                juego.select(col, row)

            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
                juego.restart()

            if event.type == pygame.QUIT:
                run = False
        juego.draw()
Exemple #15
0
 def _onCreateButtonClicked(self):
     if self.state == MainWindow.STATE_GAME_HALL_GAME_LIST or \
        self.state == MainWindow.STATE_GAME_HALL_GAME_SELECTED:
         self._setState(MainWindow.STATE_GAME_HALL_MAP_LIST)
     elif self.state == MainWindow.STATE_GAME_HALL_MAP_SELECTED:
         self.selectedGame = Game(
             -1, Game.randomGameName(), self.selectedMap,
             self.leftPanel.gameHallPanel.playerName.text())
         self.selectedGame.addPlayer(
             Player(-1, self.leftPanel.gameHallPanel.playerName.text()))
         self.selectedGame.createGame()
         self._setState(MainWindow.STATE_GAME_ROOM_WAITING)
     else:
         qFatal('Invalid state %d when create button clicked' % self.state)
Exemple #16
0
def standard(request, **kwargs):
    """The "standard" unwinnable game control."""

    # Get the move from the GET args, if any
    move = kwargs.get('move', None)
    if move:
        try:
            # Start the game and initialize some useful variables
            g = Game()
            over = False
            result = {'result': ''}
            context = dict()
            # Take the position indicated by <move>
            g.take('human', int(move))
            if len(g.available) != 0:
                # There are still moves available, so just make it feel like the computer is thinking a bit.
                # Response is otherwise pretty much instantaneous and doesn't "feel" very real.
                sleep(2)
                # Normally, I would expect this next operation to be necessary.  Since there is no actual session being
                # started, any game state would be lost when the request completes so any subsequent requests would
                # have no memory of what moves had previously been made.  It appears, however, that the Django runserver
                # preserves the game state between requests, so this isn't necessary if using the runserver.  In the
                # real world, this would take all the moves that have been made so far, which are submitted from the UI,
                # and reconstruct the game state from them.
                # x = request.GET.get('x', None)
                # if x:
                #     g.x = [int(i) for i in x.strip(',').split(',')]
                # o = request.GET.get('o', None)
                # if o:
                #     g.o = [int(i) for i in o.strip(',').split(',')]
                take = g.next_move()
                g.take('machine', take)
                winner = g.winner('machine')
                # If the machine has won, set game over and the winning vector for return to UI
                if winner:
                    over = True
                    result = {'result': list(winner)}
            else:
                take = 9999  # No other moves are taken
                over = True
                result = {'result': 'draw'}
            if over:
                # The game is over, so reset the game--this actually doesn't seem to work with the runserver though for
                # some reason.  You actually have to stop and restart the runserver to reset the game.  Not sure why.
                Game.reset()
            # Set up the response dictionary and resturn as JSON for handling by the UI
            context['move'] = take
            context['over'] = over
            context['result'] = result
            return HttpResponse(json.dumps(context), content_type="application/json")
        except Exception:
            print traceback.format_exc()
            raise Http404
    return render(request, 'standard.html')
Exemple #17
0
    def test_too_many_players(self):
        player_names = [
            "Watson", "Walace", "Profet", "Grant", "Buss", "Lenski",
            "Dobzhansky"
        ]

        self.assertRaises(ValueError, lambda: Game(player_names))
Exemple #18
0
def play_games(black: AI, white: AI):
    players = {"B": black, "W": white}
    engines = {"B": black.get_engine(), "W": white.get_engine()}
    tag = f"{black.name} vs {white.name}"
    try:
        game = Game(Logger(), engines, {"init_size": BOARDSIZE})
        game.root.add_list_property("PW", [white.name])
        game.root.add_list_property("PB", [black.name])
        start_time = time.time()
        while not game.ended:
            p = game.current_node.next_player
            move = ai_move(game, players[p].strategy, players[p].ai_settings)
        while not game.current_node.analysis_ready:
            time.sleep(0.001)
        game.game_id += f"_{game.current_node.format_score()}"
        print(
            f"{tag}\tGame finished in {time.time()-start_time:.1f}s  {game.current_node.format_score()} -> {game.write_sgf('sgf_selfplay/')}",
            file=sys.stderr)
        score = game.current_node.score
        if score > 0.3:
            black.elo_comp.beat(white.elo_comp)
        elif score > -0.3:
            black.elo_comp.tied(white.elo_comp)

        results[tag].append(score)
        all_results.append((black.name, white.name, score))

    except Exception as e:
        print(f"Exception in playing {tag}: {e}")
        print(f"Exception in playing {tag}: {e}", file=sys.stderr)
        traceback.print_exc()
        traceback.print_exc(file=sys.stderr)
Exemple #19
0
 def test_snapback(self):
     b = Game(MockKaTrain(), MockEngine(), {}, board_size=9)
     for move in ["C1", "D1", "E1", "C2", "D3", "E4", "F2", "F3", "F4"]:
         b.play(Move.from_gtp(move, player="B"))
     for move in ["D2", "E2", "C3", "D4", "C4"]:
         b.play(Move.from_gtp(move, player="W"))
     assert 5 == len(self.nonempty_chains(b))
     assert 14 == len(b.stones)
     assert 0 == len(b.prisoners)
     b.play(Move.from_gtp("E3", player="W"))
     assert 4 == len(self.nonempty_chains(b))
     assert 14 == len(b.stones)
     assert 1 == len(b.prisoners)
     b.play(Move.from_gtp("D3", player="B"))
     assert 4 == len(self.nonempty_chains(b))
     assert 12 == len(b.stones)
     assert 4 == len(b.prisoners)
Exemple #20
0
def run():

	game = Game("Pong")
	game.start()

	# create and start the controller
	controller = Controller(game)
	controller.start()

	# keep looping the game
	while True:

		# tell the controller to get the next frame
		controller.go()

		# add a little render delay
		# 60 fps
		game.delay(.016)
Exemple #21
0
def main():
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.DEBUG,
        datefmt='%Y/%m/%d %H:%M:%S')
    #filename=...  #  logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)
    # https://docs.python.org/3/library/logging.config.html#module-logging.config
    log.info("Game started")
    Game().run()
    log.info("Game finished")
    def test_play_runs_the_correct_methods(self):
        board_state = [[None]]
        board_state_after_ship_placed = [['AC', 'AC', 'AC', 'AC', 'AC']]
        user_shot_choice = 'A1'
        ship_orientation = 'row'
        shot_result = 'Hit'
        current_ship = {
            'name': 'Aircraft Carrier',
            'size': 5,
            'hit_locations': [[0, 0]]
        }

        self.comp_board = MagicMock()
        self.comp_board.state = MagicMock(return_value=board_state)
        self.comp_board.add_to_board = MagicMock(
            return_value=board_state_after_ship_placed)
        self.comp_board.update = MagicMock()
        self.comp_board.all_ships = MagicMock(
            return_value=self.board_helper.all_ships)
        self.validate = MagicMock()
        self.validate.shot_result = MagicMock(return_value=('Hit',
                                                            current_ship))
        self.validate.all_ships_sunk = MagicMock(side_effect=[False, True])
        self.ai.shoot_at_board = MagicMock(return_value=('Hit', current_ship))
        self.ui.get_input = MagicMock(return_value=user_shot_choice)
        self.ui.display = MagicMock()
        self.ui.game_board = MagicMock()
        self.ui.ship_messages = MagicMock()

        new_game = Game(self.comp_board, self.human_board, self.ai, self.ui,
                        self.validate, self.place)
        new_game.play()

        self.comp_board.add_to_board.assert_called_with(
            self.place, ship_orientation)
        self.ui.display.assert_called()
        self.comp_board.update.assert_called_with(user_shot_choice,
                                                  shot_result)
        self.validate.all_ships_sunk.assert_called()
        self.ai.shoot_at_board.assert_called_with(self.human_board)
        self.ui.game_board.assert_called()
        self.ui.ship_messages.assert_called()
Exemple #23
0
class TestGetLegalMoves(unittest.TestCase):
    def setUp(self):
        self.game = Game()
        self.state = State(c.EMPTY_BOARD)

        self.state.board[1][2] = 'white_knight'
        self.state.board[5][7] = 'black_knight'
        self.state.board[3][3] = 'white_pawn'
        self.state.board[3][4] = 'black_king'

        self.state.pieces['white_knight'].add((1, 2))
        self.state.pieces['black_knight'].add((5, 7))
        self.state.pieces['white_pawn'].add((3, 3))
        self.state.pieces['black_king'].add((3, 4))

    def test_knight(self):
        self.assertSetEqual(
            self.game._get_normal_moves('white_knight', (1, 2), self.state),
            {((1, 2), (0, 0)), ((1, 2), (0, 4)), ((1, 2), (2, 0)),
             ((1, 2), (2, 4)), ((1, 2), (3, 1))})

    def test__is_attacked(self):
        self.assertTrue(self.game._is_attacked(self.state, (3, 3)))
        self.assertFalse(self.game._is_attacked(self.state, (3, 4)))

    def test_pseudo_move(self):
        self.state.player = 'black'
        self.assertIn(((3, 4), (2, 4)),
                      self.game._get_pseudolegal_moves(self.state))
        self.assertNotIn(((3, 4), (2, 4)),
                         self.game.get_legal_moves(self.state))

    def test_repetition(self):
        old_state = State(c.DEFAULT_POSITION)
        new_state = State(c.DEFAULT_POSITION)
        Game._add_repetition(new_state, old_state)
        old_state = copy.deepcopy(new_state)
        Game._add_repetition(new_state, old_state)
        old_state = copy.deepcopy(new_state)
        Game._add_repetition(new_state, old_state)
        print(new_state.repetition_counter)
        self.assertEqual(new_state.winner, 'draw')
Exemple #24
0
def main():
	print "Welcome to digital Snap!\n"

	# Get any command line arguments supplied
	commandLineArguments = getCommandLineArguments()

	# Request number of packs
	numberOfPacks = commandLineArguments.numberOfPacks \
		if cardService.isValidNumberOfPacks(commandLineArguments.numberOfPacks) else getNumberOfPacks()

	# Request number of players
	numberOfPlayers = commandLineArguments.numberOfPlayers \
		if playerService.isValidNumberOfPlayers(commandLineArguments.numberOfPlayers) else getNumberOfPlayers()

	# Request game rules
	gameRules = commandLineArguments.gameRules if commandLineArguments.gameRules is not None else getGameRules()

	# Start the simulation
	game = Game(numberOfPacks, playerService.getNPCs(numberOfPlayers), gameRules)
	game.run()
Exemple #25
0
 def __init__(self, m):
     self.screen = pygame.display.set_mode((width, height),
                                           pygame.DOUBLEBUF)
     self.manager = m
     self.bg = Base().isurf(pygame.Surface(self.screen.get_size()),
                            (0, 0)).render((0, 0, 0))
     self.ms = [
         Game(),
     ]
     self.fps = fps
     self.clock = pygame.time.Clock()
     self.stat = Stat(self.clock, (0, 255, 0))
Exemple #26
0
def nsa(request, **kwargs):
    """The NSA game.

    They're always listening...

    Basically, the "NSA" listens to every event, so even a hover by the human triggers a move by the NSA.  With each
    move, the occupied positions are sent to the view to determine when there is a win.  Ironically, in this game, only
    NSA moves are recorded, so naturally, the human can't win against the NSA.  (Just like life, man)"""

    move = kwargs.get('move', None)
    if move:
        try:
            g = Game()
            over = False
            result = {'result': ''}
            context = dict()
            g.take('machine', int(move))
            winner = g.winner('machine')
            if winner:
                over = True
                result = {'result': list(winner)}
            context['move'] = 999
            context['over'] = over
            context['result'] = result
            return HttpResponse(json.dumps(context), content_type="application/json")
        except:
            raise Http404
    Game.reset()
    return render(request, 'nsa.html')
Exemple #27
0
 def test_merge(self):
     b = Game(MockKaTrain(), MockEngine(), {}, board_size=9)
     b.play(Move.from_gtp("B9", player="B"))
     b.play(Move.from_gtp("A3", player="B"))
     b.play(Move.from_gtp("A9", player="B"))
     assert 2 == len(self.nonempty_chains(b))
     assert 3 == len(b.stones)
     assert 0 == len(b.prisoners)
Exemple #28
0
 def test_collide(self):
     b = Game(MockKaTrain(), MockEngine(), {}, board_size=9)
     b.play(Move.from_gtp("B9", player="B"))
     with pytest.raises(IllegalMoveException):
         b.play(Move.from_gtp("B9", player="W"))
     assert 1 == len(self.nonempty_chains(b))
     assert 1 == len(b.stones)
     assert 0 == len(b.prisoners)
Exemple #29
0
def testTemplarAbility():
    game = Game(templars.Templar, templars.Templar)
    p0 = game.players[0]
    p1 = game.players[1]
    game.start()
    # empty mulligans
    p0.mulligan()
    p1.mulligan()

    p0.endTurn(p0.hand[0])

    assert len(p0.hand) == 4  # First player penalty
    assert p0.manaCap == 3

    p1.endTurn(None)

    assert len(p1.hand) == 6
    assert p1.manaCap == 2

    # Try discarding something not in your hand
    p0.endTurn(p1.hand[0])
    assert len(p1.hand) == 6
    assert p0.manaCap == 4
Exemple #30
0
    def setUp(self):
        self.game = Game()
        self.state = State(c.EMPTY_BOARD)
        self.state.castle_rights = {
            'white_king_side': True,
            'white_queen_side': True,
            'black_king_side': True,
            'black_queen_side': True
        }

        self.state.board[1][3] = 'white_pawn'
        self.state.board[7][6] = 'white_pawn'
        self.state.board[2][3] = 'black_queen'
        self.state.board[7][7] = 'white_rook'
        self.state.board[1][2] = 'black_pawn'
        self.state.board[7][4] = 'white_king'

        self.state.pieces['white_pawn'].add((1, 3))
        self.state.pieces['white_pawn'].add((7, 6))
        self.state.pieces['black_queen'].add((2, 3))
        self.state.pieces['white_rook'].add((7, 7))
        self.state.pieces['black_pawn'].add((1, 2))
        self.state.pieces['white_king'].add((7, 4))
Exemple #31
0
def make_move(request):
    """
    Make the human player's move and then calculate and make computer's move
    """
    # Load board and move information
    board = json.loads(request.GET['board'])
    box = int(request.GET['box'].replace("box_", ""))
    game_history_id = request.GET['game_history_id']

    # Make player's move and check game result
    game = Game(board)
    game.make_move(box, PLAYER)
    game_over, winning_combination = game.check_game_over()
    computer_played = False

    # If game is still on calculate computer's move and make it
    if not game_over:
        box = game.best_next_move(COMPUTER)
        game.make_move(box, COMPUTER)
        computer_played = True
        game_over, winning_combination = game.check_game_over()

    # If game is over save game history
    if game_over:
        game_history = GameHistory.objects.get(pk=game_history_id)
        game_history.finish_game(game_over)

    result = {}
    result['computer_played'] = computer_played
    result['box'] = str(box)
    result['game_over'] = game_over
    result['board'] = json.dumps(game.get_board())

    # set winning combinations for highlighting
    result['winning_combination'] = winning_combination

    return HttpResponse(json.dumps(result), mimetype='application/json')
Exemple #32
0
    def run_game(self):
        """
        Run the game.

        Will run the game this program is all about. After the game it will
        collect results and possibly list the player in the Highscores list.

        """

        g = Game(self.args.level, self.args.questions)
        start_time = time()

        try:
            g.run()
        except StopGame:
            print '\nbye!'
            exit()

        endtime = time() - start_time

        r = Results(self.args.level, self.args.questions, g.mistakes, endtime)
        r.print_results()

        Highscores().new(r)
Exemple #33
0
    def start():
        pygame.init()
        pygame.display.set_caption('PyDungeon')
        size = width, height = (640, 480)
        game = Game()
        game.setup_default_components(size)
        scene = game.scene

        tilemap = Entity()
        scene.add_entity(tilemap)
        tilemap.add_component(NameComponent("tilemap"))

        tilemap.add_component(TransformComponent(Vector2(0, 0)))

        ts = TileSet()
        ts.load("assets/tileset.png", "assets/tileinfo.info")
        tm = TileMap(ts, size)
        mp = [[["floor_" + str(random.randrange(1, 8))] for _ in range(24)]
              for _ in range(24)]
        PyDungeons.build_wall_rect(mp, pygame.Rect(2, 2, 10, 10))
        tm.load_letters(mp)
        tilemap.add_component(tm)
        tilemap.add_component(
            TileMapCollider(
                tm, ["wall_mid", "wall_side_mid_right", "wall_side_mid_left"]))
        tilemap.add_component(RendererComponent(TileMapRenderer(), size))

        player = Entity()
        scene.add_entity(player)
        player.add_component(NameComponent("player"))

        key_bindings = [[pygame.K_a], [pygame.K_d], [pygame.K_w], [pygame.K_s]]

        player.add_component(MoveComponent(1, 2))
        player.add_component(KeyControlComponent(key_bindings))
        #player.add_component(ScreenBoundsCollisionHandler(pygame.Rect(0, 0, width, height)))
        player.add_component(TransformComponent(Vector2(100, 100)))
        player.add_component(BoxCollider((16 * 2, 22 * 2), Vector2(0, 12)))
        player.add_component(
            RendererComponent(TileRenderer(ts.tiles["knight_f_idle_anim"], ts),
                              (16 * 2, 28 * 2)))
        #player.add_component(RendererComponent(ImageRenderer("assets/tileset.png"), (1000, 1000)))

        game.add_component(ExitOnEscape())

        game.run()
Exemple #34
0
def jerk(request, **kwargs):
    """The Jerk Computer game.

    This is the opponent that accomplishes exactly what the instructions say--never lose--but
    he's kind of a jerk about it.  He doesn't follow the official tic-tac-toe rules (it's not explicitly required by
    the instructions)."""

    move = kwargs.get('move', None)
    if move:
        winners = []
        sleep(1) # Again, just make it feel like a bit of thinking, just for "realism" of the game play.
        for v in WIN_VECTORS:
            # Iterate over the possible wins.  Store all vectors that do not include the human's move.
            if int(move) not in v:
                winners.append(list(v))
        # Just to make it a bit more interesting, return a randomly selected win vector from the matches so it's not
        # the same one every time you play.
        winner = winners[random.randint(0, len(winners) - 1)]
        context = dict(
            winner=winner
        )
        Game.reset()
        return HttpResponse(json.dumps(context), content_type="application/json")
    return render(request, 'jerk.html')
Exemple #35
0
def main():
    logging.basicConfig()
    client1 = c.Client(g.MUSTARD, 'www.mocky.io/v2', '')
    client2 = c.Client(g.SCARLET, 'www.mocky.io/v2', '')
    client3 = c.Client(g.WHITE, 'www.mocky.io/v2', '')
    game = Game([client1, client2, client3])
    game.take_turn()
    game.take_turn()
    game.take_turn()
    print('Done!')
Exemple #36
0
 def test_repetition(self):
     old_state = State(c.DEFAULT_POSITION)
     new_state = State(c.DEFAULT_POSITION)
     Game._add_repetition(new_state, old_state)
     old_state = copy.deepcopy(new_state)
     Game._add_repetition(new_state, old_state)
     old_state = copy.deepcopy(new_state)
     Game._add_repetition(new_state, old_state)
     print(new_state.repetition_counter)
     self.assertEqual(new_state.winner, 'draw')
Exemple #37
0
    def drawMainMenu(self):
        x = self.win.getXSize()
        y = self.win.getYSize()

        self.background = OnscreenImage(image='textures/main_menu.png')

        self.background.setSx(x / y)

        clickNewGameButton = lambda: self.push(Game())
        clickOptionsButton = lambda: self.push('Options')
        clickExitButton = lambda: sys.exit()

        def setButtonAttributes(button):
            button.setSx(.60)
            button.setSz(.26)
            button.setTransparency(TransparencyAttrib.MAlpha)

        maps = loader.loadModel('textures/continue_maps.egg')
        geom = (maps.find('**/continue'),
                maps.find('**/continue_click'),
                maps.find('**/continue_hover'))
        self.newGameButton = DirectButton(geom=geom, relief=None,
                                          command=clickNewGameButton)
        setButtonAttributes(self.newGameButton)
        self.newGameButton.setPos(0, 0, .6)

        maps = loader.loadModel('textures/options_maps.egg')
        geom = (maps.find('**/options'),
                maps.find('**/options_click'),
                maps.find('**/options_hover'))
        self.optionsButton = DirectButton(geom=geom, relief=None,
                                          command=clickOptionsButton)
        setButtonAttributes(self.optionsButton)
        self.optionsButton.setPos(0, 0, .36)

        maps = loader.loadModel('textures/exit_maps.egg')
        geom = (maps.find('**/exit'),
                maps.find('**/exit_click'),
                maps.find('**/exit_hover'))
        self.exitButton = DirectButton(geom=geom, relief=None,
                                       command=clickExitButton)
        setButtonAttributes(self.exitButton)
        self.exitButton.setPos(0, 0, .12)

        self.hasDrawnMainMenu = True
Exemple #38
0
def make_move(request):
    """
    Make the human player's move and then calculate and make computer's move
    """
    # Load board and move information
    board = json.loads(request.GET['board'])
    box = int(request.GET['box'].replace("box_",""))
    game_history_id = request.GET['game_history_id']

    # Make player's move and check game result
    game = Game(board)
    game.make_move(box, PLAYER)
    game_over, winning_combination = game.check_game_over()
    computer_played = False

    # If game is still on calculate computer's move and make it
    if not game_over:
        box = game.best_next_move(COMPUTER)
        game.make_move(box, COMPUTER)
        computer_played = True
        game_over, winning_combination = game.check_game_over()

    # If game is over save game history
    if game_over:
        game_history = GameHistory.objects.get(pk=game_history_id)
        game_history.finish_game(game_over)

    result = {}
    result['computer_played'] = computer_played
    result['box'] = str(box)
    result['game_over'] = game_over
    result['board'] = json.dumps(game.get_board())

    # set winning combinations for highlighting
    result['winning_combination'] = winning_combination

    return HttpResponse(json.dumps(result), mimetype='application/json')
Exemple #39
0
    def _parse_map_symbol(self, symbol: str, x: int, y: int,
                          game: Game) -> None:
        """
        Creates entities corresponding to the symbol.
        """
        if symbol == "#":  # Destructible wall
            tile = DestructibleWall(x=x * constants.TILE_SIZE,
                                    y=y * constants.TILE_SIZE,
                                    batch=game.background_batch)
            self.map[x, y] = tile

        if symbol == "$":  # Indestructible wall
            tile = Wall(x=x * constants.TILE_SIZE,
                        y=y * constants.TILE_SIZE,
                        batch=game.background_batch)
            self.map[x, y] = tile

        if symbol == "+":  # Bush
            tile = Bush(x=x * constants.TILE_SIZE,
                        y=y * constants.TILE_SIZE,
                        batch=game.foreground_batch)
            self.map[x, y] = tile

        if symbol == "F":  # The flag
            tile = Flag(x=x * constants.TILE_SIZE,
                        y=y * constants.TILE_SIZE,
                        batch=game.batch)
            self.map[x, y] = tile
            game.game_director.flag = tile

        if symbol == "P":  # The player (not saved into the map array)
            player = Player(
                x=x // 2 * constants.TANK_SIZE + constants.TANK_SIZE // 2,
                y=y // 2 * constants.TANK_SIZE + constants.TANK_SIZE // 2,
                batch=game.batch)
            game.entity_manager.add_entity(game.register_player(player))
            game.game_director.player = player
            game.game_director.player_spawn_point = (x, y)

        else:
            pass
Exemple #40
0
def request_game():
    start_request = StartGameRequest.from_dict(dict(request.args))

    player_count = len(APP.waiting_clients)
    if player_count < MIN_PLAYERS:
        response = StartGameResponse(client_id=start_request.client_id,
                                     game_id='')
        return jsonify(response.to_dict())

    if player_count > MAX_PLAYERS:
        game_clients = APP.waiting_clients[:MAX_PLAYERS - 2]
        game_clients.append(APP.get_client(start_request.client_id))
    else:
        game_clients = APP.waiting_clients
    game = Game(game_clients)
    APP.games.append(game)
    APP.start_game(game.game_id)

    response = StartGameResponse(client_id=start_request.client_id,
                                 game_id=game.game_id)
    return jsonify(response.to_dict())
Exemple #41
0
    def startGame(self):
        """Perform final player checks and start game."""
        users = self.getUsers()
        sock = users[0]  # Need to get reference to the namespace

        # Prevent game from restarting if a full room empties and refills
        if self.started:
            sock[SOCKETIO_NS].emit_to_room(
                'chat',
                ['System',
                 "This game already started, so I won't start a new one."])
            return

        # Ensure all seats filled
        if len(self.getAvailableSeats()) > 0:
            # Something has gone wrong
            log.error("bad seating error in startGame()")
            sock[SOCKETIO_NS].emit_to_room('err', 'Problem starting game')
            return

        # Send out the final seat chart
        sock[SOCKETIO_NS].emit_to_room('seatChart', self.getSeatingChart())

        self.game = Game()
        initData = self.game.start_game(self.getUsernamesInRoom())

        # Send initial game data to players
        log.debug("Sending initial game data in room %s", self.num)
        sock[SOCKETIO_NS].emit_to_target_room(LOBBY, 'gameStarted', self.num)

        target_sock_map = {s.session['seat']: s[SOCKETIO_NS]
                           for s in users}

        for msg in initData:
            target_sock_map[msg['tgt']].emit('startData', msg)

        self.started = True
Exemple #42
0
class TicTacToeTest(unittest.TestCase):

    def setUp(self):
        self.board = Game()

    def tearDown(self):
        self.board.reset()

    def test_001(self):
        """Test the available move checker"""

        moves = self.board.available
        # Make sure all moves are available
        self.assertTrue(len(moves) == 9, 'Not all moves are available')
        self.assertTrue(moves == [0, 1, 2, 3, 4, 5, 6, 7, 8], 'Available moves do not match')

    def test_002(self):
        """Test position setter"""

        self.board.take('machine', 4)  # Machine takes center position
        moves = self.board.available
        self.assertTrue(len(moves) == 8, 'Position not taken')
        self.assertTrue(moves == [0, 1, 2, 3, 5, 6, 7, 8], 'Available moves do not match')

    def test_003(self):
        """Test win detection"""

        self.board.take('machine', 1)
        # At this point we shoulnd't have a winner yet
        self.assertFalse(self.board.winner('machine'), 'We have a winner')
        self.board.take('machine', 7)
        # Now the machine player should have won
        self.assertTrue(self.board.winner('machine'), '{0} is not the winner'.format(PLAYERS['machine']))
        self.assertTrue(self.board.winner('machine') == (1, 4, 7), 'Unexpected winning vector')

    def test_004(self):
        """Test win detection"""

        self.board.clear('machine', 1)
        # Now the machine player should have a winning move available
        self.assertTrue(self.board.winnable('machine') == 1, 'Exptected to be able to win')

    def test_005(self):
        """Test game evaulation -- Winning move"""

        self.board.take('human', 0)
        self.board.take('human', 3)
        move = self.board.eval_tree('machine')
        self.assertTrue(move == 1, 'Expected to choose position 1 for the win')

    def test_006(self):
        """Test game evaluation -- Blocking move"""

        Game.reset()
        self.board.take('human', 4)
        self.board.take('human', 2)
        self.board.take('machine', 0)
        self.board.take('machine', 1)
        move = self.board.eval_tree('machine')
        self.assertTrue(move == 6, 'Expected to choose position 6 for the block')

    def test_007(self):
        """Test game evaluation - minimax."""

        Game.reset()
        self.board.take('human', 0)
        self.board.take('human', 4)
        self.board.take('machine', 8)
        move = self.board.next_move()
        self.assertTrue(move == 2 or move == 6, 'Expected to choose position 2 or 6 to lead to a draw')
Exemple #43
0
 def setUp(self):
     self.board = Game()
Exemple #44
0
class Room(object):
    """Container class for a game and users.

    To improve data management, a Room does not directly reference players.
    Instead, each player (socket connection) keeps their room number in their
    session and the Room object is located on-demand. This normalizes the data
    relationship and keeps the Room from maintaining an internal player list
    that could get out of sync with reality.

    Attributes:
      server (Server): Pointer to active server object.
      num (int): The room ID number.
      game (core.game Game): Game object.
      users (list of sockets): The users in the room.
      started (boolean): If a game has been started in this room.

    """
    server = None

    def __init__(self, roomNum):
        """Create a new Room with a given room number.

        Args:
          roomNum (int): The specified room number for identification purposes.

        """
        self.num = roomNum
        self.game = None
        self.started = False

    def __str__(self):
        """Return a label for the room, with special handling for the Lobby."""
        if self.num == LOBBY:
            return "Lobby"
        else:
            return "Room %i" % self.num

    def __del__(self):
        """Safely delete the Room."""
        log.debug("TODO: safely end game.")

    def getUsers(self):
        """Return list of sockets for clients in this room."""
        return [x for x in self.server.sockets.values()
                if 'roomNum' in x.session and x.session['roomNum'] == self.num]

    def getUsernamesInRoom(self):
        """Return list of all users' nicknames in this room.

        This method ensures the names are in seat order. If we implement
        username listing for the lobby, this will have to be modified.

        """
        names = [''] * NUM_PLAYERS
        for sock in self.getUsers():
            names[sock.session['seat']] = sock.session['nickname']
        return names

    def isFull(self):
        """Check if the room is full and return a boolean.

        Lobby cannot fill up.

        """
        if self.num == LOBBY:  # Lobby never fills
            return False
        elif len(self.getUsers()) == MAX_ROOM_SIZE:
            return True
        else:
            return False

    def getAvailableSeats(self):
        """Return list of unoccupied seat numbers in the room.

        FUTURE: The seat `-1` is the non-seat/observer seat and
        is always available.

        """
        allSeats = list(range(0, MAX_ROOM_SIZE))  # + [-1]
        if self.num == LOBBY:
            return allSeats
        else:
            usedSeats = [x.session['seat'] for x in self.getUsers()]
            availableSeats = [x for x in allSeats if x not in usedSeats]
            return availableSeats

    def getSeatingChart(self):
        """Return a seating chart for the room.

        If a user does not have a seat, they are given seat = -1.

        Returns:
          list: (username, seat number) pairs for users in the room.

        """
        seatChart = []
        for sock in self.getUsers():
            name = sock.session['nickname']
            if sock.session['seat'] is None:
                seat = -1
            else:
                seat = sock.session['seat']

            seatChart.append((name, seat))

        return seatChart

    def startGame(self):
        """Perform final player checks and start game."""
        users = self.getUsers()
        sock = users[0]  # Need to get reference to the namespace

        # Prevent game from restarting if a full room empties and refills
        if self.started:
            sock[SOCKETIO_NS].emit_to_room(
                'chat',
                ['System',
                 "This game already started, so I won't start a new one."])
            return

        # Ensure all seats filled
        if len(self.getAvailableSeats()) > 0:
            # Something has gone wrong
            log.error("bad seating error in startGame()")
            sock[SOCKETIO_NS].emit_to_room('err', 'Problem starting game')
            return

        # Send out the final seat chart
        sock[SOCKETIO_NS].emit_to_room('seatChart', self.getSeatingChart())

        self.game = Game()
        initData = self.game.start_game(self.getUsernamesInRoom())

        # Send initial game data to players
        log.debug("Sending initial game data in room %s", self.num)
        sock[SOCKETIO_NS].emit_to_target_room(LOBBY, 'gameStarted', self.num)

        target_sock_map = {s.session['seat']: s[SOCKETIO_NS]
                           for s in users}

        for msg in initData:
            target_sock_map[msg['tgt']].emit('startData', msg)

        self.started = True
Exemple #45
0
	def setUp(self):
		self.stdout = sys.stdout
		sys.stdout = TestStdout()
		self.game = Game(1, getNPCs(2), ValueAndSuitRules())
Exemple #46
0
class TestGame(unittest.TestCase):
	def setUp(self):
		self.stdout = sys.stdout
		sys.stdout = TestStdout()
		self.game = Game(1, getNPCs(2), ValueAndSuitRules())

	def tearDown(self):
		sys.stdout = self.stdout

	def testInit(self):
		self.failUnlessEqual(len(self.game.deck), 52)
		self.failUnlessEqual(len(self.game.pot), 0)

	def testRun(self):
		self.game._run(lambda: "")
		self.failUnlessEqual(len(self.game.deck), 0)

	def testProcessSnap(self):
		pot = [Card("2", "h"), Card("j", "c")]
		self.game.players[0].snapResponseTime = 1
		self.game.players[1].snapResponseTime = 2
		self.game.pot = pot[:]
		self.game.processSnap()
		self.failUnlessEqual(self.game.players[0]._cards, pot)
		self.failUnlessEqual(self.game.players[1]._cards, [])
		self.failUnlessEqual(len(self.game.pot), 0)

	def testProcessNoSnap(self):
		cards = [Card("2", "h"), Card("j", "c"), Card("a", "s")]
		self.game.players[0].snapResponseTime = 1
		self.game.players[0]._cards = cards
		self.game.processNoSnap()
		self.failUnlessEqual(self.game.players[0]._cards, cards[0:1])

	def testAnnounceWinner(self):
		cards = [Card("2", "h")]
		self.game.players[0]._cards = cards
		self.game._announceWinner(lambda: "")
		self.failUnless("%s won the game with %i cards!" % (self.game.players[0].name, len(cards)) in TestStdout.written)

	def testAnnounceWinnerDraw(self):
		cards = [Card("2", "h")]
		self.game.players[0]._cards = cards
		self.game.players[1]._cards = cards
		self.game._announceWinner(lambda: "")
		self.failUnless("%s drew the game with %i cards each!"
			% (' & '.join([player.name for player in self.game.players]), len(cards)) in TestStdout.written)

	def testCheckRematch(self):
		cards = [Card("2", "h")]
		cards2 = [Card("a", "s")]
		self.game.players[0]._cards = cards[:]
		self.game.players[1]._cards = cards2[:]
		self.game._checkRematch(lambda: True, lambda: "")
		self.failUnlessEqual(self.game.players[0]._cards, [])
		self.failUnlessEqual(self.game.players[1]._cards, [])
		self.failUnlessEqual(len(self.game.deck), 52)
		self.failUnlessEqual(self.game.pot, [])
Exemple #47
0
def main():
    i = Game()
    i.play()