Exemplo n.º 1
0
 def __init__(self, Name, Player_Number):
     self.Name = Name.title()
     if Player_Number > 0 and Player_Number < 3:
         self.Player_Num = Player_Number
     else:
         raise Exception("Invalid Player Number:", Player_Number)
     self.Player = True
     self.Ships = {}
     patrol_boat = Ship("Patrol Boat")
     submarine = Ship("Submarine")
     destroyer = Ship("Destroyer")
     battleship = Ship("Battleship")
     aircraft_carrier = Ship("Aircraft Carrier")
     self.Ships["Patrol Boat"] = patrol_boat
     self.Ships["Submarine"] = submarine
     self.Ships["Destroyer"] = destroyer
     self.Ships["Battleship"] = battleship
     self.Ships["Aircraft Carrier"] = aircraft_carrier
     #{"Patrol Boat": patrol_boat, "Submarine": submarine...}
     self.Ships_Remaining = self.get_ships_alive()
     self.Guesses = {}
     #Guesses = {"A1": "Hit", "B2": "Miss"...}
     grid = Grid()
     self.Grid = grid
     guess_grid = Grid()
     self.Guess_Grid = guess_grid
Exemplo n.º 2
0
 def test_randomPlaceShips(self):
     board = Grid(10, 10) 
     ships = [Ship('a', [1, 1, 1], value=1), Ship('b', [1, 1, 1, 1, 1], value=1), Ship('c', [1], value=1),Ship('d', [1, 1, 1, 1, 1, 1, 1], value=1)]
     Util.randomPlaceShips(board, ships)
     for ship in ships:
         newShipList = [s for s in ships if s.getName() is not ship.getName()]
         self.assertTrue(Util.shipFits(board, newShipList, ship.getLength(), ship.getPosition(), ship.getOrientation()))
Exemplo n.º 3
0
 def getShips(agent):
     carrier = Ship("Carrier", [1, 1, 1, 1, 1],
                    100,
                    Position(2, 3),
                    Ship.ORIENTATION_90_DEG,
                    immovable=True)
     battleship = Ship("Battleship", [1, 1, 1, 1],
                       80,
                       Position(0, 0),
                       Ship.ORIENTATION_0_DEG,
                       immovable=True)
     cruiser = Ship("Cruiser", [1, 1, 1],
                    60,
                    Position(6, 2),
                    Ship.ORIENTATION_180_DEG,
                    immovable=True)
     submarine = Ship("Submarine", [1, 1, 1],
                      60,
                      Position(8, 1),
                      Ship.ORIENTATION_90_DEG,
                      immovable=True)
     destroyer = Ship("Destroyer", [1, 1],
                      40,
                      Position(6, 6),
                      Ship.ORIENTATION_0_DEG,
                      immovable=True)
     return [carrier, battleship, cruiser, submarine, destroyer]
Exemplo n.º 4
0
 def testShipsAreEqual(self):
     ship1 = Ship(3, 3, 3, 1)
     ship2 = Ship(2, 4, 2, 2)
     assert ship1 != ship2
     ship1 = Ship(0, 3, 2, 1)
     ship2 = Ship(2, 4, 2, 2)
     assert ship1 == ship2
Exemplo n.º 5
0
def put_ship_on_board(let, num, dir, length, board, bot):
    coordinates = ship_coordinates(let, num, dir, length)
    for coord in coordinates:
        board[coord[0]][coord[1]][0] = True
    if bot:
        bot_ships.append(Ship(coordinates))
    else:
        my_ships.append(Ship(coordinates))
Exemplo n.º 6
0
    def __init__(self, strategy):
        if(isinstance(strategy, PlayerStrategy)):
            self._strategy = strategy
        else:
            self._strategy = HumanStrategy()

        self._board = Board()
        self._ships = [Ship("Carrier", 5), Ship("Battleship", 4), Ship("Submarine", 3), Ship("Destroyer", 3), Ship("Patrol Boat", 2)]
Exemplo n.º 7
0
 def getShips(agent):
     # Ship positions/orientations will be updated later when placing ships
     carrier = Ship("Carrier", [1, 1, 1, 1, 1], 100)
     battleship = Ship("Battleship", [1, 1, 1, 1], 80)
     cruiser = Ship("Cruiser", [1, 1, 1], 60)
     submarine = Ship("Submarine", [1, 1, 1], 60)
     destroyer = Ship("Destroyer", [1, 1], 40)
     return [carrier, battleship, cruiser, submarine, destroyer]
Exemplo n.º 8
0
def create_ships():
    carrier = Ship("Carrier", 5)
    battleship = Ship("Battleship", 4)
    cruiser = Ship("Cruiser", 3)
    submarine = Ship("Submarine", 3)
    destroyer = Ship("Destroyer", 2)
    ships = [carrier, battleship, cruiser, submarine, destroyer]
    return ships
Exemplo n.º 9
0
    def SetNewBoard(self):
        #setup new board
        self.board = Board(8)

        #place 5 ships in random coordinates
        self.board.PlaceShipAtRandomCoordinate(Ship(5, 'A'))
        self.board.PlaceShipAtRandomCoordinate(Ship(4, 'B'))
        self.board.PlaceShipAtRandomCoordinate(Ship(3, 'S'))
        self.board.PlaceShipAtRandomCoordinate(Ship(3, 'S'))
        self.board.PlaceShipAtRandomCoordinate(Ship(2, 'C'))

        self.board.initalTileListState = copy.deepcopy(self.board.tileList)
Exemplo n.º 10
0
 def test_length(self):
     #Checks to see if each ship is the correct length
     patrol_boat = Ship("Patrol Boat")
     submarine = Ship("Submarine")
     destroyer = Ship("Destroyer")
     battleship = Ship("Battleship")
     aircraft_carrier = Ship("Aircraft Carrier")
     self.assertEqual(patrol_boat.Length, 2)
     self.assertEqual(submarine.Length, 3)
     self.assertEqual(destroyer.Length, 3)
     self.assertEqual(battleship.Length, 4)
     self.assertEqual(aircraft_carrier.Length, 5)
     self.assertRaises(Exception, Ship, "Banana")
Exemplo n.º 11
0
    def test_Create(self):
        ship = Ship("carrier", [1, 2, 1], 1, Position(1, 1),
                    Ship.ORIENTATION_180_DEG)
        self.assertEqual("carrier", ship.getName())
        self.assertEqual(Position(1, 1), ship.getPosition())
        self.assertEqual(3, ship.getLength())
        self.assertEqual(Ship.ORIENTATION_180_DEG, ship.getOrientation())

        ship2 = Ship("destroyer", [1], 1)
        self.assertEqual("destroyer", ship2.getName())
        self.assertEqual(Position(0, 0), ship2.getPosition())
        self.assertEqual(1, ship2.getLength())
        self.assertEqual(Ship.ORIENTATION_0_DEG, ship2.getOrientation())
Exemplo n.º 12
0
 def __init__(self):
     self.__command = Command(
     )  # create the command object for processing commands
     self.__ship_1 = Ship("h", (0, 0))  # create the initial two ships
     self.__ship_2 = Ship("v", (3, 1))
     self.__ship_list = [self.__ship_1, self.__ship_2
                         ]  # create a list to keep track of ships
     self.__sea_row = [" 0 ", " 0 ", " 0 ", " 0 ", " 0 "
                       ]  # easier to repeat this 5 times than type it all
     self.__sea = [
         self.__sea_row, self.__sea_row, self.__sea_row, self.__sea_row,
         self.__sea_row
     ]
     self.__occupied_space = []  # no space occupied yet
Exemplo n.º 13
0
 def loadShips(self):
     shipOne = Ship(Game.NAME_SHIP_ONE, Game.START_POS_SHIP_ONE,
                    Game.START_HEADING_SHIP_ONE)
     shipTwo = Ship(Game.NAME_SHIP_TWO, Game.START_POS_SHIP_TWO,
                    Game.START_HEADING_SHIP_TWO)
     offlimits = [(vec3ToTuple(self.planet.getPos()), Game.GRAVITY_DISTANCE)
                  ]
     shipOne.setPos(self.generateRandomStartPos(offlimits))
     shipOne.heading = random.random() * 360
     shipTwo.heading = random.random() * 360
     offlimits.append((shipOne.getPos(), 150))
     shipTwo.setPos(self.generateRandomStartPos(offlimits))
     self.ships = []
     self.ships.append(shipOne)
     self.ships.append(shipTwo)
Exemplo n.º 14
0
    def timerFired(self, dt):
        self.timer += dt
        self.shipGroup.update(dt, self.isKeyPressed, self.width, self.height)
        self.asteroids.update(self.width, self.height)
        self.bullets.update(self.width, self.height)
        self.explosions.update(dt)
        self.starGroup.update()
        ship = self.shipGroup.sprite
        star = self.starGroup.sprite

        if ((not ship.isInvincible()) and pygame.sprite.groupcollide(
                self.shipGroup, self.asteroids, False, False,
                pygame.sprite.collide_circle)):

            self.explosions.add(Explosion(ship.x, ship.y))
            self.shipGroup.add(Ship(self.width / 2, self.height / 2))

        for asteroid in pygame.sprite.groupcollide(
                self.asteroids, self.starGroup, True, False,
                pygame.sprite.collide_circle):
            self.asteroids.remove(asteroid)

        for asteroid in pygame.sprite.groupcollide(
                self.asteroids, self.bullets, True, True,
                pygame.sprite.collide_circle):
            self.asteroids.add(asteroid.breakApart())
Exemplo n.º 15
0
    def start_game(self) -> str:
        """Resets the game field and draws the initial game back at level 1."""
        # Initial empty group for bullets
        self.MIN_SPAWN_DIST = 50
        self.LEVEL_TIMER_IN_SEC = 10
        self.bullets = pygame.sprite.Group()

        # Player ship
        self.player_ship = Ship(*self.WINDOW_RES, self.bullets)
        self.player_ship.update()

        # Initial asteroids
        self.asteroids = pygame.sprite.Group()
        self.asteroid_emitters = []

        for _ in range(0, 10):
            aster_x, aster_y = self.random_offset_from_ship()

            asteroid = Asteroid(aster_x, aster_y, self.DISPLAYSURF)
            self.asteroids.add(asteroid)

        # Initial asteroid emitter
        emitter = AsteroidEmitter(self.asteroids, self.DISPLAYSURF,
                                  self.random_offset_from_ship)
        self.asteroid_emitters.append(emitter)

        return 'level_1'
Exemplo n.º 16
0
def check_addships(screen, game_set, mouse_x, mouse_y, addship_btns, myfleet,
                   start_btn):
    for ship_btn in addship_btns:
        if ship_btn.rect.collidepoint(mouse_x, mouse_y) and ship_btn.active:
            # создаем соотв. корабль в моем флоте
            size = int(ship_btn.width / 50)
            ship = Ship(size, ship_btn.pos, 'right', True)

            # все остальные корабли становятся недвигабельны (хз зачем, на всякий написал)
            for i in myfleet:
                i.move = False
            '''
            for j in addship_btns:
                if not j.active:
                    j.ships_left += 1
            '''

            # добавляем корабль в список моего флота
            myfleet.append(ship)
            # теперь эту кнопку можно нажать на 1 раз меньше
            ship_btn.ships_left -= 1

            # пока ставим, все кнопки выбора кораблей пропадают
            for item in addship_btns:
                item.active = False
Exemplo n.º 17
0
    def startNewGame(self, hardMode=False):
        #starts a new game and takes flag for hardMode
        #   in hard mode, barries don't regenerate and player can damage own
        #   barriers
        self.mode = self.pauseMode
        self.playerInitials = ''
        self.isGyruss = False
        # Will store time between bullet fires
        self.bulletCoolDownTimer = 0
        self.alienBulletTimer = 0

        # Alien move stuff
        self.alienStepTimer = 0
        self.alienSpeedIncreaseFactor = 0.95
        self.alienVector = (1, 0)

        self.barrierFriendlyFire = False
        if hardMode: self.barrierFriendlyFire = True

        self.startingBarriers = 3

        self.pointsPerKill = 10
        self.alienMoveWaitTime = self.baseAlienMoveWaitTime
        self.playerLevel = 0
        self.playerLives = 3
        self.playerScore = 0
        self.populateWithAliens()
        self.placeBarriers(self.startingBarriers)
        self.shipGroup.add(
            Ship(self.shipStartX, self.shipStartY, img=self.shipSelection))
Exemplo n.º 18
0
    def create_ship(self,
                    start_x,
                    start_y,
                    length,
                    direction,
                    state='ship',
                    managed=False):
        ship = None

        if managed:
            ship = Ship()
            ship.create(start_x, start_y, length, direction, state)
            ship.cells = [None] * length
            for i in range(0, length):
                x_ = start_x
                y_ = start_y
                if direction == "V":
                    y_ = start_y + i
                elif direction == "H":
                    x_ = start_x + i
                ship.cells[i] = self.composite(x_, y_, state)
        else:
            cells = self.take_cells(start_x, start_y, length, direction)
            if self.add_ship(cells):
                for c in cells:
                    c.state = state
                ship = self.ships[-1]

        return ship
Exemplo n.º 19
0
def main():
    pygame.init()
    background_image = pygame.image.load("imagenes/space.png")
    background_rect = background_image.get_rect()
    pygame.display.set_caption("Invaders")

    ship = Ship(size)
    ufo = Ufo(size)

    a = [10]
    for i in range(1, 11):
        if i < 11:
            print i
            ufo.rect.left = ufo.rect.left + 40
            a.insert(i, ufo.rect.left)
            print a
    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        ship.update()
        ufo.update()

        screen.blit(background_image, background_rect)
        screen.blit(ship.image, ship.rect)
        for x in a:
            ufo.rect.left = x
            screen.blit(ufo.image, ufo.rect)
            ufo.update()
        pygame.display.update()
        pygame.time.delay(10)
Exemplo n.º 20
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings, screen, "Play")
    ship = Ship(ai_settings, screen)
    alien = Alien(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Exemplo n.º 21
0
 def prep_ships(self):
     self.ships = Group()
     for ship_number in range(self.stats.ships_left):
         ship = Ship(self.ai_settings, self.screen, self.sprite_sheet)
         ship.rect.x = 10 + ship_number * ship.rect.width
         ship.rect.y = 10
         self.ships.add(ship)
Exemplo n.º 22
0
    def set_ships(
        self
    ):  #set the ships on the board by handing the coordinates over to the board class

        while (True):
            x = input("How many ships do you want to play with?\n")
            os.system("cls")
            if (x == "1") | (x == "2") | (x == "3") | (x == "4") | (x == "5"):
                x = int(x)
                for i in range(x):
                    self.ships.append(i + 1)
                break
            else:
                print("Invalid number of ships! You can only have 1-5.\n")
        for i in range(len(self.ships)):
            while (True):
                final_location = self.choose_coordinates(i)
                if final_location == False:
                    continue
                else:
                    break
            front_loc = final_location[0] + final_location[1]
            back_loc = final_location[2] + final_location[3]
            self.ships.pop(i)
            self.ships.insert(i, Ship(i + 1, front_loc, back_loc))
            self.board.setUp(self.ships[i])
Exemplo n.º 23
0
 def prep_ships(self):
     self.ships = Group()
     for ship_number in range(self.stats.ships_left):
         ship = Ship(self.ai_game)
         ship.rect.x = 10 + ship_number * ship.rect.width
         ship.rect.y = 10
         self.ships.add(ship)
Exemplo n.º 24
0
    def test_shipSegmentIndex(self):
        ship = Ship("carrier", [1, 1, 1], 1)
        self.assertEqual(0, ship.shipSegmentIndex(Position(0, 0)))
        self.assertEqual(1, ship.shipSegmentIndex(Position(1, 0)))
        self.assertEqual(2, ship.shipSegmentIndex(Position(2, 0)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(3, 0)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(0, -1)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(-1, 0)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(1, 1)))

        ship.place(Position(-1, -1), Ship.ORIENTATION_90_DEG)
        self.assertEqual(0, ship.shipSegmentIndex(Position(-1, -1)))
        self.assertEqual(1, ship.shipSegmentIndex(Position(-1, 0)))
        self.assertEqual(2, ship.shipSegmentIndex(Position(-1, 1)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(-1, 2)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(0, 0)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(-1, -2)))

        ship.place(Position(-1, -1), Ship.ORIENTATION_270_DEG)
        self.assertEqual(0, ship.shipSegmentIndex(Position(-1, -1)))
        self.assertEqual(1, ship.shipSegmentIndex(Position(-1, -2)))
        self.assertEqual(2, ship.shipSegmentIndex(Position(-1, -3)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(-1, -4)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(-1, 0)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(0, 0)))
        self.assertEqual(-1, ship.shipSegmentIndex(Position(-2, -1)))
Exemplo n.º 25
0
 def update_left_ships(self):
     self.ships = Group()
     for i in range(self.stats.ships_left):
         s = Ship(self.setting, self.screen)
         s.rect.left = 10 + i * s.rect.width
         s.rect.top = 10
         self.ships.add(s)
Exemplo n.º 26
0
def main():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))  #,RESIZABLE)
    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings, screen, "Play")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    ship = Ship(ai_settings, screen)
    moon = Moon(ai_settings, screen)
    earth = Earth(ai_settings, screen)
    stars = Group()
    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    gf.create_multilayer_star(ai_settings, screen, stars)
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens,
                             bullets)
            stats.update_highscore()
        gf.update_screen(ai_settings, screen, stats, stars, sb, [moon, earth],
                         [ship], play_button, aliens, bullets)
Exemplo n.º 27
0
 def level3init(self):
     self.win = False
     self.screen3 = True
     self.bgColor = (0, 0, 0)
     Ship.init()
     ship = Ship(self.width / 2, self.height / 2)
     self.shipGroup = pygame.sprite.GroupSingle(ship)
     self.earthStage = 1
     planet = Planet(self.width / 2, self.height - 100, "earth")
     self.planetGroup = pygame.sprite.Group(planet)
     self.asteroids = pygame.sprite.Group()
     self.missiles = pygame.sprite.Group()
     self.hitCount = 1
     self.score3 = 0
     self.earthFlag = False
     self.counter = 0
     self.lost = False
     self.bgImage = pygame.transform.rotate(
         pygame.transform.scale(
             pygame.image.load('images/Lev3.png').convert_alpha(),
             (self.width, self.height)), 0)
     self.closeImage = pygame.transform.rotate(
         pygame.transform.scale(
             pygame.image.load('images/finish.jpg').convert_alpha(),
             (self.width, self.height)), 0)
Exemplo n.º 28
0
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    # 创建Play 按钮
    play_button = Button(ai_settings, screen, "Play")

    # 创建一个用于存储游戏统计信息的实例
    stats = GameStats(ai_settings)
    # 创建存储游戏统计信息的实例,并创建计分牌
    sb = Scoreboard(ai_settings, screen, stats)
    # 创建一艘飞船
    ship = Ship(ai_settings, screen)
    # 创建一个用于存储子弹的编组、一个外星人编组
    bullets = Group()
    aliens = Group()
    # 创建外星人群体
    gf.create_fleet(ai_settings, screen, ship, aliens)
    # 开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, stats, play_button, ship, aliens,
                        bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Exemplo n.º 29
0
    def __init__(self, area, asteroidsNumber):

        self.area = area

        # create asteroidsGroup
        self.asteroidNumber = asteroidsNumber
        self.asteroidsGroup = pygame.sprite.Group()
        self.createAsteroids(self.asteroidNumber)
        # print([a.pos for a in self.asteroidsGroup.sprites()[:5]])

        # create player ship
        self.ship = Ship(x=int(SCREEN_WIDTH * 0.5),
                         y=int(SCREEN_HEIGHT * 0.5),
                         color=(255, 255, 255),
                         speed=0.1,
                         theta=0.0)
        self.shipGroup = pygame.sprite.GroupSingle(self.ship)

        # create bullets
        self.bulletsGroup = pygame.sprite.Group()

        self.score = 0
        self.age = 0

        self.isOver = False
Exemplo n.º 30
0
 def create_new_ship(self, createShip, currentTime):
     if createShip and (currentTime - self.shipTimer > 900):
         self.player = Ship()
         self.allSprites.add(self.player)
         self.playerGroup.add(self.player)
         self.makeNewShip = False
         self.shipAlive = True