def test_board_check_all_directions(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) checker = Checker(0, 0, RED, RED_BASE, BLUE_BASE, 50) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) board.board = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, checker, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ] assert board.check_all_directions(1, 1) == [(2, 1), (1, 0), (1, 2), (0, 1), (2, 0), (3, 3), (0, 0), (0, 2)] assert board.check_all_directions(0, 0) == [(1, 0), (0, 1)]
def handle_login(): username = escape(request.form.get("username", str, None)) if not username: return {"error": "bad_request"}, 400 session['username'] = username session['uuid'] = game.get_uuid() if game.get_player_count() == 2: game.add_spectator(Spectator(username)) session['type'] = 'spectator' elif game.get_x_player() is None: game.set_x_player(Player(username, 'X')) session['type'] = 'player' session['player'] = 'X' else: game.set_o_player(Player(username, 'O')) session['type'] = 'player' session['player'] = 'O' game.set_status(1) socketio.emit('game', get_game(), broadcast=True, include_self=False, namespace='/', skip_sid=True) return { k: v for k, v in session.items() if k in ('username', 'type', 'player') }, 201
def reset(self): '''reset the environment, called at the beginning of each episode :return curr_state (1d array): current state''' pygame.init() self.done = False # Clock for framerate self.clock = pygame.time.Clock() # screen self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Create custom events for adding a new enemy and cloud self.ADDENEMY = pygame.USEREVENT + 1 pygame.time.set_timer(self.ADDENEMY, self.enemy_timer) self.ADDCLOUD = pygame.USEREVENT + 1 pygame.time.set_timer(self.ADDCLOUD, self.cloud_timer) # Create our 'player' self.player = Player() # Create groups to hold enemy sprites, cloud sprites, and all sprites self.enemies = pygame.sprite.Group() self.clouds = pygame.sprite.Group() self.all_sprites = pygame.sprite.Group() self.all_sprites.add(self.player) curr_state = self.__get_curr_state() return curr_state
def test_board_cut_path(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) checker = Checker(0, 0, RED, RED_BASE, BLUE_BASE, 50) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) board.board = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, checker, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [0, 0, 0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] assert board.cut_path((1, 1), (7, 5)) == [(1, 1), (3, 3), (5, 3), (7, 3), (7, 5)] assert board.cut_path((1, 1), (3, 3)) == [(1, 1), (3, 3)]
def start_new_game(self) -> Optional[Model]: """ Check if a new game can be started, and if so, start it. :return: the new Model object if a game was started, otherwise None """ if len(self.new_game_queue) >= 2: sid1, sid2 = self.new_game_queue[:2] s1 = self._sessions[sid1] s2 = self._sessions[sid2] self.new_game_queue = self.new_game_queue[2:] # Create associated players p1, p2 = Player(s1.username), Player(s2.username) game = Game([p1, p2]) model = Model(game) model.register_view(ServerView(sid1, self)) model.register_view(ServerView(sid2, self)) s1.start_game(model) s2.start_game(model) print("Started game between {} and {}".format(p1.name, p2.name)) s1.outb += self.pack({'type': 'new-game-request-reply', 'data': {'status': 'success', 'game-state': ViewGameState.from_game(game, 0), 'player-number': 0}}) s2.outb += self.pack({'type': 'new-game-request-reply', 'data': {'status': 'success', 'game-state': ViewGameState.from_game(game, 1), 'player-number': 1}}) return Model(game) else: return None
def test_game_init(self): p1 = Player("p1") p2 = Player("p2") pl = [p1, p2] g = Game(pl) self.assertEqual(len(g.players), 2, "players list is 2") self.assertEqual(len(g.deck.cards), 52, "deck cards list is 52")
def testPerform(self): slot = TableSlot() player = Player("Test", None, None, MinBettingPolicy()) slot.seatPlayer(player) shoe = Shoe(1,lambda x:x) hitCmd = HitCommand(shoe) standCmd = StandCommand() splitCmd = SplitCommand(hitCmd, standCmd) player.receive_payment(cfg['MINIMUM_BET'] * (1 + cfg['SPLIT_RATIO'])) slot.addCards(Card(5,'C'), Card(5,'H')) slot.promptBet() rc = splitCmd.perform(slot) self.assertFalse(rc, 'testSplitCommand:testPerform:Split should not end hand') self.assertEqual(player.stack.amount, 0, 'testSplitCommand:testPerform:Split should deduct appropriate amount from player') hands = slot.hands self.assertEqual(len(hands), 2, 'testSplitCommand:testPerform:Split should split player\'s hand into two hands') self.assertTrue(hands[0].wasSplit, 'testSplitCommand:testPerform: Split hands should reflect split') self.assertTrue(hands[1].wasSplit, 'testSplitCommand:testPerform: Split hands should reflect split') expected = BlackjackHand() expected.addCards(Card(5,'C'), Card(2, 'S')) self.assertEqual(hands[0], expected, 'testSplitCommand:testPerform:Split hands should draw next card from shoe') expected.reset() expected.addCards(Card(5,'H'), Card(2, 'H')) self.assertEqual(hands[1], expected, 'testSplitCommand:testPerform:Split hands should draw next card from shoe')
def test_start(self) -> None: players = [Player("a"), Player("b")] game = Game() game.start(players) assert set(game.players) == set(players) assert len(game.fields) == len(players)
def test_move_valid_2(): player = Player(TestWorldEmpty) player.up() player.right() assert player.position == (2, 0)
def test_board_get_all_jumps_from_square(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) checker = Checker(0, 0, RED, RED_BASE, BLUE_BASE, 50) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) board.board = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, checker, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, checker, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ] assert board.get_all_jumps_from_square(1, 1) == [(3, 3)] assert board.get_all_jumps_from_square(4, 3) == [(4, 5), (2, 5)]
def __init__(self, screen, team=None): self.player1 = Player(self, 1) self.player2 = Player(self, 2) self.running = False self.going_player = self.player2 self.board = Board(screen, self)
def thread_client(conn, player_num): #유저 한 명의 스레드 생성 global cur_player players[player_num - 1].start_game() #유저가 2명인 지 확인 conn.send(pickle.dumps(players[player_num - 1])) while True: try: data = pickle.loads(conn.recv(2048 * 3)) #데이터를 서버로부터 받음 players[player_num - 1] = data if not data: print("disconnected") break else: if player_num == 1: #reply는 상대방 객체를 뜻함 reply = players[1] else: reply = players[0] conn.sendall(pickle.dumps(reply)) #reply를 서버로 보냄 except: break print("lost connection") cur_player -= 1 if player_num == 1: players[player_num - 1] = Player('left', key_set, True) elif player_num == 2: players[player_num - 1] = Player('right', key_set, True) conn.close()
def register(): player: Optional[Player] = get_player_from_request() if not player: name: str = request.json.get("name") if not name: return ErrorResponse.message("Please choose a valid display name.") player = Player(name=request.json["name"]) return jsonify(player.export())
def __init__(self, screen): # if (game_type == "hotseat"): self.player1 = Player(self, 1) self.player2 = Player(self, 2) self.running = False self.going_player = self.player2 self.board = Board(screen, self)
def test_attack(self) -> None: game = Game(10) player_a = Player("a") player_b = Player("b") game.start([player_a, player_b]) game.attack(player_b, "а1", CellState.WOUNDED) assert game.fields[player_b.id][0] == CellState.WOUNDED
def quit(self): # evilynux - self.audio.close() crashes when we attempt to restart if not self.restartRequested: self.audio.close() Player.savePlayers() for t in list(self.tasks + self.frameTasks): self.removeTask(t) self.running = False
def test_player_add_Checker(): player = Player('Zygfryd', RED) assert player.name == 'Zygfryd' assert player.colour == RED assert player.checkers == [] checker1 = Checker(4, 11, BLUE, BLUE_BASE, RED_BASE, 50) player.add_checker(checker1) assert len(player.checkers) == 1
def test_player_add_game(): player = Player('Zygfryd', RED) assert player.name == 'Zygfryd' assert player.colour == RED assert player.checkers == [] game = 'game_object' player.add_game(game) assert player.game == 'game_object'
def deleteCharacter(self): tsYes = _("Yes") q = Dialogs.chooseItem(self.engine, [tsYes, _("No")], _("Are you sure you want to delete this player?")) if q == tsYes: if self.player: Player.deletePlayer(self.player) self.engine.view.popLayer(self) self.engine.input.removeKeyListener(self)
def Task1(self) -> int: player1 = Player(self.data[0]) player2 = Player(self.data[1]) game = Combat(player1, player2) game.play() return game.calculateWinner()
def test_finish_empty_match(self): match = Match(max_players=2) match.add_player(Player("Player 1")) match.add_player(Player("Player 2")) self.assertEqual(match.status, Match.Status.RUN) match.remove_player(match.players[0]) self.assertEqual(match.status, Match.Status.RUN) match.remove_player(match.players[1]) self.assertEqual(match.status, Match.Status.FINISH)
class Simulation: def __init__(self): mines = 3 self.player = Player(game=Minesweeper(mines=mines, width=5, height=5)) self.score = 0 self.undiscovered = mines def minesLeft(self): return self.undiscovered - self.score - len(filter(identity, self.player.marked)) def sweep(self): while self.player.sweep(): pass def guess(self): self.score += int(self.player.guess()) def dump(self): self.player.dump() print 'mines hit:', str(self.score) def prompt(self): response = raw_input('') if 's' in response: self.sweep() elif 'g' in response: self.guess() elif 'e' in response: self.player.eliminate() elif 'b' in response: # 'b' for both self.sweep() self.guess() return 'stop' not in response and not self.player.complete() def auto(self, interval=0, verbose=False): while not self.player.complete(): progress = True while progress: progress = False if verbose: print 'Sweeping...' progress = progress or self.sweep() if verbose: print 'Eliminating...' progress = progress or self.player.eliminate() if verbose: print 'Guessing...' self.guess() print 'final score:', str(self.score) def manual(self): while self.prompt(): self.dump() def probabilities(self): prob = Problem(self.player.game.board, self.player.state()) return prob.probabilities(self.minesLeft()) def s(self): self.guess() self.dump()
class TestPlayer(unittest.TestCase): def setUp(self): self.player = Player() self.game = Game() def test_is_Empty(self): self.assertEqual(len(self.player.stack_of_cards), 0) def test_oneCardLess_AfterPlayingTopCard(self): self.player.stack_of_cards.append(Card(9, "swords")) self.player.stack_of_cards.append(Card(9, "clubs")) self.player.playTopCard() self.assertEqual(len(self.player.stack_of_cards), 1) def test_havePlayersHalfDeck(self): self.assertEqual(len(self.game.player1.stack_of_cards), 20) self.assertEqual(len(self.game.player2.stack_of_cards), 20) def test_hasTableOneCardAfterPlayerPlayedIt(self): self.game.playCard() self.assertEqual(len(self.game.table), 1) def test_TableGotOneCardFromPlayer(self): self.game.table = [] self.game.player1.stack_of_cards = [Card(9, "swords")] self.game.playCard() self.assertEqual(self.game.table[0], Card(9, "swords")) self.assertEqual(len(self.game.player1.stack_of_cards), 0) def test_playCardTwice_TableGotTwoCardsFromDifferentPlayers(self): self.game.table = [] self.game.player1.stack_of_cards = [Card(9, "swords")] self.game.player2.stack_of_cards = [Card(9, "clubs")] self.game.playCard() self.game.playCard() self.assertEqual(self.game.table[0], Card(9, "swords")) self.assertEqual(self.game.table[1], Card(9, "clubs")) def test_doesPlayerPlayAgainIfSpecialCardWasPlayed(self): self.game.table = [] self.game.player1.stack_of_cards = [Card(2, "swords")] self.game.player2.stack_of_cards = [Card(7, "clubs"), Card(5, "coins")] self.game.playCard() self.game.playCard() self.game.playCard() self.assertEqual( self.game.table, [Card(2, "swords"), Card(5, "coins"), Card(7, "clubs")])
def test_winner_is_board_solver(self): match = Match(max_players=2) player1 = Player("Player 1") player2 = Player("Player 2") match.add_player(player1) match.add_player(player2) match.get_player_board(player1).solve() match.update_status() self.assertEqual(match.status, Match.Status.FINISH) self.assertEqual(match.winner, player1)
def test_drop_unknown_inventory_item(self): player = Player(gender="male", age="10", hair_color="blue", inventory=[Item("elephant")]) player.location = OutsideRoom() loc_items = len(player.location.items) self.assertEqual(len(player.inventory), 1) player.drop("rock") self.assertEqual(len(player.inventory), 1) self.assertEqual(len(player.location.items), loc_items)
def test_has_moved(self): player = Player(gender="male", age="10", hair_color="blue") # initially, the player starts off by having been "moved" to a # new location self.assertTrue(player.moved) self.assertTrue(player.has_moved()) # after checking for a move, the flag is reset self.assertFalse(player.moved)
def test_board_check_jump_up_right(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) assert board.check_jump_up_right(2, 3) == (0, 5) assert board.check_jump_up_right(1, 4) == None
def test_board_check_jump_down_left(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) assert board.check_jump_down_left(13, 12) == (15, 10) assert board.check_jump_down_left(15, 15) == None
def test_board_space_down(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) assert board.space_down(4, 4) == (5, 4) assert board.space_down(15, 15) == None
def test_board_space_crosswise_down_right(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) assert board.crosswise_down_right(4, 1) == (5, 2) assert board.crosswise_down_right(13, 12) == None
def test_that_construction_is_possible_with_enough_productions(self): right_player = Player({'production': {}}) left_player = Player({'production': {}}) player = Player({'production': {}}) player.with_neighbor(right_player, left_player) player.build_structure(self.structures['Stone Pit']) self.assertEqual(player.build_cost(self.structures['Baths']['cost']), 0)
def do_game(self, agent1, agent2): g = Game.Game(GAME_SIZE, GAME_SIZE, Player.Player(0, 3, 3, GAME_SIZE, GAME_SIZE, decision_maker=agent1, movement=random.choice([[0, 1], [0, -1], [1, 0], [-1, 0]])), Player.Player(1, 11, 11, GAME_SIZE, GAME_SIZE, decision_maker=agent2, movement=random.choice([[0, 1], [0, -1], [1, 0], [-1, 0]]))) for i in range(self.game_length): g.update() if g.done: return g.get_winner() # Update later for victory by score return g.get_winner()
def test_board_get_checker(monkeypatch): def fake_sounds(self): return None WIN = 'window' player1 = Player('ZYGFRYYD', RED) player2 = Player('Radziwił', BLUE) checker = Checker(0, 0, RED, RED_BASE, BLUE_BASE, 50) monkeypatch.setattr('board.Board.get_jump_sounds', fake_sounds) board = Board(50, WIN, player1, player2) assert board.get_checker(0, 0) != 0 assert board.get_checker(8, 8) == 0
def test_describe_key_attributes_of_players( self, game, p0: Player): p0.health = 22 p0.mana_slots = 8 p0.mana = 3 p0_hand = [Card(3), Card(5), Card(1)] p0.hand = p0_hand assert game.status['players']['First']['health'] == 22 assert game.status['players']['First']['mana_slots'] == 8 assert game.status['players']['First']['mana'] == 3 assert game.status['players']['First']['hand'] == p0_hand
def setUp(self): self.game1 = Game() player1 = Player('John') player2 = Player('Paul') self.game1.players["1"] = player1 self.game1.players["2"] = player2 self.game1.kills.append(Kill('1', '2', '5')) self.game1.kills.append(Kill('1', '2', '6')) self.game1.kills.append(Kill('1', '2', '7')) self.game1.kills.append(Kill('1', '2', '8')) self.game1.kills.append(Kill('2', '1', '2')) self.game1.proccess_kills()
async def connect(self): data = await self.communicate("player") username = data.get("name") bot_name = data.get("bot") bot_tile = data.get("tile") if not username or not bot_name or not bot_tile: await self.send_status("400") raise Exception("Bad player data") self.username = str(username) Player.__init__(self, self.game, str(bot_name), int(bot_tile)) await self.send_status("200") await self.communicate("map", self.game.get_map())
def testIsAvailable(self): player = Player("Test", None, None, MinBettingPolicy()) player.receive_payment(cfg['MINIMUM_BET']) self.slot.seatPlayer(player) self.slot.addCards(Card('A','H'), Card(6,'D')) cfg.mergeFile('cfg/no_surrender.ini') self.assertFalse(self.surrenderCmd.isAvailable(self.slot), 'testSurrenderCommand:testIsAvailable:Surrender should not be available if disallowed') cfg.reset() self.assertTrue(self.surrenderCmd.isAvailable(self.slot), 'testSurrenderCommand:testIsAvailable:Surrender should be available if allowed') HitCommand(Shoe(2, lambda x:x)).perform(self.slot) self.assertFalse(self.surrenderCmd.isAvailable(self.slot), 'testSurrenderCommand:testIsAvailable:Surrender should not be available after first action')
def pluginControls(self): self.gameDrums = 0 self.gameGuitars = 0 self.gameMics = 0 Player.pluginControls(self.activeGameControls) for i in self.activeGameControls: if self.controls.type[i] == -1: self.gameBots += 1 elif self.controls.type[i] in Player.DRUMTYPES: self.gameDrums += 1 elif self.controls.type[i] in Player.MICTYPES: self.gameMics += 1 elif self.controls.type[i] in Player.GUITARTYPES: self.gameGuitars += 1
def testNumSplits(self): slot = TableSlot() slot.addCards(Card(9,'D'), Card(8,'H')) self.assertEqual(slot.numSplits,0,'testTableSlot:testNumSplits:New hand should have no splits') slot = TableSlot() player = Player('', None, MinBettingPolicy(), None) player.receive_payment(cfg['SPLIT_RATIO']) slot.seatPlayer(player) slot.addCards(Card(7,'D'), Card(7,'H')) slot.splitHand() self.assertEqual(slot.numSplits,1,'testTableSlot:testNumSplits:Split hand should have 1 split') slot.addCards(Card(7,'C')) slot.splitHand() self.assertEqual(slot.numSplits,2,'testTableSlot:testNumSplits:Resplit hand should have 2 splits')
def test_set_location(self): """ test that set_location() sets the location and the moved flag """ hallway = HallwayRoom() player = Player(gender="male", age="10", hair_color="blue") # the player is initiated without a location self.assertIsNone(player.location) player.set_location(hallway) self.assertEqual(player.location, hallway) self.assertTrue(player.moved)
def _play_game(self, ai_1_id, ai_2_id): ai1 = self.entries[ai_1_id] ai2 = self.entries[ai_2_id] player1 = Player(ai=ai1.ai()) player2 = Player(opponent=player1, ai=ai2.ai()) player1.opponent = player2 game = GameRunner(player1, player2) winner = game.play() if winner == player1: ai1.win(ai_2_id) ai2.lose(ai_1_id) else: ai1.lose(ai_2_id) ai2.win(ai_1_id)
class RemotePlayer: def __init__(self, session, request): playerKey = session.get("id") knownGameState = request.get_json().get("knownGameState") self.player = Player(playerKey, None, knownGameState) session["id"] = self.player.key self.player.dbSave() #if self.player.game is not None: # self.player.game.dbSave() def __enter__(self): return self.player def __exit__(self, type, value, traceback): self.player.dbSave()
def get(self): for player in Player.all(): print player.nickname print player.own_games.filter("status !=", "ABANDONED").count() print player.other_games.filter("status !=", "ABANDONED").count() # if it has only abandoned games we delete the player and the games if player.own_games.filter("status !=", "ABANDONED").count() == 0 \ and player.other_games.filter("status !=", "ABANDONED").count() == 0: # if there are won games we delete them for game in player.own_games.filter("status =", "ABANDONED"): game.delete(); # if there are other games we delete them for game in player.other_games.filter("status =", "ABANDONED"): game.delete(); # finally delete player player.delete() print "deleted player", player.nickname print "OK"
def test_move_valid_3(): player = Player(TestWorldEmpty) player.up() player.up() player.up() assert player.position == (1, 0) player = Player(TestWorldEmpty) player.left() player.left() player.left() assert player.position == (0, 1)
def testIsActive(self): player = Player('Tim', None, None, MinBettingPolicy()) player.receive_payment(1000) slot = TableSlot() slot.seatPlayer(player) slot.promptBet() self.assertTrue(slot.isActive,'testTableSlot:testIsActive:Slot with betting player should be active') class NoBettingPolicy(BettingPolicy): def bet(self, **kwargs): return 0 player = Player('Jack',None, None, NoBettingPolicy()) slot = TableSlot() slot.seatPlayer(player) slot.promptBet() self.assertFalse(slot.isActive,'testTableSlot:testIsActive:Slot with non-betting player should not be active') slot = TableSlot() self.assertFalse(slot.isActive,'testTableSlot:testIsActive:Empty slot should not be active')
def test_step_record(): player = Player(TestWorldStarts) player.down() player.right() player.up() assert player.step_record == [Player.DOWN, Player.RIGHT, Player.UP]
def get(self): for player in Player.all(): # avoid NoneType problems if not player.won: player.won = 0 if not player.lost: player.lost = 0 if not player.created: player.created = 0 if not player.abandoned: player.abandoned = 0 # compute score player.score = 10 * player.won - 3 * player.lost player.put() self.response.out.write(template.render(template_path + 'scores.html', { 'Scores' : 'active', 'players' : Player.all().order("-score") }))
def test_collect_starts(): player = Player(TestWorldStarts) assert not player.world.is_solved() player.down() player.right() player.up() assert player.world.is_solved()
def saveCharacter(self): pref = self.choices[0:8] pref.insert(7, self.neck) if len(self.choices[0]) > 0: if self.choices[0].lower() == "default": Dialogs.showMessage(self.engine, _("That is a terrible name. Choose something not 'default'")) elif self.choices[0].lower() not in self.invalidNames or self.choices[0] == self.player: Player.updatePlayer(self.player, pref) self.updatedName = self.choices[0] if self.avatar is not None: shutil.copy(self.engine.resource.fileName(self.avatar),os.path.join(self.engine.data.path,"users","players",self.choices[0]+".png")) if self.oldName: if os.path.exists(self.engine.resource.fileName(os.path.join("users","players",self.oldName+".png"))) and self.oldName != self.choices[0]: if self.avatar is None: os.rename(self.engine.resource.fileName(os.path.join("users","players",self.oldName+".png")), os.path.join(self.engine.data.path,"users","players",self.choices[0]+".png")) else: os.remove(self.engine.resource.fileName(os.path.join("users","players",self.oldName+".png"))) self.engine.view.popLayer(self) self.engine.input.removeKeyListener(self) else: Dialogs.showMessage(self.engine, _("That name already exists!")) else: Dialogs.showMessage(self.engine, _("Please enter a name!"))
def test_move_obstacle(): player = Player(TestWorld) player.down() assert player.position == (0, 1) player = Player(TestWorld) player.right() assert player.position == (0, 0)
def get(self): # see who's online now (the last 30 minutes) now = datetime.now() players = [] for player in Player.all().order("nickname"): dif = now - player.last_online if dif.days * 84000 + dif.seconds > 60: player.online = False else: player.online = True players.append(player) self.response.out.write(template.render(template_path + 'players.html', { 'Players' : 'active', 'players' : players, }))
def test_drop_inventory_item(self): """ test that dropping an item leaves the item in the current location """ player = Player(gender="male", age="10", hair_color="blue", inventory=[Item("elephant")]) self.assertIn("an elephant", player.show_inventory()) player.location = OutsideRoom() self.assertNotIn("an elephant", player.location.show_items()) player.drop("elephant") self.assertNotIn("an elephant", player.show_inventory()) self.assertIn("elephant", player.location.show_items())
def _purge(self): """ Purge all dead players (last_online > 30 secs) The ping can be efficiently made every 30s in C. """ # Get players who haven't pinged in more than 30secs and who are currently marked as online players = Player.all().filter("last_online < ", datetime.now() - timedelta(seconds=30)).filter("online = ", True) for player in players: player.online = False # Not online anymore player.put() # save # Get his former game player_game = Game.all().filter("creator =", player).filter("status = ", 'PLAYING') for game in player_game: game.status = 'ABANDONED' # game OVER game.put() # save # increment the abandoned counter if player.abandoned: player.abandoned = player.abandoned + 1 else: player.abandoned = 1 player.put() # Get his former game player_game = Game.all().filter("creator =", player).filter("status = ", 'WAITING') for game in player_game: game.status = 'ABANDONED' # game OVER game.put() # save # increment the abandoned counter if player.abandoned: player.abandoned = player.abandoned + 1 else: player.abandoned = 1 player.put()
def test_setInt(self): myPlayer = Player() myPlayer.setInt(4) self.assertEqual(myPlayer.myInt,4)
def connect(self): """This command must be sent to the server whenever a player connects for the first time. If the player with the given nickname does not already exist then it is created with the given password. If it already exists and the password is incorrect FAIL is returned. If he's already online, he won't be connected to prevent messing up with the IP and Port. This is the only time we do not check if the player is online to act on the system. Parameters - nickname : is the name of the player and it must be unique. - password: is the password for the given player. - ip : is the local IP address of the player. It is a string like 192.168.10.104. - port : is the port on which the player waits for connections from other players. Return value - OK if everything is ok and the player has been added. - FAIL for any other errors (i.e. bad password, bad IP, bad port, etc.) """ nickname = self.request.get("nickname") password = self.request.get("password") ip_address = self.request.get("ip") listen_port = self.request.get("port") # check if the player already exists player = self._get(Player, "nickname = ", nickname) # if it's a new player if player == None: player = Player(nickname=nickname, password=password) # It's a known player if password != player.password: self.response.out.write("FAIL Incorrect password") return elif player.online == True: # It will be triggered if the player has left without saying 'disconnect' # 90 seconds later, the player will be able to connect himself if someone triggers a purge # THIS IS REALLY ANNOYING DURING DEVELOPEMENT # self.response.out.write("FAIL Already connected elsewhere") # return pass # set new properties, user authenticated player.ip_address = ip_address player.listen_port = listen_port player.last_online = datetime.now() player.online = True # save player.put() # respond with OK self.response.out.write("OK")
def test_move_valid_1(): player = Player(TestWorldEmpty) player.up() assert player.position == (1, 0) player = Player(TestWorldEmpty) player.right() assert player.position == (2, 1) player = Player(TestWorldEmpty) player.down() assert player.position == (1, 2) player = Player(TestWorldEmpty) player.left() assert player.position == (0, 1)
def __init__(self, resource, svg): self.logClassInits = Config.get("game", "log_class_inits") if self.logClassInits == 1: Log.debug("Data class init (Data.py)...") self.logLoadings = Config.get("game", "log_loadings") self.logImageNotFound = Config.get("log", "log_image_not_found") self.resource = resource self.svg = svg self.sfxVolume = Config.get("audio", "SFX_volume") self.crowdVolume = Config.get("audio", "crowd_volume") # Get theme themename = Config.get("coffee", "themename") self.themeLabel = themename self.themeCoOp = False self.players = None self.players = Player.loadPlayers() # myfingershurt: check for existence of theme path themepath = os.path.join(Version.dataPath(), "themes") self.themepath = themepath self.path = Version.dataPath() if not self.checkImgDrawing(os.path.join("themes", themename, "notes", "notes.png")): # myfingershurt: here need to ensure an existing theme is selected themes = [] defaultTheme = None # myfingershurt allthemes = os.listdir(themepath) for name in allthemes: if self.checkImgDrawing(os.path.join("themes", name, "notes", "notes.png")): themes.append(name) if name == "MegaLight V4": # myfingershurt defaultTheme = name # myfingershurt if defaultTheme != "MegaLight V4": # myfingershurt defaultTheme = themes[0] # myfingershurt # not a valid theme if notes.png isn't there! Force default theme: Config.set("coffee", "themename", defaultTheme) # re-init Data with new default themename = defaultTheme self.themeLabel = themename if not os.path.exists(os.path.join(Version.dataPath(), "themes", themename, "vocals")): self.vocalPath = "vocals" else: self.vocalPath = os.path.join("themes", themename, "vocals") self.theme = 2 self.themeCoOp = True self.fontScreenBottom = ( 0.75 ) # from our current viewport's constant 3:4 aspect ratio (which is always stretched to fill the video resolution) self.loadPartImages() # myfingershurt: multi-OS compatibility file access fixes using os.path.join() # load font customization images # Worldrave - Use new defined Star3 and star4. Using star1 and star2 as a fallback. # MFH - no more custom glyphs, these are wasting memory. # MFH - but we do need these star1-4 images anyway. Leaving them loaded here in the Data object. self.loadImgDrawing(self, "star1", os.path.join("themes", themename, "star1.png"), textureSize=(128, 128)) self.loadImgDrawing(self, "star2", os.path.join("themes", themename, "star2.png"), textureSize=(128, 128)) # MFH - let's not rely on errors here if we don't have to... if not self.loadImgDrawing( self, "star3", os.path.join("themes", themename, "star3.png"), textureSize=(128, 128) ): self.star3 = self.star1 if not self.loadImgDrawing( self, "star4", os.path.join("themes", themename, "star4.png"), textureSize=(128, 128) ): self.star4 = self.star2 if self.loadImgDrawing( self, "starPerfect", os.path.join("themes", themename, "starperfect.png"), textureSize=(128, 128) ): self.perfectStars = True self.maskStars = False else: self.starPerfect = self.star2 self.fcStars = False self.starFC = self.star2 self.maskStars = True self.perfectStars = False if self.perfectStars: if self.loadImgDrawing( self, "starFC", os.path.join("themes", themename, "starfc.png"), textureSize=(128, 128) ): self.fcStars = True else: self.starFC = self.starPerfect self.fcStars = False # load misc images self.loadImgDrawing( self, "loadingImage", os.path.join("themes", themename, "loadingbg.png"), textureSize=(256, 256) ) self.loadImgDrawing(self, "optionsBG", os.path.join("themes", themename, "menu", "optionsbg.png")) if self.loadImgDrawing(self, "submenuSelect", os.path.join("themes", themename, "submenuselect.png")): subSelectImgW = self.submenuSelect.width1() self.submenuSelectFound = True self.subSelectWFactor = 640.000 / subSelectImgW self.subSelectImgH = self.submenuSelect.height1() else: self.submenuSelectFound = False self.loadImgDrawing(self, "submenuSelect", os.path.join("themes", themename, "menu", "selected.png")) self.subSelectWFactor = 0 # load all the data in parallel # asciiOnly = not bool(Language.language) or Language.language == "Custom" # reversed = _("__lefttoright__") == "__righttoleft__" and True or False asciiOnly = True reversed = False scale = 1 # evilynux - Load bigger fonts so they're nicer when scaled, scaling readjusted fontSize = [44, 132, 34, 32, 30] w, h = [int(s) for s in Config.get("video", "resolution").split("x")] aspectRatio = float(w) / float(h) self.fontList = [ ["font1", "font", "default.ttf", fontSize[4]], ["font2", "bigFont", "title.ttf", fontSize[1]], ["font3", "pauseFont", "pause.ttf", fontSize[2]], ["font4", "scoreFont", "score.ttf", fontSize[3]], ["font5", "streakFont", "streak.ttf", fontSize[3]], ["font6", "loadingFont", "loading.ttf", fontSize[3]], ["font7", "songFont", "song.ttf", fontSize[4]], ["font8", "songListFont", "songlist.ttf", fontSize[3]], ["font9", "shadowFont", "songlist.ttf", fontSize[3]], ["font10", "streakFont2", "streakphrase.ttf", fontSize[2]], ] for f in self.fontList: if self.fileExists(os.path.join("themes", themename, "fonts", f[2])): fn = resource.fileName(os.path.join("themes", themename, "fonts", f[2])) f[0] = lambda: Font( fn, f[3], scale=scale * 0.5, reversed=reversed, systemFont=not asciiOnly, outline=False, aspectRatio=aspectRatio, ) resource.load(self, f[1], f[0], synch=True) elif self.fileExists(os.path.join("themes", themename, "fonts", "default.ttf")): Log.debug("Theme font not found: " + f[2]) fn = resource.fileName(os.path.join("themes", themename, "fonts", "default.ttf")) f[0] = lambda: Font( fn, f[3], scale=scale * 0.5, reversed=reversed, systemFont=not asciiOnly, outline=False, aspectRatio=aspectRatio, ) resource.load(self, f[1], f[0], synch=True) else: Log.debug("Default theme font not found: %s - using built-in default" % str(f[2])) fn = resource.fileName(os.path.join("fonts", "default.ttf")) f[0] = lambda: Font( fn, f[3], scale=scale * 0.5, reversed=reversed, systemFont=not asciiOnly, outline=False, aspectRatio=aspectRatio, ) resource.load(self, f[1], f[0], synch=True) self.fontDict = { "font": self.font, "bigFont": self.bigFont, "pauseFont": self.pauseFont, "scoreFont": self.scoreFont, "streakFont": self.streakFont, "songFont": self.songFont, "streakFont2": self.streakFont2, "songListFont": self.songListFont, "shadowFont": self.shadowFont, "loadingFont": self.loadingFont, } assert self.fontDict["font"] == self.font # load sounds asynchronously resource.load(self, "screwUpsounds", self.loadScrewUpsounds) resource.load(self, "screwUpsoundsBass", self.loadScrewUpsoundsBass) resource.load(self, "screwUpsoundsDrums", self.loadScrewUpsoundsDrums) resource.load(self, "acceptSounds", self.loadAcceptSounds) resource.load(self, "cancelSounds", self.loadBackSounds) # loadSoundEffect asynchronously self.syncSounds = [ ["bassDrumSound", "bassdrum.ogg"], ["battleUsedSound", "battleused.ogg"], ["CDrumSound", "crash.ogg"], ["clapSound", "clapsound.ogg"], ["coOpFailSound", "coopfail.ogg"], # ["crowdSound","crowdcheers.ogg"], ["failSound", "failsound.ogg"], ["rescueSound", "rescue.ogg"], ["rockSound", "rocksound.ogg"], ["selectSound1", "select1.ogg"], ["selectSound2", "select2.ogg"], ["selectSound3", "select3.ogg"], ["starActivateSound", "staractivate.ogg"], ["starDeActivateSound", "stardeactivate.ogg"], ["starDingSound", "starding.ogg"], ["starLostSound", "starlost.ogg"], ["starReadySound", "starpowerready.ogg"], ["starSound", "starpower.ogg"], ["startSound", "start.ogg"], ["T1DrumSound", "tom01.ogg"], ["T2DrumSound", "tom02.ogg"], ["T3DrumSound", "tom03.ogg"], ] for self.sounds in self.syncSounds: if self.fileExists(os.path.join("themes", themename, "sounds", self.sounds[1])): self.loadSoundEffect(self, self.sounds[0], os.path.join("themes", themename, "sounds", self.sounds[1])) elif self.fileExists(os.path.join("sounds", self.sounds[1])): Log.debug("Theme sound not found: " + self.sounds[1]) self.loadSoundEffect(self, self.sounds[0], os.path.join("sounds", self.sounds[1])) else: Log.warn("File " + self.sounds[1] + " not found using default instead.") self.loadSoundEffect(self, self.sounds[0], os.path.join("sounds", "default.ogg")) # TODO: Simplify crowdSound stuff so it can join the rest of us. # MFH - fallback on sounds/crowdcheers.ogg, and then starpower.ogg. Note if the fallback crowdcheers was used or not. if self.fileExists(os.path.join("themes", themename, "sounds", "crowdcheers.ogg")): self.loadSoundEffect( self, "crowdSound", os.path.join("themes", themename, "sounds", "crowdcheers.ogg"), crowd=True ) self.cheerSoundFound = 2 elif self.fileExists(os.path.join("sounds", "crowdcheers.ogg")): self.loadSoundEffect(self, "crowdSound", os.path.join("sounds", "crowdcheers.ogg"), crowd=True) self.cheerSoundFound = 1 Log.warn(themename + "/sounds/crowdcheers.ogg not found -- using data/sounds/crowdcheers.ogg instead.") else: self.cheerSoundFound = 0 Log.warn("crowdcheers.ogg not found -- no crowd cheering.")
def __init__(self): mines = 3 self.player = Player(game=Minesweeper(mines=mines, width=5, height=5)) self.score = 0 self.undiscovered = mines
from deck import Deck from game import Player, Dealer d = Deck() player = Player(100) dealer = Dealer() while True: bet = player.bet() dcards = d.deal(2) pcards = d.deal(2) pc_value = player.play(pcards, dcards[1], d) dc_value = dealer.play(dcards, d) if pc_value > 0 and dc_value > 0: if pc_value < dc_value: print("dealer wins") elif pc_value > dc_value: print("player wins") if pc_value == 21: player.win(bet * 1.5) else: player.win(bet * 2) elif pc_value == -1 and dc_value > 0: print("dealer wins") elif dc_value == -1 and pc_value > 0: print("player wins") if pc_value == 21: player.win(bet * 2.5) else: