def update(self, dt): if randrange(60) == 0: self.vx = -self.vx Ship.update(self, dt) if self.vx > 0: self.image = self.orig_image else: self.image = self.flipped_image
def __init__(self): self.name = '' self.board = Board() self.ships = [ Ship("Destroyer"), Ship("Submarine"), Ship("Cruiser"), Ship("Battleship"), Ship("Carrier") ]
def update(self, dt): #one in 60 chance it will flip directions if randrange(60) == 0: self.vx = -self.vx Ship.update(self, dt) if self.vx > 0: self.image = self.orig_image else: self.image = self.flipped_image
def update(self, dt): vx = self.vx vy = self.vy Ship.update(self, dt) if vx != self.vx or vy != self.vy: if vx != self.vx: vx = self.vx vy = -vy else: vx = -vx vy = self.vy
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 doTurn( self, game ): (ao,ro,ag) = Ship.doTurn(self, game) if self.inNebula and self.ttl%(config.fps*2)==0: self.loseTarget( game ) if self.lostTarget and (self.originalTtl-self.ttl)>config.fps: self.launcher = None # detect hit for obj in game.objects.getWithinRadius( self, self.stats.maxRadius ): if obj.alive and obj.player and (not self.launcher or obj.player != self.launcher.player): if self.launcher: sender = self.launcher.player else: sender = None (ao0, ro0, ag0) = obj.hit( game, utils.angleBetweenObjects( obj, self ), sender, self.weapon.stats.energyDamage, self.weapon.stats.massDamage ) (ao1, ro1, ag1) = self.explode( game ) (ao, ro, ag) = (ao+ao0+ao1, ro+ro0+ro1, ag+ag0+ag1) break if self.alive and not (self.originalTtl-self.ttl)%self.thinkFreq: if isinstance( self.target, Object ): target = ( self.target.xp, self.target.yp ) if not self.target.alive: self.target = target else: target = self.target # ori destAngle = utils.angleBetween( (self.xp,self.yp), target ) angle = utils.angleDiff( destAngle, self.ori ) absAngle = fabs( angle ) if absAngle > self.stats.maxRg*2: # *(config.fps/10): #*5: if angle > 0: self.rg = self.stats.maxRg else: self.rg = -1*self.stats.maxRg else: self.rg = 0 self.thrust = self.stats.maxThrust if utils.distLowerThan( (self.xp,self.yp), target, self.stats.maxRadius*4 ): (ao1, ro1, ag1) = self.explode( game ) (ao, ro, ag) = (ao+ao1, ro+ro1, ag+ag1) # self.alive = False # ro.append( self ) # ag.append( GfxExplosion( (self.xp,self.yp), self.stats.maxRadius*3 ) ) if self.alive: if self.ttl == 0: self.alive = False ro.append( self ) else: self.ttl = self.ttl - 1 return (ao,ro,ag)
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 update(self, dt): vx = self.vx vy = self.vy Ship.update(self, dt) if vx != self.vx or vy != self.vy: if vx != self.vx: vx = self.vx vy = -vy else: vx = -vx vy = self.vy tie = TieFighter(self.rect.x, self.rect.y, vx, vy, self.bounds, self.color) for group in self.groups(): group.add(tie)
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 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 init(): """ Init game """ os.system('cls') print("\n====================") print("Welcome to LE HAVRE!") print("====================") random.shuffle(game_state.bases) # shuffle bases # print("Add Players") # player_count = 2 # int(input("Enter total player count (1-5): ")) # ai_count = 1 # int(input("Enter AI player count: ")) # for i in range(0, player_count - ai_count): # pname = input("P" + str(i+1) + " name: ") game_state.players.append(Player.create_player("Marvel")) # for i in range(0, ai_count): game_state.players.append((Player.create_player("AI"))) Building.setup_offers(game_state) Ship.setup_rounds(game_state)
def update(self, dt): vx = self.vx vy = self.vy Ship.update(self, dt) # create a new ship if bounced (when they bounce, vx, vy no longer = self.vx or self.vy if vx != self.vx or vy != self.vy: if vx != self.vx: vx = self.vx vy = -vy else: vx = -vx vy = self.vy tie = TieFighter(self.rect.x, self.rect.y, vx, vy, self.bounds, self.color) for group in self.groups(): group.add(tie)
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 generate_fake_ships(min_ships=3, max_ships=10) -> list: """Creates a list of randomly generated ships. Args: min_ships (int, optional): Minimum amount of ships to generate. Defaults to 3. max_ships (int, optional): Maximum amount of ships to generate. Defaults to 10. Returns: list: A list of ships with randomly generated parts and entry orders """ return [Ship.random() for _ in range(randint(min_ships, max_ships))]
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))
class Missile(Ship): def __init__(self, (xp, yp), zp, ori, (xi, yi), target, launcher, weapon): Ship.__init__(self, weapon.stats.projectile, None, xp, yp, zp, ori, xi, yi, 0, 0) self.target = target self.launcher = launcher self.weapon = weapon self.maxRi = 0.01 self.ttl = weapon.stats.projectileTtl #30*5 self.originalTtl = weapon.stats.projectileTtl self.lostTarget = False self.thinkFreq = 1 #randint( 2, config.fps/3) # randint( 3, config.fps/2) self.xi = launcher.xi self.yi = launcher.yi
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 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 doTurn(self, game): (ao, ro, ag) = Ship.doTurn(self, game) if self.inNebula and self.ttl % (config.fps * 2) == 0: self.loseTarget(game) if self.lostTarget and (self.originalTtl - self.ttl) > config.fps: self.launcher = None # detect hit for obj in game.objects.getWithinRadius(self, self.stats.maxRadius): if obj.alive and obj.player and ( not self.launcher or obj.player != self.launcher.player): if self.launcher: sender = self.launcher.player else: sender = None (ao0, ro0, ag0) = obj.hit(game, utils.angleBetweenObjects(obj, self), sender, self.weapon.stats.energyDamage, self.weapon.stats.massDamage) (ao1, ro1, ag1) = self.explode(game) (ao, ro, ag) = (ao + ao0 + ao1, ro + ro0 + ro1, ag + ag0 + ag1) break if self.alive and not (self.originalTtl - self.ttl) % self.thinkFreq: if isinstance(self.target, Object): target = (self.target.xp, self.target.yp) if not self.target.alive: self.target = target else: target = self.target # ori destAngle = utils.angleBetween((self.xp, self.yp), target) angle = utils.angleDiff(destAngle, self.ori) absAngle = fabs(angle) if absAngle > self.stats.maxRg * 2: # *(config.fps/10): #*5: if angle > 0: self.rg = self.stats.maxRg else: self.rg = -1 * self.stats.maxRg else: self.rg = 0 self.thrust = self.stats.maxThrust if utils.distLowerThan((self.xp, self.yp), target, self.stats.maxRadius * 4): (ao1, ro1, ag1) = self.explode(game) (ao, ro, ag) = (ao + ao1, ro + ro1, ag + ag1) # self.alive = False # ro.append( self ) # ag.append( GfxExplosion( (self.xp,self.yp), self.stats.maxRadius*3 ) ) if self.alive: if self.ttl == 0: self.alive = False ro.append(self) else: self.ttl = self.ttl - 1 return (ao, ro, ag)
def update(self, dt): vx = self.vx vy = self.vy Ship.update(self, dt)
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
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))
def update(self, dt): #if randrange(60) == 0: # self.vx = -self.vx Ship.update(self, dt)
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 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)
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 create_ship(self): new_ship = Ship(self) self.ships.add(new_ship) self.a_game.ships.add(new_ship)
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)) 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"))