def test_shoot_sunked_32(self): board = Board() result = [] board.set_boat(5, 7, 3, "horizontal") for i in range(7, 10): result.append(board.shoot(5, i)) self.assertEqual(result[len(result) - 1], "sunked")
def run(self): pytorch_utils.add_model_indicators(self.policy) for epoch, (game, arrange) in enumerate(self.games): board = Board(arrange) # TODO change this state = board.get_current_board() for iteration in count(): logger.log('epoch : {}, iteration : {}'.format(epoch, iteration), Color.cyan) action = self.get_action(state) next_state, reward, done = self.step(board, action.item()) if done: next_state = None self.memory.push(state, action, next_state, reward) state = next_state self.train() if done: tracker.add(iterations=iteration) tracker.save() break if epoch % self.target_update == 0: self.target.load_state_dict(self.policy.state_dict()) if self.is_log_parameters: pytorch_utils.store_model_indicators(self.policy)
def test_shoot_sunked_31(self): board = Board() result = [] board.set_boat(1, 2, 3, "vertical") for i in range(1, 4): result.append(board.shoot(i, 2)) self.assertEqual(result[len(result) - 1], "sunked")
def test_place_ship_ew(): board = Board() ship = {'code': 'C', 'size': 2} board.place_ship(0, 0, ship, 'EW') assert board[0][0] == 'C' assert board[0][1] == 'C'
def example_two_players_users(): # Creating the ships MANUALLY for the 2 players Alice and Bob list_ships_player_alice = [ Ship(coord_start=(3, 1), coord_end=(3, 5)), # length = 5 Ship(coord_start=(9, 7), coord_end=(9, 10)), # length = 4 Ship(coord_start=(1, 9), coord_end=(3, 9)), # length = 3 Ship(coord_start=(5, 2), coord_end=(6, 2)), # length = 2 Ship(coord_start=(8, 3), coord_end=(8, 3)), # length = 1 ] list_ships_player_bob = [ Ship(coord_start=(5, 8), coord_end=(9, 8)), # length = 5 Ship(coord_start=(5, 4), coord_end=(8, 4)), # length = 4 Ship(coord_start=(3, 1), coord_end=(5, 1)), # length = 3 Ship.get_ship_from_str_coordinates( coord_str_start='F10', coord_str_end='G10'), # Another way of creating a Ship Ship.get_ship_from_str_coordinates( coord_str_start='A4', coord_str_end='A4'), # Another way of creating a Ship ] # Creating their boards board_player_alice = Board(list_ships_player_alice) board_player_bob = Board(list_ships_player_bob) # Creating the players player_alice = PlayerUser(board_player_alice, name_player="Alice") player_bob = PlayerUser(board_player_bob, name_player="Bob") # Creating and launching the game game = Game(player_1=player_alice, player_2=player_bob) game.play()
def setUp(self): self.game = GameBattleship() input_user = [ '1, 1, 1, vertical', '1, 2, 2, vertical', '1, 3, 3, vertical', '1, 4, 3, vertical', '1, 5, 4, vertical', '1, 6, 5, vertical', ] board = Board() board_table = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 31, 32, 4, 5, 0, 0, 0], [0, 0, 2, 31, 32, 4, 5, 0, 0, 0], [0, 0, 0, 31, 32, 4, 5, 0, 0, 0], [0, 0, 0, 0, 0, 0, 4, 5, 0, 0], [0, 0, 0, 0, 0, 0, 0, 5, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] board.board = board_table for single_input in input_user: self.game.play(single_input) self.game.player_cpu.board_own = board
def test_place_ship_exc(): board = Board() ship = {'code': 'C', 'size': 2} with pytest.raises(IndexError) as excinfo: board.place_ship(0, 9, ship, 'NS') assert 'index out of range' in str(excinfo.value)
def test_attack_miss(): board = Board() result = board.attack(0, 1) assert result == 'Miss. 0:1' assert board[0][1] == 'M' assert board.hit_ships == []
def test_shoot_sunked_5(self): board = Board() result = [] board.set_boat(5, 5, 5, "vertical") for i in range(5, 10): result.append(board.shoot(i, 5)) self.assertEqual(result[len(result) - 1], "sunked")
class PlayerCPU(object): def __init__(self): self.board_own = Board() self.board_opponent = Board() def get_boards(self): return [self.board_own, self.board_opponent] # Llena el board con todos los barcos de forma random def fill_own_board(self): if self.board_own.state == 'empty': boats = [1, 2, 3, 3, 4, 5] i = 0 while not self.board_own.is_ready_to_war(): row = randint(0, 9) column = randint(0, 9) orientation_own = choice(orientation) is_possible = self.board_own.set_boat(row, column, boats[i], orientation_own) if is_possible: i += 1 return True else: return False
def test__hit(): check = Board(5) check._hit(check.fleet['P'],(0,0)) check._hit(check.fleet['P'],(0,1)) print(check.brd)
def test_init(): check = Board(5) check.board[(1,1)] = 'X' print(check.board) print(check.fleet)
def __init__(self): self.board_own = Board() self.board_opponent = Board() self.possible_coordenates = [] self.messages = [] for i in range(9): for j in range(9): self.possible_coordenates.append([i, j])
def test_attack_hit(): board = Board() board[0][0] = 'C' board[0][1] = 'C' result = board.attack(0, 0) assert result == 'Hit! 0:0' assert board[0][0] == 'H' assert board.hit_ships == ['C']
def __init__(self, human_player_name: str = None): self.human_board = Board() self.cpu_board = Board() self.human_player = HumanPlayer(self.human_board, name=human_player_name) self.cpu_player = CPUPlayer(self.cpu_board, "Jack Sparrow") self.ui_manager = UiManager(self.cpu_player, self.human_player)
def test_no_winner(): dims = (5, 5) s1 = {Ship(1, 1, 3, "v")} p1 = Player(Board(dims, s1)) s2 = {Ship(1, 1, 3, "v")} p2 = Player(Board(dims, s2)) game = Game(p1, p2, dims) result = game.get_winner() assert result is None
def test_game_text(): dims = (3, 3) s1 = {Ship(0, 0, 3, "v")} p1 = Player(Board(dims, s1)) s2 = {Ship(0, 0, 3, "v")} p2 = Player(Board(dims, s2)) game = Game(p1, p2, dims) p1_lines = game.p1_lines() p2_lines = game.p2_lines() assert list(p1_lines) == [["s", ".", "."], ["s", ".", "."], ["s", ".", "."]] assert list(p2_lines) == [["s", ".", "."], ["s", ".", "."], ["s", ".", "."]]
def test_get_sequence(): board = Board() board[0][0] = 'C' board[1][0] = 'C' ns_seq = board.get_sequence(0, 0, 3, 'NS') assert ns_seq == { 'values': ['C', 'C', 'O'], 'indices': [(0, 0), (1, 0), (2, 0)] } ew_seq = board.get_sequence(0, 0, 2, 'EW') assert ew_seq == {'values': ['C', 'O'], 'indices': [(0, 0), (0, 1)]}
def test_p2_winner(): dims = (5, 5) s1 = {Ship(1, 1, 3, "v")} p1 = Player(Board(dims, s1)) s2 = {Ship(1, 1, 3, "v")} p2 = Player(Board(dims, s2)) game = Game(p1, p2, dims) game.p2_move(1, 1) game.p2_move(1, 2) game.p2_move(1, 3) result = game.get_winner() assert result == 2
def test_inicial(self): board = Board() result = board.get_board() board_expected = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertEqual(result, board_expected)
def test_board_mark_shoot_hit(self): board = Board() board.mark_shoot(0, 0, True) board_expected = [ ['x', 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertEqual(board.board, board_expected)
def test_board_mark_shoot_water(self): board = Board() board.mark_shoot(0, 0, False) board_expected = [ ['-', 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertEqual(board.board, board_expected)
def _pick_random_move(self, board: Board) -> Tuple[int, int]: while True: row = random.randint(0, BOARD_NUM_ROWS) col = random.randint(0, BOARD_NUM_COLS) is_valid, _ = board.is_valid_move(row, col) if is_valid: break return (row, col)
def test_insert_three_horizontal_ship(self): board = Board() board.set_boat(0, 7, 3, "horizontal") board_expected = [ [0, 0, 0, 0, 0, 0, 0, 31, 31, 31], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] result = board.get_board() self.assertEqual(result, board_expected)
def test_doblehit(self): board_cpu = Board() board = [ [31, 9, 31, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] board_cpu.board = board result = board_cpu.shoot(0, 1) self.assertEqual(result, 'already shoot')
def test_validate_exceeds_x_grid(): dimensions = (1, 1) with pytest.raises(RuntimeError) as e_info: ships = {Ship(1, 1, 2, "h")} _ = Board(dimensions, ships) assert "exceeds size" == str(e_info.value)
def test_insert_five_vertifcal_ship(self): board = Board() board.set_boat(3, 4, 5, "vertical") board_expected = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0, 0, 0], [0, 0, 0, 0, 5, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] result = board.get_board() self.assertEqual(result, board_expected)
def test_opponent_move_guessed(): dims = (5, 5) s1 = {Ship(1, 1, 3, "v")} p1 = Player(Board(dims, s1)) with pytest.raises(RuntimeError, match="already guessed"): p1.opponent_move(1, 1) p1.opponent_move(1, 1)
def test_validate_negative_y_grid(): dimensions = (1, 1) with pytest.raises(RuntimeError) as e_info: ships = {Ship(0, -5, 2, "h")} _ = Board(dimensions, ships) assert "cannot be a negative coordinate" == str(e_info.value)
def test_insert(self): board = Board() board.set_boat(2, 3, 1, "horizontal") board_expected = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] result = board.get_board() self.assertEqual(result, board_expected)
def test_overlapping_ships(): dimensions = (10, 10) with pytest.raises(RuntimeError) as e_info: ships = {Ship(1, 1, 3, "h"), Ship(2, 0, 3, "v")} _ = Board(dimensions, ships) assert str(e_info.value).startswith("overlapping ships at (2, 1)")
def test_player_is_defeated(): dims = (5, 5) s1 = {Ship(1, 1, 3, "v")} p1 = Player(Board(dims, s1)) for i in range(3): p1.opponent_move(1, 1 + i) assert p1.is_defeated
class Human(Player): def __init__(self): self.brd = Board() self.sunk = 0 self.occupied = set() def name(self): return "Player 1" def set_up(self): """Prompts the user to set up their board; manually choose which ship and hide it with hide_ships(), or automatically hide all. """ fleet = self.brd.fleet fleet_lst = [fleet[ship] for ship in fleet] random.shuffle(fleet_lst) while len(fleet_lst) > 0: print(PROMPT['border']) show_board(self.brd) select = input(PROMPT['which_ship'].format( '\n '.join([str(ship) for ship in fleet_lst]))) if select.lower() == 'a': # automates the hiding process for ship in fleet_lst: self.auto_hide_ships(ship, 1) self._confirm_setup() return # for manually hiding the selected ship if fleet.get(select.upper()) in fleet_lst: check = self.hide_ships(fleet.get(select.upper())) if check is True: fleet_lst.remove(fleet.get(select.upper())) else: continue elif select == '': self.hide_ships(fleet_lst.pop(0)) else: print(PROMPT['which_ship_explain'].format( ' '.join([str(ship.sign) for ship in fleet_lst]))) self._confirm_setup() def _confirm_setup(self): """Display the completed board setup for player to confirm or revise. """ show_board(self.brd) check = input(PROMPT['good2go']).lower() if check == 'n' or check == 'no': print(PROMPT['start_again']) self.brd.remove_fleet() return self.set_up() else: return def hide_ships(self, ship): """Prompts the user to select head using _pick_coord(), _head2tail() to show possible coords for the tail and _full() to select tail to hide a ship sends the ship object and a list of coords to Board. """ self.occupied = set(key for key in self.brd.board if self.brd.board[key] in FLEET.keys()) for n in range(3): print(PROMPT['lets_hide'].format(ship)) head = pick_coord('hide_head') if head in self.occupied: print(PROMPT['occupied']) continue if head is None: continue h2t = self._head2tail(ship, head) pos = self._full(h2t) if pos is None: continue display_pos = (convert(coord) for coord in pos) ans = input(PROMPT['pos_ok?'].format( str(ship), ' '.join(display_pos))).lower() if ans == 'n' or ans == 'no': self.hide_ships(ship) else: self.brd.place_ship(ship, pos) print(PROMPT['player_hidden'].format(str(ship))) return True def _full(self, h2t): """Uses _pick_coord() to prompt user to select the tail coord of the ship from the dict returned by _head2tail() returns the full set of coords to return to hide_ships() if selection is valid. """ if len(h2t) == 0: print(PROMPT['no_tail']) return None options = [convert(key) for key in h2t.keys()] if len(h2t) == 1: ans = input(PROMPT['this_tail_ok'].format( '{ ' + options[0] + ' }')).lower() if ans == 'n' or ans == 'no': return None else: return h2t[convert(options[0])] for n in range(3): print(PROMPT['tail_option'].format( '{ ' + ' '.join(options) + ' }')) tail = pick_coord('hide_tail') if tail in h2t.keys(): return h2t[tail] elif tail == 'r': # exception if user wants to revise head coord return None else: continue else: print(PROMPT['wrong_tail']) return None def where2bomb(self): """Human selects a coordinate to bomb. """ bomb = pick_coord('where2bomb') print(PROMPT['player_attack'].format(convert(bomb))) return bomb def win(self): """Declares Human as the winner and shows the board. """ print(PROMPT['result']) # show_game(self.players[1].brd, self.players[0].brd) print(PROMPT['one_wins'])
def __init__(self): self.brd = Board() self.sunk = 0 self.occupied = set()