def __init__(self): self.name = '' self.board = Board() self.ships = [ Ship("Destroyer"), Ship("Submarine"), Ship("Cruiser"), Ship("Battleship"), Ship("Carrier") ]
def main(input_file): with open(input_file, 'r') as f: lines = f.readlines() instruction_re = r'([N,S,W,E,L,R,F]{1})(\d*)\s*' instructions = [] for line in lines: matches = re.match(instruction_re, line).groups() direction, n = matches instructions.append(Instruction(direction, int(n))) # STAR 1 print('PART 1') ship = Ship() for instruction in instructions: ship.move(instruction) manhattan_dist = abs(ship.hor_axis) + abs(ship.vert_axis) print(f'Ship\'s final state: {ship}') print(f"Ship's Manhattan distance = {manhattan_dist}") print('\n-------------------------------------------------------\n') # STAR 2: MOVE SHIP REFERENT TO A WAYPOINT print('PART 2') ship = MovingShip() for instruction in instructions: ship.move(instruction) manhattan_dist = abs(ship.hor_axis) + abs(ship.vert_axis) print(f'Ship\'s final state: {ship}') print(f'Waypoint\'s final state: {ship.waypoint}') print(f"Ship's Manhattan distance = {manhattan_dist}")
def generate_ships(self): ids = ["S" + str(id + 1).zfill(3) for id in range(0, self.ships_num)] for id in ids: self.ships.append( Ship(id, randint(self.ships_min_width, self.ships_max_width), randint(self.ships_min_length, self.ships_max_length), randint(self.ships_min_height, self.ships_max_height)))
def __init__(self): self.board_size = 10 self.board = [] self.ship_info = [ Ship("Aircraft Carrier", 5), Ship("Battleship", 4), Ship("Submarine", 3), Ship("Cruiser", 3), Ship("Patrol Boat", 2) ] for rows in range(self.board_size): row = [] for spot in range(self.board_size): row.append(self.EMPTY) self.board.append(row) self.print_board()
def create_armada(self): armada = [] for ship_name, ship in __ARMADA__.items(): for i in range(ship['quantity']): new_ship = Ship(ship['length'], ship_name, self, ship['short_name']) armada.append(new_ship) return armada
def refresh_ships(self): for shipname in self.ships: shipcount = 0 shipsfull = self.ships[shipname] for letter in self.seamap.map: for column in self.seamap.map[letter]: if column == shipname: shipcount += 1 shipcount = ceil(shipcount / Ship(shipname).length) self.ships[shipname] = shipcount
def singlePlayer(name, size): newShip = Ship(name) newShip.generateShip(size) while board.checkAgainstBoard(newShip.coordinates, newShip.orientation): newShip.generateShip(size) else: board.updateBoard( newShip.coordinates, False ) #False = pierwszy użytkownik, zostawiam na multiplayer :)
def populate_random(self, anum=1, bnum=1, snum=1, dnum=1, pnum=2): a = Ship("Aircraft Carrier") b = Ship("Battleship") s = Ship("Submarine") d = Ship("Destroyer") p = Ship("Patrol Boat") shipnumdict = {a: anum, b: bnum, s: snum, d: dnum, p: pnum} for ship in shipnumdict: shipcount = shipnumdict[ship] while shipcount > 0: randlet = random.choice(self.letlist) randnum = random.choice(self.numlist) randdir = random.choice(self.dirlist) if self.okay_to_place(ship, randlet, randnum, randdir): print( "\nFleet Control: 'Placing {0} at {1}{2} going {3}.''". format(ship.name, randlet, randnum, randdir)) self.place_ship(ship, randlet, randnum, randdir) shipcount -= 1 print("{0} {1} left to place randomly...".format( shipcount, ship.name))
def main(): pygame.init() pygame.display.set_caption('BattleShips') screen = pygame.display.set_mode((scr_width, scr_height)) screen.fill(style.WHITE) # init fields usr_field = Field(surface=screen, cells=10, topleft=20, back_color=style.SOFT_BLUE) enemy_field = Field(surface=screen, cells=10, topleft=445, back_color=style.SOFT_RED) pygame.draw.line(screen, style.BLACK, (scr_width // 2, 0), (scr_width // 2, scr_height)) run = True # main loop while run: for event in pygame.event.get(): # close event if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: # get position event if event.button == 1: pos = pygame.mouse.get_pos() x, y = pos if x in range(0, scr_width // 2): usr_field.get_position(pos) elif x in range(scr_width // 2, scr_width): enemy_field.get_position(pos) # end event # draw fields usr_field.draw_field() enemy_field.draw_field() # draw ships ship1 = Ship(style.RED, 40, 40) screen.blit(ship1.image, ship1.rect) pygame.display.update() pygame.display.flip() # update display
def is_possible_ship(self, letter, number, direction): lengths = [] for shipname in self.opponent.ships: if self.opponent.ships[shipname] > 0: lengths.append(Ship(shipname).length) if len(lengths) == 0: print("No opponent ships still standing.") return False first = self.get_opponent_cardinal(letter, number, direction) occupants = [] newnum = number newlet = letter for i in range(max(lengths)): if direction == "right": occupant = self.get_opponent_cardinal(newlet, newnum + i, direction) if direction == "left": occupant = self.get_opponent_cardinal(newlet, newnum - i, direction)
def manageOutbound(self): dock = None lorry = Lorry(self) self.stack = self.findNeStack() while dock == None and len(self.containers) < self.max: dock = self.ask_ship() lorry.bring_container(15) while dock == None: dock = self.ask_ship() ship = Ship(dock, self.nr_containers, self.upperBound, self.port.emptyC) self.ship = ship ship.colour = self.colour self.port.ship_queue.append(ship) while len(self.containers) < self.max: lorry.bring_container(15) del lorry while not len(ship.containers) == 0: time.sleep(1 / self.speed) ship.colour = self.colour self.ship = ship ship.status = "loading" while len(self.containers) > 0: ship.accept_container(self, 10) ship.status = "leaving1" while not ship.status == "left": time.sleep(0.1) del ship self.stack.nr_groups = self.stack.nr_groups - 1 self.ship = None dock.ship = None dock.occupied = False self.max = random.randint(self.lowerBound, self.upperBound) self.activity = self.checkUnload()
def build_ship(self, identity, x, y, size, health, color, speed): new_player = Ship(identity, x, y, size, health, color, speed) self.data["ship"].append(new_player) return new_player
from ships import Desc, Board, Ship desc = Desc(3) ship1 = Ship(desc) ship2 = Ship(desc) ships = [ship1, ship2] print('game begins') desc.print_desc() while not all(ship.destroyed for ship in ships): user_input_x = int(input('type X coordinate for attack: ')) user_input_y = int(input('type Y coordinate for attack: ')) miss = True for ship in ships: for board in ship.boards: if (user_input_x, user_input_y) == (board.x_coordinate, board.y_coordinate): board.destroyed = True miss = False break if all(board.destroyed for board in ship.boards): ship.destroyed = True if ship.destroyed: ships.remove(ship) print('ship destroyed, good job!') if not miss: desc.desc[user_input_x][user_input_y] = 'X' print('board knocked down, nice!') else:
def create_ship(self): new_ship = Ship(self) self.ships.add(new_ship) self.a_game.ships.add(new_ship)
randlet = random.choice(self.letlist) randnum = random.choice(self.numlist) randdir = random.choice(self.dirlist) if self.okay_to_place(ship, randlet, randnum, randdir): print( "\nFleet Control: 'Placing {0} at {1}{2} going {3}.''". format(ship.name, randlet, randnum, randdir)) self.place_ship(ship, randlet, randnum, randdir) shipcount -= 1 print("{0} {1} left to place randomly...".format( shipcount, ship.name)) if __name__ == "__main__": m = Map() b = Ship("Battleship") b2 = Ship("Battleship") p = Ship("Patrol Boat") print(m.coord_okay(0, 8)) print(m.get_occupant(0, 0)) # m.map[5][5] = "x" for row in m.map: print(row) print(m.is_clear_lane(3, 3, "down", 5)) print(m.is_clear_lane(3, 3, "left", 5)) print(m.is_clear_lane(5, 3, "right", 5)) print(m.get_lane_occupants(3, 3, "down", 5)) print(m.get_lane_occupants(3, 3, "left", 5)) print(m.get_lane_occupants(5, 3, "right", 5)) print(m.place_ship(b, 7, 7, "up")) print(m.place_ship(b2, 5, 5, "left"))
def main(): time = 0 running = True playership = Ship(settings.PLAYER_BASE_X, settings.PLAYER_BASE_Y) enemies = initialize_enemies(3) while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: playership.shoot() if event.key == pygame.K_r: playership.ammo = 0 playership.reloading = True reload_time = time keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: playership.set_direction_X('left') if keys[pygame.K_RIGHT]: playership.set_direction_X('right') if keys[pygame.K_UP]: playership.set_direction_Y('up') if keys[pygame.K_DOWN]: playership.set_direction_Y('down') if keys[pygame.K_LEFT] and keys[pygame.K_RIGHT]: playership.set_direction_X('stop') if not keys[pygame.K_LEFT] and not keys[pygame.K_RIGHT]: playership.set_direction_X('stop') if keys[pygame.K_UP] and keys[pygame.K_DOWN]: playership.set_direction_Y('stop') if not keys[pygame.K_UP] and not keys[pygame.K_DOWN]: playership.set_direction_Y('stop') enemies[:] = [enemy for enemy in enemies if enemy.alive] Ship.bullets[:] = [ bullet for bullet in Ship.bullets if bullet.coordY > 0 and not bullet.hit] Enemy.bullets[:] = [bullet for bullet in Enemy.bullets if bullet.coordY < settings.SCREEN_HEIGHT and not bullet.hit] screen.fill((255, 255, 255)) for enemy in enemies: if detect_colision(*enemy.give_position(1), *playership.give_position(1), max_distance=64) and not playership.invincible: enemy.alive = False playership.reduce_lifes() invincible_time = time continue for bullet in playership.bullets: if bullet.hit: continue if detect_colision(*enemy.give_position(1), *bullet.give_position(1)): enemy.alive = False bullet.hit = True break else: draw(enemy.img, enemy.give_position(0)) enemy.move() if random.randint(1, 100) == 100: enemy.shoot() for bullet in Ship.bullets: draw(bullet.img, bullet.give_position(0)) bullet.move() for bullet in Enemy.bullets: if detect_colision(*bullet.give_position(1), *playership.give_position(1)) and not playership.invincible: playership.reduce_lifes() bullet.hit = True invincible_time = time else: draw(bullet.img, bullet.give_position(0)) bullet.move() if playership.reloading: if time-3000 > reload_time: playership.reload() if playership.invincible: draw(Enemy.img, playership.give_position(0)) if time - 3000 > invincible_time: playership.invincible = False if playership.lifes > 0: playership.move() draw(playership.img, playership.give_position(0)) pygame.display.update() dt = clock.tick(60) time += dt
def place_ship(self, shipname, letter, number, direction): self.seamap.place_ship(Ship(shipname), letter, number, direction)
def build_enemy_ships(self, identity, size, health, color, speed, amount): self.enemy_count = amount for number in range(amount): self.data["ship"].append( Ship(identity, rnd(20, 500), rnd(20, 30), size, health, color, speed))