class TestCheckIsHit(unittest.TestCase): def setUp(self): self.testPlayer = Player() self.ship1 = Ship('ship1', 3) self.ship2 = Ship('ship2', 4) self.ship3 = Ship('ship3', 2) self.testPlayer._setShips([self.ship1, self.ship2, self.ship3, ]) self.ship1.placeShip((5, 5), DOWN) self.ship2.placeShip((0, 6), RIGHT) self.ship3.placeShip((6, 5), RIGHT) def test_checkIsMiss(self): shot = (1, 1) hit, hitShip = self.testPlayer._checkIsHit(shot) self.assertFalse(hit) self.assertEqual(hitShip, None) def test_checkIsHit(self): shot = (5, 3) hit, hitShip = self.testPlayer._checkIsHit(shot) self.assertTrue(hit) self.assertEqual(hitShip, self.ship1)
def test_valid_command(self): '''This test ensures that a valid command is correctly checked''' deck = Deck(1) player_1 = Player(0) player_2 = Player(1) players = [player_1] layouts = Layouts(1) deck.shuffle() deck.deal(players) seven_suits = [c.suit for c in player_1.hand if c.rank == 7] test_suit = seven_suits[0] card_cmd_str = "7" + test_suit layout_dict = { "C": "L0", "D": "L1", "H": "L2", "S": "L3" } layout_cmd_str = layout_dict[test_suit] cmd_str = card_cmd_str + layout_cmd_str cmd = Command(cmd_str, layouts) self.assertTrue(cmd.is_valid(player_1.hand))
class TestCheckAllShipsSunk(unittest.TestCase): def setUp(self): self.testPlayer = Player() self.ship1 = Ship('ship1', 3) self.ship2 = Ship('ship2', 4) self.ship3 = Ship('ship3', 2) self.testPlayer._setShips([self.ship1, self.ship2, self.ship3, ]) self.ship1.placeShip((5, 5), DOWN) self.ship2.placeShip((0, 6), RIGHT) self.ship3.placeShip((6, 5), RIGHT) def test_noShipsSunk(self): self.assertFalse(self.testPlayer._checkAllShipsSunk()) def test_oneShipSunk(self): self.ship1.hits = self.ship1.locations self.assertFalse(self.testPlayer._checkAllShipsSunk()) def test_allShipsSunk(self): self.ship1.hits = self.ship1.locations self.ship2.hits = self.ship2.locations self.ship3.hits = self.ship3.locations self.assertTrue(self.testPlayer._checkAllShipsSunk())
def main_experiments(player: Player = None): logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) colors = list(Color) colors.remove(Color.EMPTY) possible_codes = [p for p in itertools.product(colors, repeat=4)] if player is None: player = SmartPlayer(strategy=SmartStrategy.FIRST) rounds = [] for possible_code in possible_codes: start = datetime.datetime.now() # print(possible_code) code = Code(*possible_code) player.reset() round = player.play_game(50, code) rounds.append(round + 1) end = datetime.datetime.now() print(f"Code: {possible_code}, time: {end - start}, rounds: {round + 1}") print(f"Number of games: {len(rounds)}") print(f"Mean: {np.mean(rounds)}") print(f"Max: {max(rounds)}") print(f"Min: {min(rounds)}") return np.mean(rounds), max(rounds)
def play(self, otherChoice, mistakeRate): if self.__isOnGrudge: if self.__grudgeCount == 0: self.__grudgeCount = -2 self.__isOnGrudge = False self.choice.append('C') else: self.choice.append('B') self.__grudgeCount -= 1 else: if otherChoice == 'B': if self.__grudgeCount == 0: # Betrayal during a normal cooperation self.startGrudge() self.choice.append('B') elif self.__grudgeCount < 0: # Betrayal during the 2 turns of forgiveness self.__grudgeCount += 1 if self.__grudgeCount == 0: # If it was the last turn of forgiveness, prepare the next punition self.startGrudge() self.choice.append('C') else: # both cooperating if self.__grudgeCount < 0: # update the count of forgiveness turns self.__grudgeCount += 1 self.choice.append('C') Player.apply_mistake_rate(self, mistakeRate)
def game_starts(context): user_input = io.StringIO('x') sys.stdin = user_input marker1 = context.user_interface.choose_marker() sys.stdin = sys.__stdin__ context.player1 = Player(marker1) marker2 = context.player1.switch_marker(marker1) context.player2 = Player(marker2)
def __playRound(self, player: Player): cards, card3 = deal() bet = 1 + player.play(cards[0], cards[1]) if (cards[0] < card3 and card3 < cards[1]): player.changeScore(bet) else: player.changeScore(-bet)
def get_players(): NUM_HIDDEN_LAYERS = 10 NUM_ACTIONS = 16 f = CardFeaturizer1(NUM_HIDDEN_LAYERS, 20) Q0 = QNetwork(NUM_ACTIONS, NUM_HIDDEN_LAYERS, f, None, 0, None) Q1 = QNetwork(NUM_ACTIONS, NUM_HIDDEN_LAYERS, f, None, 1, None) players = [Player(0, strategy_RL(Q0, True), 100, verbose=True, name='SB'), Player(1, strategy_RL(Q1, True), 100, verbose=True, name='DH')] return players
def __init__(self, **kwargs): """Initializes screen with default values""" super(Game, self).__init__(**kwargs) self.mode = ObjectProperty(None) self.difficulty = ObjectProperty(None) self._player_one = Player(self, PlayerToken.X) self._player_two = Player(self, PlayerToken.O) self._current_player = self._player_one self._allow_move = True self.grid_size = 3
def play(self, otherChoice, mistakeRate): if len(self.choice) == 0 : self.choice.append('C') else : if otherChoice == 'B': self.__grudge = True if self.__grudge: self.choice.append('B') else : self.choice.append('C') Player.apply_mistake_rate(self, mistakeRate)
def _generate_player_instances(self, strategy_p1, strategy_p2, Q_networks, Pi_networks, learn_start, verbose): players = [] # Strategies that do not require Q for p_id, strategy in enumerate([strategy_p1, strategy_p2]): if strategy not in allowed_strategies: raise ValueError("Not a valid strategy") elif strategy in baseline_strategies: players.append( Player(p_id, strategy_function_map[strategy], INITIAL_MONEY, p_names[p_id], verbose=verbose)) elif strategy in qnetwork_strategies: players.append( Player(p_id, strategy_function_map[strategy](Q_networks[p_id], True), INITIAL_MONEY, p_names[p_id], verbose=verbose)) elif strategy in NFSP_strategies: Q = Q_networks[p_id] pi = Pi_networks[p_id] if self.should_load_models[p_id]: Q = load_model(self.q_model_paths[p_id], Q, cuda=self.cuda) pi = load_model(self.pi_model_paths[p_id], pi, cuda=self.cuda) strategy = StrategyNFSP(Q=Q, pi=pi, eta=self.etas[p_id], eps=self.eps, cuda=self.cuda) nfp = NeuralFictitiousPlayer( pid=p_id, strategy=strategy, stack=INITIAL_MONEY, name=p_names[p_id], gamma=self.gamma, learning_freq=self.learning_freq, target_Q_update_freq=self.target_Q_update_freq, memory_rl_config=self.memory_rl_config, memory_sl_config=self.memory_sl_config, learn_start=self.learn_start, verbose=self.verbose, tensorboard=self.tensorboard, cuda=self.cuda) players.append(nfp) return players
def play(self, otherChoice, mistakeRate): if otherChoice == 'B': if self.__wasBetrayed: self.choice.append('B') else: self.__wasBetrayed = True self.choice.append('C') else: if self.__wasBetrayed: self.__wasBetrayed = False self.choice.append('C') Player.apply_mistake_rate(self, mistakeRate)
class Game: def __init__(self, word): self.p1 = Player("David", "c") self.p2 = Player("Rogers", "v") self.game_word = word self.subs = self.divide_strings_into_subs(self.game_word) self.seperate_subs(self.subs) def start(self): self.p1.calculate_score(self.consonants) self.p2.calculate_score(self.vowels) print(self.p1.name, self.p1.score) print(self.p2.name, self.p2.score) self.result() def divide_strings_into_subs(self, word): res = [ word[i:j].upper() for i in range(len(word)) for j in range(i + 1, len(word) + 1) ] return res def seperate_subs(self, ty): vows = ["A", "E", "I", "O", "Ö", "İ", "U", "Ü"] cons = [ "B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z" ] self.vowels = [] self.consonants = [] for i in ty: if i[0] in vows: self.vowels.append(i) elif i[0] in cons: self.consonants.append(i) else: continue def result(self): if self.p1.score > self.p2.score: print("The Winner is " + self.p1.name + " with " + str(self.p1.score - self.p2.score) + " difference") elif self.p2.score > self.p1.score: print("The Winner is " + self.p2.name + " with " + str(self.p2.score - self.p1.score) + " difference") else: print("Draw")
def test_doubledeck(self): ''' Ensures that both players have 52 cards in their hand after dealing 2 decks. ''' deck = Deck(2) player_1 = Player(0) player_2 = Player(1) players = [player_1, player_2] deck.shuffle() deck.deal(players) self.assertEqual(len(player_1.hand), 52)
def __init__( self, player1_name='Player1', player2_name='Player2', level=level2, ): self.level = level self.player1 = Player( player_name=player1_name, starting_room=level[0] ) self.player2 = Player( player_name=player2_name, starting_room=level[1] ) self.n_round = 0
def __init__(self, surface, lane_map, speed=0, y=0, lane=4, is_subject=False, subject=None, score=None, agent=None): self.surface = surface self.lane_map = lane_map self.sprite = None if not VISUALENABLED else red_car if is_subject else white_car self.speed = min(max(speed, 0), MAX_SPEED) self.y = y self.lane = lane self.x = (self.lane - 1) * 50 + 15 + 8 + ROAD_VIEW_OFFSET self.is_subject = is_subject self.subject = subject self.max_speed = -1 self.removed = False self.emergency_brake = None self.switching_lane = -1 self.available_directions = ['M'] self.available_moves = ['D'] self.score = score self.player = np.random.choice([ Player(self), AggresivePlayer(self), StickyPlayer(self) ]) if not self.is_subject else DeepTrafficPlayer(self, agent=agent) self.hard_brake_count = 0 self.alternate_line_switching = 0
def test_player(self): ''' Ensures that both players have 26 cards in their hand after dealing 1 deck. ''' deck = Deck(1) player_1 = Player(0) player_2 = Player(1) players = [player_1, player_2] deck.shuffle() deck.deal(players) self.assertEqual(len(player_1.hand), 26)
def play(self, otherChoice, mistakeRate): if len(self.choice) == 0: self.choice.append('C') elif len(self.choice) < 4: if 'B' == otherChoice: self.__actLikeCopycat = True if len(self.choice) == 1: self.choice.append('B') else: self.choice.append('C') else: if self.__actLikeCopycat: Copycat.play(self, otherChoice, mistakeRate) else: self.choice.append('B') Player.apply_mistake_rate(self, mistakeRate)
def setUp(self): self.testPlayer = Player() self.ship1 = Ship('ship1', 3) self.ship2 = Ship('ship2', 4) self.ship3 = Ship('ship3', 2) self.testPlayer._setShips([self.ship1, self.ship2, self.ship3, ])
class GameTest(unittest.TestCase): def setUp(self): self.test_db = TestDB() self.player = Player('X', self.test_db) self.board = Board() def test_define_second_marker_automatically_when_the_first_one_is_o(self): symbol = self.player.switch_marker('O') self.assertEqual(symbol, 'X') def test_define_second_marker_automatically_when_the_first_one_is_x(self): symbol = self.player.switch_marker('X') self.assertEqual(symbol, 'O') def test_move_when_user_entered_valid_move_option(self): self.player.move(self.board, 4, 'O') board_spot_value = self.board.get_value(3) self.assertEqual(board_spot_value, 'O')
def __list_players__(): if not __players_list__: data = __request_players__() for p in data['plrs']: if p['pid'] and p['nameF'] and p['nameL']: __players_list__.append( Player(int(p['pid']), p['nameF'], p['nameL'])) return __players_list__
def __init__(self, name, numLives, history): Player.__init__(self, name, numLives, history) self.alpha = Learning.ALPHA self.gamma = Learning.GAMMA self.epsilon = Learning.EPSILON if os.path.exists(Learning.Q_DIREC + name + "_" + Learning.CALLS_QVALS): with open(Learning.Q_DIREC + name + "_" + Learning.CALLS_QVALS, "rb") as file: self.qCalls = pickle.load(file) else: self.qCalls = defaultdict(float) self.qCalls[Learning.DECAY] = 1.0 if os.path.exists(Learning.Q_DIREC + name + "_" + Learning.PLAY_QVALS): with open(Learning.Q_DIREC + name + "_" + Learning.PLAY_QVALS, "rb") as file: self.qPlays = pickle.load(file) else: self.qPlays = defaultdict(float) self.qPlays[Learning.DECAY] = 1.0
def setUp(self): self.testPlayer = Player() self.ship1 = Ship('ship1', 3) self.ship2 = Ship('ship2', 4) self.ship3 = Ship('ship3', 2) self.testPlayer._setShips([self.ship1, self.ship2, self.ship3, ]) self.ship1.placeShip((5, 5), DOWN) self.ship2.placeShip((0, 6), RIGHT) self.ship3.placeShip((6, 5), RIGHT)
def generate(self): self.players = [ Player(self.CP, 0, self, "DumbStrategy", self.player_coords[0]), Player(self.CP, 1, self, "DumbStrategy", self.player_coords[1]) ] self.planets = [ Planet(coord, self.player_coords.index(coord) + 1) for coord in self.player_coords ] for s in range(2): self.players[s].army_set_up(self.player_coords[s]) possible_coords = [[x, y] for x in range(5) for y in range(5) if x != 2 or (y != 2 and y != 4)] for n in range(7): choice = possible_coords[random.randrange(len(possible_coords))] self.planets.append(Planet(choice, False, 0)) self.board.setup(self.planets, self.players)
def proxy_player(self, p: Player): self.other = p orig_choose_action = p.choose_action orig_do_choose_from_piles = p.do_choose_from_piles def wrapped_choose_action(other_self, b: Game, p_other: Player, actions): res = orig_choose_action(b, p_other, actions) #self.send_msg('choose_action_other', str(res)) self.other_actions.append(('choose_action', str(res))) return res def wrapped_do_choose_from_piles(other_self, action, piles: [Pile], min_n, max_n): res = orig_do_choose_from_piles(action, piles, min_n, max_n) #self.send_msg('choose_piles_other', str(res)) self.other_actions.append(('choose_piles', str(res))) return res p.choose_action = types.MethodType(wrapped_choose_action, p) p.do_choose_from_piles = types.MethodType(wrapped_do_choose_from_piles, p)
def main_single(player: Player, code: Code = None): logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) print("ready") if code is None: code = Code(Color.ORANGE, Color.PURPLE, Color.ORANGE, Color.YELLOW) if player is None: player = SmartPlayer() round = player.play_game(50, code) print(round + 1)
def create_players(self, players): """ Add all the new players into the game's players group """ for player in players: print(player['width']) if player['player_type'] == 0: new_player = Player(self.screen, self.controller, self.settings, player['player_type'], player['imagepath']) self.players.append(new_player) elif player['player_type'] == 1: new_player = SidePlayer(self.screen, self.controller, self.settings, player['rightside'], player['imagepath'], player['player_type']) self.players.append(new_player)
def turn(player1: Player, player2: Player, i: int, mistakeRate: int): """Play one turn between two player :param player1: Player 1 :param player2: Player 2 :param i: The number of the turn :return: None """ print("Turn {} : ".format(i+1), end="") if i == 0: player1.play('C', mistakeRate) player2.play('C', mistakeRate) else : player1.play(player2.choice[-1], mistakeRate) player2.play(player1.choice[-2], mistakeRate) print("Player 1 [{}] || Player 2 [{}]".format(player1.choice[-1],player2.choice[-1])) gain(player1, player2)
def new_player_vs_advanced( self ): # initializes the game variables and window to match the style of game. print("Selected game mode: Player vs Advanced AI") self.player1 = Player() self.player2 = Advanced() self.turn = "position" self.window.close() self.window = sg.Window("Battleship", self.create_ship_placement_layout(), icon="assets/battleship.ico", margins=(30, 30)) self.player2.create_board() self.player1turns = 0 self.player2turns = 0 self.whowon = None
def do_turn(self, p1: Player, p2: Player): if p1.need_draw: p1.draw(5 if self.turn > 0 else 3) p1.need_draw = False if p1.discard: p1.choose_discard(p1.discard) for c in p1.outposts: self.play(p1, p2, c) for c in p1.bases: self.play(p1, p2, c) while self.do_one_user_action(p1, p2): if p2.health <= 0: raise GameOver(p1) p1.end_turn()
def __init__(self): self.lyrics = None self.lyricsTimer = None self.player = Player() self.player.registerOnPlayerConnected(self.onPlayerConnected) self.player.registerOnSongChange(self.onSongChanged) self.player.registerOnPlay(self.onPlay) self.player.registerOnStop(self.onStop) self.player.registerOnElapsedChanged(self.onSeek) self.lyricsEngine = LyricsEngine(self.onLyricsFound, self.onEngineFinish) self.lyricsEngine.setLyricsSources(['alsong', 'minilyrics', 'lrcdb', 'lyricsscreenlet']) self.label = gtk.Label("Lyrics Applet") self.gconf_client = gconf.client_get_default() self.gconf_client.add_dir("/apps/lyrics_applet", gconf.CLIENT_PRELOAD_NONE) self.gconf_client.notify_add('/apps/lyrics_applet/color', self.color_changed) self.gconf_client.notify_add('/apps/lyrics_applet/font', self.font_changed) self.color_changed(None) self.font_changed(None)
def play(self, p1: Player, p2: Player, card: Card): remaining_actions = [(card, action) for action in card.actions] + p1.remaining_actions is_allied = card.faction != Faction.UNALIGNED and any( card.is_ally(c) for c in chain(p1.in_play, p1.bases, p1.outposts)) new_remaining = [] for c, action in remaining_actions: # perform actions if isinstance(action, AllyAction): if is_allied and card.is_ally(c): action = action.action else: new_remaining.append((c, action)) continue if isinstance(action, OptionalAction): new_remaining.append((c, action)) continue action.exec(c, self, p1, p2) p1.remaining_actions = new_remaining
def do_action(self, p1: Player, p2: Player, a: UserAction): if self.verbose: log.info('turn %s player %s: %s', self.turn, p1.name, a) if isinstance(a, UserActionAttackFace): if p2.outposts: raise Exception('user has outposts!' + str(p2.outposts)) p2.health -= p1.damage p1.damage = 0 elif isinstance(a, UserActionPlayCard): self.action_play_card(p1, p2, a.card) elif isinstance(a, UserActionBuyCard): self.action_buy(p1, a.card) elif isinstance(a, UserActionCardAction): # TODO: this is always optional... should we remove in choose_action? try: p1.remaining_actions.remove((a.card, a.action)) except ValueError: p1.remaining_actions.remove((a.card, OptionalAction(a.action))) try: a.action.exec(a.card, self, p1, p2) except: p = 1 elif isinstance(a, UserActionAttackOutpost): p2.outposts.remove(a.outpost) p2.discard_pile.append(a.outpost) p1.damage -= a.outpost.defence elif isinstance(a, UserActionAttackBase): p2.bases.remove(a.base) p2.discard_pile.append(a.base) p1.damage -= a.base.defence elif a == USER_ACTION_DONE: return False else: raise Exception(f'unhandled action: {a}') return True
def __init__(self, name): Player.__init__(self, name)
def __init__(self): Player.__init__(self) self.name = "Copykitten" self.__wasBetrayed = False
def reset(self): Player.reset(self) self.__wasBetrayed = False
class Lyrics(object): color = gtk.gdk.Color() font = "Sans 10" applet = None label = None lyrics_directory = "/home/dencer/Lyrics" def __init__(self): self.lyrics = None self.lyricsTimer = None self.player = Player() self.player.registerOnPlayerConnected(self.onPlayerConnected) self.player.registerOnSongChange(self.onSongChanged) self.player.registerOnPlay(self.onPlay) self.player.registerOnStop(self.onStop) self.player.registerOnElapsedChanged(self.onSeek) self.lyricsEngine = LyricsEngine(self.onLyricsFound, self.onEngineFinish) self.lyricsEngine.setLyricsSources(['alsong', 'minilyrics', 'lrcdb', 'lyricsscreenlet']) self.label = gtk.Label("Lyrics Applet") self.gconf_client = gconf.client_get_default() self.gconf_client.add_dir("/apps/lyrics_applet", gconf.CLIENT_PRELOAD_NONE) self.gconf_client.notify_add('/apps/lyrics_applet/color', self.color_changed) self.gconf_client.notify_add('/apps/lyrics_applet/font', self.font_changed) self.color_changed(None) self.font_changed(None) def color_changed(self, client, *args): color = self.gconf_client.get_string("/apps/lyrics_applet/color") if color: self.color = gtk.gdk.Color(color) self.label.modify_fg(gtk.STATE_NORMAL, self.color) def font_changed(self, client, *args): font = self.gconf_client.get_string("/apps/lyrics_applet/font") if font: self.font = font font_desc = pango.FontDescription(font) self.label.modify_font(font_desc) def onPlayerConnected(self): print "onPlayerConnected" def onStop(self): if self.lyricsTimer: self.lyricsTimer.pause() def onPlay(self): if self.lyricsTimer: self.lyricsTimer.resume() def onSeek(self, elapsed): print "## seek to:", elapsed if self.lyrics: self.lyricsTimer.pause() self.lyricsTimer = LyricsTimer(self.lyrics, self.update) self.lyricsTimer.start(elapsed) self.label.set_text(self.lyrics[self.lyricsTimer.actualLine].text[0].strip()) def onSongChanged(self, songFile): try: self.lyrics = None if self.lyricsTimer: self.lyricsTimer.pause() self.lyricsTimer = None print "onSongChanged" metadata = getSongMetadata(self.player) metadata['file'] = songFile self.label.set_text("") print metadata lyrics = self.getLyricsFromDisk(metadata) if lyrics is None: self.lyricsEngine.search(metadata) print "searching started" else: self.onLyricsFound(lyrics) except: traceback.print_exc() def onLyricsFound(self, lyrics): if not self.lyrics and lyrics: print "onLyricsFound" try: parsed = lyricsparser.parseLyrics(lyrics) if isinstance(parsed[0], LyricEntity): self.lyrics = parsed self.lyricsTimer = LyricsTimer(self.lyrics ,self.update) elapsed = self.player.getElapsed() #print "elapsed:", elapsed self.lyricsTimer.start(elapsed) self.label.set_text(self.lyrics[self.lyricsTimer.actualLine].text[0].strip()) self.lyricsEngine.stop() except: traceback.print_exc() def update(self, lyricsLine): lyricLine = self.lyrics[lyricsLine].text[0].strip() if lyricLine: self.label.set_text(self.lyrics[lyricsLine].text[0].strip()) def onEngineFinish(self): print "onEngineFinish" def getLyricsFromDisk(self, songInfo): logger.debug("searching lyrics on disk") # check for .lrc file in song file directory lrc_file = None if songInfo.has_key('file'): lrc_file = songInfo['file'].rstrip("mp3")+"lrc" #TODO: not only mp3 expecting if lrc_file == None or not os.path.exists(lrc_file): lrc_path = lyricsFile(songInfo) lrc_file = os.path.join(self.lyrics_directory, lrc_path['folder'], lrc_path['file']) logger.debug("lyrics should be here: %s" % lrc_file) print lrc_file if lrc_file != None and os.path.exists(lrc_file): f = open(lrc_file, 'r') print "lyrics from file: %s" % lrc_file lrc = f.read() f.close() return lrc print "Nothing on disk" return None def show_about(self, *args): print args pass def show_preferences(self, *args): dialog = OptionsDialog(self) response = dialog.run() if response == gtk.RESPONSE_OK: dialog.save_preferences() dialog.destroy()
def __init__(self, colour): Player.__init__(self, colour)
class Game(object): def __init__( self, player1_name='Player1', player2_name='Player2', level=level2, ): self.level = level self.player1 = Player( player_name=player1_name, starting_room=level[0] ) self.player2 = Player( player_name=player2_name, starting_room=level[1] ) self.n_round = 0 def new_turn(self): print('\nNew turn for players. ROUND: <<< {} >>>'.format(self.n_round)) self.player1.input_orders() self.player1.execute_orders() self.update_states() print('\n') self.player2.input_orders() self.player2.execute_orders() self.update_states() self.n_round += 1 print('End of turn for players') def update_states(self): self.player1.update_states() self.player2.update_states()
class TestShipsPlacedLegally(unittest.TestCase): def setUp(self): self.testPlayer = Player() self.ship1 = Ship('ship1', 3) self.ship2 = Ship('ship2', 4) self.ship3 = Ship('ship3', 2) self.testPlayer._setShips([self.ship1, self.ship2, self.ship3, ]) def test_shipPlacedOffBoard(self): self.ship1.placeShip((0, 0), DOWN) result = self.testPlayer.isShipPlacedLegally(self.ship1) self.assertFalse(result) self.assertFalse(self.testPlayer._allShipsPlacedLegally()) def test_shipsOverlapping(self): self.ship1.placeShip((5, 5), DOWN) self.ship2.placeShip((0, 6), RIGHT) self.ship3.placeShip((5, 5), RIGHT) result = self.testPlayer.isShipPlacedLegally(self.ship1) self.assertFalse(result) result = self.testPlayer.isShipPlacedLegally(self.ship2) self.assertTrue(result) result = self.testPlayer.isShipPlacedLegally(self.ship3) self.assertFalse(result) self.assertFalse(self.testPlayer._allShipsPlacedLegally()) def test_shipsAreValid(self): self.ship1.placeShip((5, 5), DOWN) self.ship2.placeShip((0, 6), RIGHT) self.ship3.placeShip((6, 5), RIGHT) result = self.testPlayer.isShipPlacedLegally(self.ship1) self.assertTrue(result) result = self.testPlayer.isShipPlacedLegally(self.ship2) self.assertTrue(result) result = self.testPlayer.isShipPlacedLegally(self.ship3) self.assertTrue(result) self.assertTrue(self.testPlayer._allShipsPlacedLegally())