def __init__(self, name): self.warships = [] self.highscore = [] self.name = name self.board = Ocean() self.board.read_board_from_file() self.view = Ocean() self.view.read_board_from_file()
def __init__(self, name): self.name = name # Gets ship. self.get_ships_placement() self._initialize_ocean_fields() # Create players board. self.board = Ocean(self.my_ships, self.ocean_fields) board_bar_len = self.board.__str__().split('\n') # Ustawia długość belki do printów. Player.board_row_len = len(board_bar_len[0])
def __init__(self): self.role = 'server' self.sock = socket.socket() self.conn = socket.socket() self.oceanSize = 5 self.player = Player('Player', Ocean(self.oceanSize)) self.opponent = Player('Opponent', Ocean(self.oceanSize)) self.host = '' self.port = -1 self.gameState = 'IDLE'
def afficherSoi(self): #afficher océan du joueur actif ocean_temporaire = Ocean(tailleoceanx,tailleoceany) #for bateau in flotte1: # for ObjetPos in bateau.listepos: # if ObjetPos.etat: # ocean_temporaire[ObjetPos.x][ObjetPos.y] = '\' # else: # ocean_temporaire[ObjetPos.x][ObjetPos.y] = '€' ocean_temporaire.afficher_ocean()
def generateOcean(self): ocean = Ocean() for shipTuple in sorted(Ship.ship_types.items(), key=lambda x: x[1], reverse=True): ship_added = False while not ship_added: chosenY = random.randint(0, 9) chosenX = random.randint(0, 9) isVertical = bool(random.getrandbits(1)) ship = Ship(shipTuple[0], isVertical, chosenY, chosenX) ship_added = ocean.insert_ship(ship) return ocean
def __init__(self, iq): self.ocean_fields = [] self._initialize_ocean_fields() self.get_ships_placement() # Create board. self.board = Ocean(self.my_ships, self.ocean_fields) self.intelligence = iq
def __init__(self, name): """ Constructs a *Player* object. Parameters: ---------- name: str enemy_ocean_representation: object player_ocean: object init_ships_dict: dict sunken_ships: list ------ """ self.name = name self.enemy_ocean_representation = Ocean() self.player_ocean = Ocean() self.init_ships_dict() self.sunken_ships = []
class Player: def __init__(self, name): self.name = name self.ocean = Ocean() def add_ship(self, ship): return self.ocean.insert_ship(ship) def has_lost(self): if not self.ocean.ships: return True return False def take_damage(self, row, column): return self.ocean.make_hit(row, column) def __str__(self): return "Player: " + self.name
def set_simulation(self): ''' Game computer - computer Returns: player_1, player_2 - Player object ''' player_type = 'computer' print('Setting computer player') user_1 = 'computer' player_1 = Player(user_1, Ocean()) player_1.generate_ships_for_computer(player_type) print('Setting second computer player') user_2 = 'computer_2' player_2 = Player(user_2, Ocean()) player_2.generate_ships_for_computer(player_type) return player_1, player_2
def starting_positions_ships(self): ''' Method to put starting coordinate on board ''' ocean_player = Ocean() os.system('clear') print(ocean_player) for key in self.player_ships: print("Enter coordinates of" + " " + key) print("(1) Horizontal\n(2) Vertical") is_connect = True while is_connect: horizontal = input("Select direction:\n") if horizontal == "1": horizontal = True elif horizontal == "2": horizontal = False else: continue numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] position_x = input("Enter x position:") while position_x not in numbers: position_x = input("Enter x position:") position_y = input("Enter y position:") while position_y not in numbers: position_y = input("Enter y position:") position_x = int(position_x) position_y = int(position_y) positions = (position_x, position_y, self.player_ships[key], horizontal) if ocean_player.board[positions[1]][positions[0] - 1].is_empty is False: print("WRONG CORDS!") continue else: is_connect = False self.starting_positions.append(positions) os.system('clear') ocean_player.preview_ships(*positions) ocean_player.add_ships(*positions) print(ocean_player) return self.starting_positions
def set_single_players(self): ''' Game player - computer. Set ships, Returns: player_1, player_2 - Player object ''' player_type = 'human' print('Setting First player') user_1 = DataReader.input_player_name() player_1 = Player(user_1, Ocean()) print('{} set you ships'.format(player_1.name)) player_1.get_ships_from_player(player_type) player_type = 'computer' print('Setting computer player') user_2 = 'computer' player_2 = Player(user_2, Ocean()) player_2.generate_ships_for_computer(player_type) return player_1, player_2
def set_multiplayers(self): ''' Game player - player. Returns: player_1, player_2 - Player object ''' player_type = 'human' print('Setting First player') user_1 = DataReader.input_player_name() player_1 = Player(user_1, Ocean()) print('{} set you ships'.format(player_1.name)) player_1.get_ships_from_player(player_type) print('Setting second player') user_2 = DataReader.input_player_name() player_2 = Player(user2, Ocean()) print('{} set you ships'.format(player_2.name)) player_2.get_ships_from_player(player_type) return player_1, player_2
def run_up(self): ''' Starting Game. Returns: None ''' mode = self.choose_option() ocean = Ocean() player_1, player_2 = self.set_mode(mode) present_player, next_player = self.choose_first_player(player_1, player_2) winner, points = self.play_game(present_player, next_player) self.end_game(winner, points)
class Human(Player): """This is User-Player class.""" def __init__(self, name): self.name = name # Gets ship. self.get_ships_placement() self._initialize_ocean_fields() # Create players board. self.board = Ocean(self.my_ships, self.ocean_fields) board_bar_len = self.board.__str__().split('\n') # Ustawia długość belki do printów. Player.board_row_len = len(board_bar_len[0]) def choose_attack_coordinates(self, opponent): """ Returns coordinates in list [x, y].""" print(' ' + self.name + ", it's bombard time! \n Please specify attack coordinates:\n") return self._input_and_check_coordinates() def _initialize_ship_coordinates(self): """ Returns dict of ships placement coordinates. """ return get_ship_dictionary_from_user_input() def _input_and_check_coordinates(self): """ Returns list of coordinates. """ correct_letters = "ABCDEFGHIJ" invalid_input_info = "invalid input." coordinate = [] row_index = "" while not row_index or row_index not in correct_letters: row_index = input(" Please, specify row (A - J): ").upper() # Goes one line up. sys.stdout.write("\033[F") # Clears the line. sys.stdout.write("\033[K") coordinate.append(correct_letters.index(row_index)) while True: try: column_index = int( input(" Please, specify column (1 - 10): ")) sys.stdout.write("\033[F") sys.stdout.write("\033[K") if column_index in range(1, 11): coordinate.append(column_index - 1) break except ValueError: sys.stdout.write("\033[F") sys.stdout.write("\033[K") return coordinate
def main(): os.system('clear') ocean1 = Ocean() ocean2 = Ocean() ocean1.format_board() ocean2.format_board() player1 = Player(ask_name('player1'), ocean1, ocean2) player2 = Player(ask_name('player2'), ocean2, ocean1) choose_all_ships(player1, ocean1) choose_all_ships(player2, ocean2) while True: print("{} TURN".format(player1.name.upper())) change_turns(player1) print("{} TURN".format(player2.name.upper())) change_turns(player2)
def create_game(): system("clear") read_ascii('ship.csv') players = determine_number_of_players() player_name = ask_for_name() ask_for_difficulty() player_1st = Player(player_name) player_2nd = Player("AI") battlefield_1st = Ocean(player_1st) battlefield_2nd = Ocean(player_2nd) system("clear") battlefield_1st.fill_board() set_up_board(battlefield_1st, player_1st) battlefield_2nd.fill_board() set_up_board(battlefield_2nd, player_2nd) return battlefield_1st, battlefield_2nd, player_1st, player_2nd, players
def main(): os.system('clear') display_intro_screen() player1_name = input('Enter your name: ') ocean1 = Ocean() ocean1.load_board() player1 = Player(player1_name, ocean1) insert_ships_to_table(ocean1, player1) print('Now player 2') player2_name = input('Enter your name: ') ocean2 = Ocean() ocean2.load_board() player2 = Player(player2_name, ocean2) insert_ships_to_table(ocean2, player2) os.system('clear') input('Now its time to start the game! If you\'re ready press Enter: \n') hide_squares(ocean1) hide_squares(ocean2) end_game = False players_list = [[ocean1, player1], [ocean2, player2]] rounds = 0 while not end_game: attacker = players_list[rounds % 2] deffender = players_list[abs((rounds % 2) - 1)] os.system('clear') print(attacker[1].name + ' is now shooting') end_game = player_round(deffender[0], deffender[1]) rounds += 1 display_end_game_screen()
def __init__(self, name, name2): self.player = Player(name) self.player2 = Player(name2) self.board = Ocean() self.board2 = Ocean()
fishAgent.y, fishAgent.x - Ihm.AGENT_LENGTH * fishAgent.vx, fishAgent.y - Ihm.AGENT_LENGTH * fishAgent.vy, fill='blue') def draw(self): self.canvas.delete(ALL) for fish in self.environment.fishs: self.drawFish(fish) for obstacle in self.environment.obstacles: self.drawObstacle(obstacle) def update(self): self.environment.update() self.draw() self.fen.after(25, self.update) def addObstacle(self, event): self.environment.addObstacle(event.x, event.y) def drawObstacle(self, obstacle): self.canvas.create_oval(obstacle.x, obstacle.y, obstacle.x + obstacle.radius, obstacle.y + obstacle.radius, fill='black') ocean = Ocean(20, 500, 500) ihm = Ihm(ocean)
fishAgent.y, fishAgent.x - Ihm.AGENT_LENGTH * fishAgent.vx, fishAgent.y - Ihm.AGENT_LENGTH * fishAgent.vy, fill=fishAgent.color) def draw(self): self.canvas.delete(ALL) for fish in self.environment.fishs: self.drawFish(fish) for obstacle in self.environment.obstacles: self.drawObstacle(obstacle) def update(self): self.environment.update() self.draw() self.fen.after(25, self.update) def addObstacle(self, event): self.environment.addObstacle(event.x, event.y) def drawObstacle(self, obstacle): self.canvas.create_oval(obstacle.x, obstacle.y, obstacle.x + obstacle.radius, obstacle.y + obstacle.radius, fill='black') ocean = Ocean(100, 500, 500) ihm = Ihm(ocean)
def __init__(self, name): """Creates Player object.""" self.name = name self.player_ocean = Ocean() self.enemy_ocean = Ocean()
# -*- coding: utf-8 -*- from interface import Interface from ocean import Ocean testJouer = Interface.start_up() if testJouer == True: h, l = Interface.saisir_params_ocean(True) o1 = Ocean() o1.construire_ocean(h, l) # o1.afficher_ocean() # Interface.saisir_params_bateau(o1) else: print("au revoir") ## Quitter le programme
def main(): ''' Function for main menu, create ships, shooting - playing the game Parameters: ----------- chose_number = int ''' os.system('clear') main_menu() chose_number = input("Enter number:\n") if chose_number == '1': os.system('clear') new_player1 = input("Enter name of player 1:\n") new_player2 = input("Enter name of player 2:\n") ship1 = player.Player(new_player1) new_ships1 = ship1.starting_positions_ships() ocean_player1 = Ocean() for s in new_ships1: ocean_player1.add_ships(*s) ship2 = player.Player(new_player2) new_ships2 = ship2.starting_positions_ships() ocean_player2 = Ocean() for s in new_ships2: ocean_player2.add_ships(*s) os.system('clear') print("GOOD LUCK") while True: turn = 1 while turn == 1: radius = range(1, 11) print("==================================") print("Your ships", new_player1) print("==================================") print(ocean_player1) shot = (int(input("Enter x:\n")), int(input("Enter y:\n"))) if shot[0] not in radius or shot[1] not in radius: continue os.system('clear') ocean_player1.shot(shot[0], shot[1]) print(ocean_player1) pauza = input() os.system('clear') turn = 2 while turn == 2: radius = range(1, 11) print("==================================") print("Your ships", new_player2) print("==================================") print(ocean_player2) shot = (int(input("Enter x:\n")), int(input("Enter y:\n"))) if shot[0] not in radius or shot[1] not in radius: continue os.system('clear') ocean_player2.shot(shot[0], shot[1]) print(ocean_player2) pauza = input() os.system('clear') break else: print('Wrong sign, try again')
self.canvas.pack() self.fen = fen self.canvas.bind_all("a", self.addFish) #attacher une touche self.canvas.bind("<Button-3>", self.addFish) # attacher la souris self.fen.after(1000, self.update) # lancer la boucle principale self.fen.mainloop() def addFish(self, event): self.environment.addFish(event.x, event.y, random.random() * 2 * pi) def drawFish(self, fishAgent): self.canvas.create_line(fishAgent.x, fishAgent.y, fishAgent.x - Ihm.AGENT_LENGTH * fishAgent.vx, fishAgent.y - Ihm.AGENT_LENGTH * fishAgent.vy, fill='blue') def draw(self): self.canvas.delete(ALL) for fish in self.environment.fishs: self.drawFish(fish) def update(self): self.environment.update() self.draw() self.fen.after(25, self.update) ocean = Ocean(10, 200, 200) ihm = Ihm(ocean)
class Player: def __init__(self, name): self.warships = [] self.highscore = [] self.name = name self.board = Ocean() self.board.read_board_from_file() self.view = Ocean() self.view.read_board_from_file() def print_boards(self): print(" ENEMY BOARD") self.view.print_board() # view = opponent board print(" YOUR BOARD") self.board.print_board() # board = your board def shoot_to_ship(self, coordinates): try: square = self.view.find_object(coordinates) square.change_to_hit() except AttributeError: pass def get_hit(self, coordinates): try: square = self.board.find_object(coordinates) square.change_to_hit() except AttributeError: pass def get_ship_coordinates(self, name, coordinates, vertical): cord = list(coordinates) cord[1] = int(cord[1]) chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', "#"] ship = Ship(name, vertical) for i in range(0, ship.lenght): square = self.board.find_object("".join([cord[0], str(cord[1])])) ship.coordinates.append(square) if ship.vertical: cord[1] += 1 else: index = chars.index(cord[0]) cord[0] = chars[index + 1] return ship def check_if_square_sign_dot(self, square): if not isinstance(square, Square): return False if square.sign == ".": return True else: return False def validate_if_ship_is_near(self, ship): chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', "#"] check_if_place = [] for coordinate in ship.coordinates: cord = list(coordinate.name) cord[1] = int(cord[1]) index = chars.index(cord[0]) for index in range( chars.index(cord[0]) - 1, chars.index(cord[0]) + 2): square = self.board.find_object("".join( [chars[index], str(cord[1] + 1)])) square1 = self.board.find_object("".join( [chars[index], str(cord[1] - 1)])) square2 = self.board.find_object("".join( [chars[index], str(cord[1])])) check_if_place.append(self.check_if_square_sign_dot(square)) check_if_place.append(self.check_if_square_sign_dot(square1)) check_if_place.append(self.check_if_square_sign_dot(square2)) return self.check_if_validate_positive(check_if_place) def check_if_validate_positive(self, validation_table): for element in validation_table: if not element: return False return True
def setupGrid(self, n, m, maxtheta=80, oceans=False, inputfile=None): ''' Sets up the Tube's grid of parcels. Args: + n, m (ints): the width and height of the grid. If inputfile is provided, the input will be padded to match n and m if one is greater than the provided dimensions, and if n and m are less than the provided dimensions they will be ignored. + maxtheta (float): the maximum latitude (in degrees) to model to. Default is 80. + oceans (bool): if True, will model oceans (default False). If inputfile is provided, will read that in for the oceans (where O's are considered oceans, X's landmasses, and spaces are ignored.) For example, if I had the file: x x o o x x o o o This would generate a 3x3 grid (provided n, m are equal to or less than 3) with one landmass in cells (0,0), (0,1), (1,1), and (1,2), with all other cells filled by oceans. If m or n was larger than 3, the remaining cells would be padded *by ocean objects*. + inputfile (str or None): if None (default) will randomly generate oceans if oceans is True. If a string, will use that file per the description above to generate a world. NOTE: If inputfile is provided, it will override the value of oceans and will assume oceans are to be generated. ''' # Read in the inputfile if provided. if inputfile is not None: # Make sure inputfile is a string assert isinstance(inputfile, str), "Infile must be None or" \ "a string" # Read in the file with open(inputfile, 'r') as infile: m = 0 lines = [] # Doing it this way for ease of coding, not expensive anyways for line in infile.readlines(): m += 1 n = 0 for char in line.strip().split(): if char.lower().strip() == 'x': val = 1 else: val = 0 lines.append(val) n += 1 landgrid = np.array(lines) elif oceans: # Randomly generate ocean map landgrid = np.random.randint(2, size=m * n) else: labdgrid = np.ones(m * n) # Assign attributes self.n = n # width self.m = m # height self.maxtheta = maxtheta # max latitude to use self.deltheta = self.maxtheta / (0.5 * m) # theta resolution self.npix = n * m self.thetas = (np.ones([m, n]) * np.linspace(maxtheta, -maxtheta, m)[:, np.newaxis]) self.Ls = abs( np.sin((90 - self.thetas.reshape(self.npix)) * np.pi / 180 + self.phi)) grid = [] for i, val in enumerate(landgrid): if landgrid[i] == 1: grid.append( Parcel(self.P, self.gamma, self.a_vec, self.A_vec, self.Ls[i], T_vec=self.T_vec)) else: grid.append(Ocean(290)) self.grid = np.reshape(grid, (m, n))
def __init__(self, name): self.name = name self.ocean = Ocean()
def __init__(self): self.ocean = Ocean()
self.canvas.pack() self.fen = fen self.canvas.bind_all("a", self.addFish) #attacher une touche self.canvas.bind("<Button-3>", self.addFish) # attacher la souris self.fen.after(1000, self.update) # lancer la boucle principale self.fen.mainloop() def addFish(self, event): self.environment.addFish(event.x, event.y, random.random() * 2 * pi) def drawFish(self, fishAgent): self.canvas.create_line(fishAgent.x, fishAgent.y, fishAgent.x - Ihm.AGENT_LENGTH * fishAgent.vx, fishAgent.y - Ihm.AGENT_LENGTH * fishAgent.vy, fill='blue') def draw(self): self.canvas.delete(ALL) for fish in self.environment.fishs: self.drawFish(fish) def update(self): self.environment.update() self.draw() self.fen.after(25, self.update) ocean = Ocean(100, 1000, 1000) ihm = Ihm(ocean)
class Player: def __init__(self, name): """ Constructs a *Player* object. Parameters: ---------- name: str enemy_ocean_representation: object player_ocean: object init_ships_dict: dict sunken_ships: list ------ """ self.name = name self.enemy_ocean_representation = Ocean() self.player_ocean = Ocean() self.init_ships_dict() self.sunken_ships = [] def append_sunken_ship(self, hit_object): """ Appends ship in specific coordinates and turn to ocean object. Parameters: ---------- ship_name: str coordinates: tuple of integers turn: bool ------ """ self.sunken_ships.append(hit_object) def init_ships_dict(self): """ Creates dictionary: keys - ship's name, values - ship's object. Parameters: ---------- """ self.ship_dict = {} self.ship_dict['Carrier'] = Ship(5) self.ship_dict['Battleship'] = Ship(4) self.ship_dict['Cruiser'] = Ship(3) self.ship_dict['Submarine'] = Ship(3) self.ship_dict['Destroyer'] = Ship(2) def add_ship_to_ocean(self, ship_name, coordinates, turn=True): """ Appends ship in specific coordinates and turn to ocean object. Parameters: ---------- ship_name: str coordinates: tuple of integers turn: bool ------ """ if ship_name not in self.ship_dict.keys(): raise NameError('Invalid ship name') ship = self.ship_dict[ship_name] ship_lenght = len(ship.square_list) column = coordinates[0] row = coordinates[1] self.check_range(column, row, ship_lenght, turn) self.check_is_water(column, row, ship_lenght, turn) for value in range(ship_lenght): square = ship.square_list[value] if turn is True: self.player_ocean.add_to_ocean((column + value, row), square) elif turn is False: self.player_ocean.add_to_ocean((column, row + value), square) def check_is_water(self, column, row, ship_lenght, turn): """ Parameters: ---------- column, row, ship_length: int turn: bool Raises: ------ KeyError: when user tries to add ship on another ship or next to. """ for x in range(-1, 2): for y in range(-1, ship_lenght + 1): if turn is True: if self.player_ocean.board.get( (column + y, row + x)) is not None: raise KeyError elif turn is False: if self.player_ocean.board.get( (column + x, row + y)) is not None: raise KeyError def check_range(self, column, row, ship_lenght, turn): """ Parameters: ---------- column, row, ship_length: int turn: bool Raises: ------ KeyError: when user wants to add ship out of edge """ max_value = 10 if turn is True: if column + ship_lenght > max_value: raise KeyError if turn is False: if row + ship_lenght > max_value: raise KeyError def shoot_ship(self, enemy, shooted_object): """ Checks what kind of object was shooted (square or water). Parameters: ---------- enemy: object shooted_object: object Returns: key - str ------ """ dict_of_ships = enemy.ship_dict for key in dict_of_ships: item_index = -1 ship = dict_of_ships[key] for square in ship.square_list: item_index += 1 if shooted_object is square: ship.mark_square(item_index) return key def _copy_object(self, object_to_shoot, shoot_coordinates): """ Double representation of player's board. Parameters: ---------- object_to_shoot: object shoot_coordinates: tuple ------ """ self.enemy_ocean_representation.add_to_ocean(shoot_coordinates, object_to_shoot) def shoot_and_check_if_is_sunk(self, enemy, shoot_coordinates): """ Checks what kind of object was shooted and returns its name. Parameters: ---------- enemy: object shoot_coordinates: tuple ------ """ object_to_shoot = enemy.player_ocean.get_item_from_ocean( shoot_coordinates) self._copy_object(object_to_shoot, shoot_coordinates) if type(object_to_shoot) is Square: shooted_object_name = self.shoot_ship(enemy, object_to_shoot) elif type(object_to_shoot) is Water: object_to_shoot.mark() shooted_object_name = 'water' return shooted_object_name
def __init__(self, name='computer'): self.name = name self.ocean = Ocean() self.enemy_ocean = Ocean() self.my_turn = False