def test_other_player(self): """test that other_player returns other player""" battleship = Battleship() player1 = battleship.players[0] player2 = battleship.players[1] self.assertEqual(battleship.other_player(player1), player2) self.assertEqual(battleship.other_player(player2), player1)
def test_board_functions(self): """test board normalization""" battleship = Battleship() table = ["bat", "puppy", "lcdsoundsystem"] normalized_table = battleship.normalize_rows(table, 16) self.assertEqual(len(table[0]), 16) self.assertEqual(len(table[1]), 16) self.assertEqual(len(table[2]), 16)
def on_loop(self): self.game.run() if AUTO_REMATCH and self.game.game_ended: for ai in ais: ai.reset_ai() self.game = Battleship(self.display, self.font, self.small_font, self.width, self.height, SHIPS, ais)
def test_coordinate_manipulation(self): """test that functions correctly find coordinates in each direction of those in lists""" battleship = Battleship() coord_set = [ ["A1", "A2", "A3"], ["A3", "A4", "A5"], ["A1"], ["A10"], ["A3"], ["D3"], ["J5"], ["D4", "E4"] ] #test below self.assertEqual(battleship.below_coord(coord_set[0]), "A4") self.assertEqual(battleship.below_coord(coord_set[1]), "A6") self.assertEqual(battleship.below_coord(coord_set[2]), "A2") #test above self.assertEqual(battleship.below_coord(coord_set[3]), "A11") self.assertEqual(battleship.above_coord(coord_set[0]), "A0") self.assertEqual(battleship.above_coord(coord_set[1]), "A2") #test right self.assertEqual(battleship.right_coord(coord_set[2]), "B1") self.assertEqual(battleship.right_coord(coord_set[5]), "E3") self.assertEqual(battleship.right_coord(coord_set[6]), None) self.assertEqual(battleship.right_coord(coord_set[7]), "F4") #test left self.assertEqual(battleship.left_coord(coord_set[2]), None) self.assertEqual(battleship.left_coord(coord_set[5]), "C3") self.assertEqual(battleship.left_coord(coord_set[6]), "I5") self.assertEqual(battleship.left_coord(coord_set[7]), "C4")
def on_event(self, event): if event.type == pygame.QUIT: self.running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: self.running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.game.game_ended: for ai in ais: ai.reset_ai() self.game = Battleship(self.display, self.font, self.small_font, self.width, self.height, SHIPS, ais)
def test_collision_during_setup(self): """test that collision_check returns old ship if new ship would overlap with it, or False if not""" battleship = Battleship() player = battleship.players[0] player.ships.append(Ship("Ship_1", ["A1", "I10"])) player.ships.append(Ship("Ship_2", ["B1", "J10"])) self.assertEqual(battleship.collision_check(player, "A1"), "Ship_1") self.assertEqual(battleship.collision_check(player, "B1"), "Ship_2") self.assertEqual(battleship.collision_check(player, "I10"), "Ship_1") self.assertEqual(battleship.collision_check(player, "J10"), "Ship_2") self.assertEqual(battleship.collision_check(player, "B6"), False)
def place_battleship(self, battleship_size, row, column, direction): """ Check if battleship can be placed in the given position and place it if possible. :param battleship_size: int which represent the battleship size :param row: str which represent the row to check if battleship is placed :param column: int which represent the column to check if battleship is placed :param direction: str 'vertical' or 'horizontal' which represent the required direction :return: True if battleship was placed or False if not """ converted_row, converted_column = self.convert_position(row, column) if direction == 'vertical': current_row = converted_row for i in range(battleship_size): if current_row < 10 and self.find_battleship(current_row, converted_column) == 'O' \ and (converted_column == 0 or self.find_battleship(current_row, converted_column - 1) == 'O')\ and (converted_column == 9 or self.find_battleship(current_row, converted_column + 1) == 'O')\ and (current_row == 0 or self.find_battleship(current_row - 1, converted_column) == 'O') \ and (current_row == 0 or converted_column == 0 or self.find_battleship(current_row - 1, converted_column - 1) == 'O') \ and (current_row == 0 or converted_column == 9 or self.find_battleship(current_row - 1, converted_column + 1) == 'O') \ and (current_row == 9 or self.find_battleship(current_row + 1, converted_column) == 'O') \ and (current_row == 9 or converted_column == 0 or self.find_battleship(current_row + 1, converted_column - 1) == 'O') \ and (current_row == 9 or converted_column == 9 or self.find_battleship(current_row + 1, converted_column + 1) == 'O'): current_row += 1 else: return False positions = [] for i in range(battleship_size): positions.append(str(converted_row) + str(converted_column)) converted_row += 1 self.battleships.append(Battleship(positions)) return True if direction == 'horizontal': current_column = converted_column for i in range(battleship_size): if current_column < 10 and self.find_battleship(converted_row, current_column) == 'O' \ and (converted_row == 0 or self.find_battleship(converted_row - 1, current_column) == 'O') \ and (converted_row == 9 or self.find_battleship(converted_row + 1, current_column) == 'O') \ and (current_column == 0 or self.find_battleship(converted_row, current_column - 1) == 'O') \ and (current_column == 0 or converted_row == 0 or self.find_battleship(converted_row - 1, current_column - 1) == 'O') \ and (current_column == 0 or converted_row == 9 or self.find_battleship(converted_row + 1, current_column - 1) == 'O') \ and (current_column == 9 or self.find_battleship(converted_row, current_column + 1) == 'O') \ and (current_column == 9 or converted_row == 0 or self.find_battleship(converted_row - 1, current_column + 1) == 'O') \ and (current_column == 9 or converted_row == 9 or self.find_battleship(converted_row + 1, current_column + 1) == 'O'): current_column += 1 else: return False positions = [] for i in range(battleship_size): positions.append(str(converted_row) + str(converted_column)) converted_column += 1 self.battleships.append(Battleship(positions)) return True
def test_ship_placement(self): """test that coordinate and direction result in correct ship placement""" battleship = Battleship() player = battleship.players[0] player.ships.append(Ship("Ship_1", ["A1", "B1"])) player.ships.append(Ship("Ship_2", ["A8", "B8"])) aircraft_carrier = battleship.ship_types[4] patrol_boat = battleship.ship_types[0] self.assertEqual(battleship.find_ship_coords_or_give_error(player, patrol_boat, "A2", "right"), ["A2", "B2"]) self.assertEqual(battleship.find_ship_coords_or_give_error(player, aircraft_carrier, "A2", "down"), ["A2", "A3", "A4", "A5", "A6"]) self.assertEqual(battleship.find_ship_coords_or_give_error(player, patrol_boat, "A1", "right"), "***This overlaps with your Ship_1!***") self.assertEqual(battleship.find_ship_coords_or_give_error(player, patrol_boat, "B8", "right"), "***This overlaps with your Ship_2!***")
def test_coordinate_validation(self): """test that coordinates are accurately verified against board borders""" battleship = Battleship() dummy_coords = [ "A1", "A01", "A10", "J1", "J10", "J11", "W1", "W11", "&99", "&9", "A100", ] self.assertEqual(battleship.validate_coordinate(dummy_coords[0]), "A1") self.assertEqual(battleship.validate_coordinate(dummy_coords[1]), "A01") self.assertEqual(battleship.validate_coordinate(dummy_coords[2]), "A10") self.assertEqual(battleship.validate_coordinate(dummy_coords[3]), "J1") self.assertEqual(battleship.validate_coordinate(dummy_coords[4]), "J10") self.assertEqual(battleship.validate_coordinate(dummy_coords[5]), False) self.assertEqual(battleship.validate_coordinate(dummy_coords[6]), False) self.assertEqual(battleship.validate_coordinate(dummy_coords[7]), False) self.assertEqual(battleship.validate_coordinate(dummy_coords[8]), False) self.assertEqual(battleship.validate_coordinate(dummy_coords[9]), False) self.assertEqual(battleship.validate_coordinate(dummy_coords[10]), False)
def __init__(self): pygame.init() pygame.font.init() pygame.display.set_caption('Battleship') icon = pygame.Surface((1, 1)) icon.fill(colors.MISS) pygame.display.set_icon(icon) self.width = BOARD_WIDTH self.height = BOARD_HEIGHT self.size = self.calc_size() self.running = True self.display = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self.clock = pygame.time.Clock() self.font = pygame.font.Font('./Roboto-Regular.ttf', FONT_SIZE) self.small_font = pygame.font.Font('./Roboto-Regular.ttf', HINT_FONT_SIZE) self.game = Battleship(self.display, self.font, self.small_font, self.width, self.height, SHIPS, ais)
def accept_connections_thread(self): while True: client, asser = self.socket_servidor.accept() if len(self.jugadores) == 0: self.jugadores[client] = 'P1' elif len(self.jugadores) == 1: self.jugadores[client] = 'P2' listen_thread = threading.Thread(target=self.listen_thread, args=(client,), daemon=True) listen_thread.start() if len(self.jugadores) == 2: self.juego = Battleship(loaded=True) msj1 = {'status': 'result', 'data': self.juego.view_from('P1'), 'turno': 'SI'} msj2 = {'status': 'result', 'data': self.juego.view_from('P2'), 'turno': 'NO'} self.send(list(self.jugadores)[0], msj1) self.send(list(self.jugadores)[1], msj2) break
def test(): # Initialize game bs = Battleship() bs.user.board.iloc[5:8, 2] = 1 bs.user.board.iloc[2][5:9] = 1 bs.user.shots.iloc[:,7:10] = True bs.pc.board.iloc[5:8, 2] = 1 bs.pc.board.iloc[2][5:9] = 1 bs.pc.shots.iloc[:,7:10] = True print(bs.user.board) print(bs.user.shots) # print game board status print(bs)
def gen_ship(self, i=None, j=None, length=None, number=1): if self.is_playable(): available = self.lines(filter_vals=True) max_length = max([len([line]) for line in available]) print("max_length", max_length, "\navailable:", available) print("STUFF", list(map(len, available))) max_length, max_line = max_idx(list(map(len, available))) available_ship_lens = [ sl for sl in self.random_ship_lengths if sl <= max_line ] remaining_lines = [ line for line in available if len(line) <= max_line and len(line) in available_ship_lens ] if not remaining_lines: raise ValueError("Not enough space to spawn a new ship.") chosen_line = choice(remaining_lines) print( dict_print( { "available": available, "max_length_idx": max_length, "available[max_length]": available[max_length], "available_ships": available_ship_lens, "max_line": max_line, "remaining_lines": remaining_lines, "choice_idx": chosen_line, }, "Generating Ship")) battleship = Battleship( "Battleship #{}".format( str(len(self.battleships) + 1).rjust(2, "0")), chosen_line) self.add_battleship(battleship) else: raise ValueError( "Unable to generate a new battleship on current grid. No available cells." ) if 1 < number: self.gen_ship(i=i, j=j, length=length, number=number - 1)
def play_battleship(input_path, output_path): with open(input_path, 'r') as f: # Create a new board battleship = Battleship(f.readline()) # add ships to the board ships = f.readline().rstrip().split(') ') for ship in ships: battleship.place_ship(ship[X_INDEX], ship[Y_INDEX], ship[ORIENTATION_INDEX]) # operate ships for line in f: x = line[X_INDEX] y = line[Y_INDEX] if len(line) > SUNK_LINE_LEN: # move the ship operations = line[SUNK_LINE_LEN:].rstrip() battleship.move_ship(x, y, operations) else: battleship.sunk_ship(x, y) # print result to a output file with open(output_path, 'w') as f: f.write(str(battleship))
def main(args): # Initialize game bs = Battleship() if args.instructions: print(bs.instructions()) return # game with custom ship numbers if args.custom: ship_nmbrs = zeros(5) ship_names = ['carriers', 'battleships', 'destroyers', 'submarines', 'patrol boats'] input_needed = True while input_needed: for i in range(5): shipnum = input("Please enter number of {:12s} (size={}): ".format(ship_names[i], 5-i)) try: ship_nmbrs[i] = int(shipnum) except ValueError: print("Input is not a Number. Number of {} is set to zero.".format(ship_names[i])) # Number of ship field should not exceed a certain limit # multiply ship quantity with their respective size, sum all elements up shipnum = ([5,4,3,2,1]*ship_nmbrs).sum() if shipnum <= 30: input_needed = False else: print("The number of ship fields ({:.0f}) is too high (max 30). Please consider less or smaller ships.".format(shipnum)) bs.set_ship_nmbrs(ship_nmbrs.astype(int)) else: bs.set_ship_nmbrs(array([1,1,2,2,2])) # distribute ships on both pc and user grids bs.distribute_ships() print("Game started.\n") while(1): # game routine # print game board status print(bs, "\n") # prevent pc from playing after inputs restart/ships/quit->no user_turn = True while(user_turn): shot = input("Please enter field(e.g. E5)/ships/quit/restart: ").upper() # upper characters to limit possibilities # play game if (shot[0] in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]) and (len(shot)>=2): if shot[1:] in ['1','2','3','4','5','6','7','8','9','10']: res = bs.user.shoot(shot) sleep(1) print(res) sleep(1) if not res == 'Field is already shot': user_turn = False else: print("Row number has to be between 1 and 10.") # restart game elif shot in ["RESTART", "R"]: bs.restart() print("\nGame restarted.\n") print(bs, "\n") # quit game elif shot in ["QUIT", "Q"]: while(1): confirmation = input("Do you really want to quit game? (yes/y/Y/no/n/N) ") if confirmation.lower() in ["yes", "y"]: return elif confirmation.lower() in ["no", "n"]: break # print remaining ships elif shot in ["SHIPS", "S"]: # print remaining ships print("\n"+bs.remaining_ships()+"\n") # no pattern matched else: print("No pattern matched. Please try again.") # calculate computer move pc_move = bs.create_computer_move() print("Computer chooses field: "+ pc_move) sleep(1) # execute computer move # TODO # res = bs.pc.shoot(pc_move) # print shoot result # print(res, "\n") sleep(1) # check if one party has won if bs.user.game_over: if bs.pc.game_over: print("DRAW! All ships are destroyed! What a game...") else: print("VICTORY! Congratulations, you have destroyed all ships!") break elif bs.pc.game_over: print("DEFEAT! Computer has found all of your ships!") break
from http.server import HTTPServer, BaseHTTPRequestHandler import urllib from battleship import Battleship import sys host = "localhost" port = int(sys.argv[1]) board_path = sys.argv[2] game = Battleship(board_path=board_path) print(game.format_board(game.opp_board)) class Handler(BaseHTTPRequestHandler): def do_HEAD(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): if self.path == ("/own_board.html"): #print("Serving own board") self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() board = game.generate_board_html(game.own_board) #print(game.format_board(game.own_board)) self.wfile.write(bytes(board, 'utf-8')) if self.path == ("/opponent_board.html"): #print("Serving opponent board")
from battleship import Battleship MAX_TRIES = 20 gameFinished = False user1 = "Rodrigo" user2 = "Felipe" battleship = Battleship(user1, user2, MAX_TRIES, 2, 2, 1) currentUser = user1 battleship.drawUserBoards(currentUser) winner = None while winner is None: row, column = battleship.getUserInputRandom(currentUser) nextUser = battleship.updateBoardWithInputAndReturnNextPlayer( currentUser, row, column) battleship.drawOtherUserBoard(currentUser) winner = battleship.getWinner() if winner is None: currentUser = nextUser battleship.drawUserBoards(currentUser) print("\nCongrats " + currentUser + "! You won the game on Round [" + str(battleship.currentRound) + "]!!!")
from battleship import Battleship print("Welcome to Battleship") print("Enter the size of grid:", end=" ") size = int(input()) bs = Battleship(size) bs.start_game() while not bs.is_game_over(): bs.turn() if bs.is_won(): print("You won") else: print("You lost")
class Main: def __init__(self): pygame.init() pygame.font.init() pygame.display.set_caption('Battleship') icon = pygame.Surface((1, 1)) icon.fill(colors.MISS) pygame.display.set_icon(icon) self.width = BOARD_WIDTH self.height = BOARD_HEIGHT self.size = self.calc_size() self.running = True self.display = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self.clock = pygame.time.Clock() self.font = pygame.font.Font('./Roboto-Regular.ttf', FONT_SIZE) self.small_font = pygame.font.Font('./Roboto-Regular.ttf', HINT_FONT_SIZE) self.game = Battleship(self.display, self.font, self.small_font, self.width, self.height, SHIPS, ais) def calc_size(self): height = (RECT_SIZE * self.height + (self.height + 1) * RECT_MARGIN) + SCREEN_PADDING * 4 width = (RECT_SIZE * self.width + (self.width + 1) * RECT_MARGIN) * 2 + SCREEN_PADDING * 6 return [width, height] def on_event(self, event): if event.type == pygame.QUIT: self.running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: self.running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and self.game.game_ended: for ai in ais: ai.reset_ai() self.game = Battleship(self.display, self.font, self.small_font, self.width, self.height, SHIPS, ais) def on_loop(self): self.game.run() if AUTO_REMATCH and self.game.game_ended: for ai in ais: ai.reset_ai() self.game = Battleship(self.display, self.font, self.small_font, self.width, self.height, SHIPS, ais) def on_render(self): self.game.draw() pygame.display.update() self.clock.tick(args.fps) def on_cleanup(self): pygame.quit() def run(self): while (self.running): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup()
def setUp(self): self.battleship = Battleship(['00', '01', '02', '03'])
class TestBattleship(unittest.TestCase): def setUp(self): self.battleship = Battleship(['00', '01', '02', '03']) def test_contains_Z_before(self): self.assertEqual(self.battleship.is_contained('00'), 'Z') def test_contains_X_after(self): self.battleship.hit('00') self.assertEqual(self.battleship.is_contained('00'), 'X') def test_contains_O_before(self): self.assertEqual(self.battleship.is_contained('04'), 'O') def test_contains_O_after(self): self.battleship.hit('04') self.assertEqual(self.battleship.is_contained('04'), 'O') def test_hit_if_miss(self): self.assertFalse(self.battleship.hit('07')) def test_hit_if_hit(self): self.assertTrue(self.battleship.hit('01')) def test_hit_twice(self): self.battleship.hit('01') self.assertFalse(self.battleship.hit('01')) def test_hit_if_not_sunk(self): self.battleship.hit('01') self.assertFalse(self.battleship.is_sunk) def test_hit_if_sunk(self): self.battleship.hit('01') self.battleship.hit('03') self.battleship.hit('02') self.battleship.hit('00') self.assertEqual(self.battleship.is_sunk, True)
from battleship import Battleship if __name__ == "__main__": game = Battleship() # Show game splash screen # Input for first and second player for x in range(2): game.init_player(x + 1) turns = range(game.get_player_count()) for x in turns: game.change_and_announce_player() game.choose_ships() # Announce start of game while True: game.change_and_announce_player() win = game.make_move() if win is True: break # Show win screen game.win()
class Server: def __init__(self): print("Inicializando servidor...") self.host = "localhost" self.port = 1234 self.socket_servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_servidor.bind((self.host, self.port)) print("Dirección y puerto enlazados..") self.socket_servidor.listen(2) thread = threading.Thread(target=self.accept_connections_thread, daemon=True) thread.start() print("Servidor aceptando conexiones...") self.jugadores = {} self.sockets = {'P1': None, 'P2': None} self.jugada = {'P1': None, 'P2': None} def accept_connections_thread(self): while True: client, asser = self.socket_servidor.accept() if len(self.jugadores) == 0: self.jugadores[client] = 'P1' elif len(self.jugadores) == 1: self.jugadores[client] = 'P2' listen_thread = threading.Thread(target=self.listen_thread, args=(client,), daemon=True) listen_thread.start() if len(self.jugadores) == 2: self.juego = Battleship(loaded=True) msj1 = {'status': 'result', 'data': self.juego.view_from('P1'), 'turno': 'SI'} msj2 = {'status': 'result', 'data': self.juego.view_from('P2'), 'turno': 'NO'} self.send(list(self.jugadores)[0], msj1) self.send(list(self.jugadores)[1], msj2) break def listen_thread(self, client): while True: respuesta = client.recv(4) largo_respuesta = int.from_bytes(respuesta, byteorder='big') resp = bytearray() while len(resp) < largo_respuesta: resp += client.recv(256) print(resp) resp = resp.decode() decod = json.loads(resp) print(decod) self.handle_command(decod, client) def handle_command(self, recived, cliente): if recived['status'] == 'posicion': if self.jugada[self.jugadores[cliente]] is None: self.jugada[self.jugadores[cliente]] = recived['data'] self.play_time(cliente) elif recived['status'] == 'salida': cliente2 = [cl for cl in self.jugadores.keys() if cl != cliente] p = self.jugadores[cliente2[0]] msj = {'status': 'result', 'data': p} self.send(list(self.jugadores)[0], msj) self.send(list(self.jugadores)[1], msj) def play_time(self, cliente): if not self.juego.game_over(): jugada = self.jugada[self.jugadores[cliente]] self.juego.attack(self.jugadores[cliente], jugada) p = self.jugadores[cliente] cliente2 = [cl for cl in self.jugadores.keys() if cl != cliente] p2 = '' if p == 'P1': p2 = 'P2' turno1 = 'NO' turno2 = 'SI' else: p2 = 'P1' turno1 = 'SI' turno2 = 'NO' msj1 = {'status': 'result', 'data': self.juego.view_from(p), 'turno': turno1} msj2 = {'status': 'result', 'data': self.juego.view_from(p2), 'turno': turno2} self.send(cliente, msj1) self.send(cliente2[0], msj2) else: ganador = self.juego.get_winner() msj = {'status': 'salida', 'data': 'El jugador {} ha ganado'.format(ganador)} self.send(list(self.jugadores)[0], msj) self.send(list(self.jugadores)[1], msj) def send(self, socket, valor): msg_json = json.dumps(valor) msg_bytes = msg_json.encode() msg_length = len(msg_bytes).to_bytes(4, byteorder="big") socket.send(msg_length + msg_bytes)