Exemplo n.º 1
0
    def __init__(self):

        #initialize game
        pygame.init()

        #icon
        self.icon = pygame.image.load('images/icon.png')

        pygame.display.set_icon(self.icon)

        #screen size
        self.screen = pygame.display.set_mode((800, 600))

        #ships object
        self.ship = Ship(self)

        self.bullet = Bullets(self)
        #game name
        pygame.display.set_caption('my game')

        #background image
        self.background = pygame.image.load('images/background.png')

        #load ship sound when moving
        self.accelarate = pygame.mixer.Sound('music/accelarate.wav')
Exemplo n.º 2
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.º 3
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.º 4
0
    def __init__(self):
        '''initialize game and resources'''
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))

        self.stats = Game_stats(self)
        self.score = Scoreboard(self)

        pygame.display.set_caption("Alien Invasion")

        # ship
        self.ship = Ship(self)

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

        # alien
        self.aliens = pygame.sprite.Group()

        self._create_invasion()

        #control
        self.play_button = Button(self, "Play")
Exemplo n.º 5
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.º 6
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.º 7
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.º 8
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")
    ship = Ship(screen, ai_settings)
    bullets = Group()
    aliens = Group()
    healths = Group()
    stats = GS(ai_settings)
    score = sc(ai_settings, screen, stats)
    play_button = Button(ai_settings, screen, 'Play')
    gf.create_fleet(ai_settings, screen, aliens, ship)
    gf.health_bar(ai_settings, screen, stats, healths)

    #start

    while True:

        #Check the pressing of keyboard and mouse
        gf.check_events(ai_settings, screen, ship, bullets, play_button, stats,
                        aliens, healths, score)

        #last display every iteration of screen
        if stats.game_active:
            ship.update()
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
            gf.update_bullets(bullets, aliens, ai_settings, screen, ship,
                              stats, score)
            gf.update_bar(healths, stats)
            gf.update_screen(ai_settings, screen, ship, bullets, aliens,
                             healths, score)
        else:
            gf.Start_Game(ai_settings, screen, play_button)
Exemplo n.º 9
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
Exemplo n.º 10
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.º 11
0
def runGame():
    #initialize pygame, screen and screen object
    pygame.init()
    aiSettings = Settings(
    )  #store the settings variables in the aiSettings to access them through this variable
    screen = pygame.display.set_mode(
        (aiSettings.screenWidth, aiSettings.screenHeight))
    pygame.display.set_caption(aiSettings.caption)

    #make a ship
    ship = Ship(aiSettings, screen)
    #make an alien
    alien = Alien(aiSettings, screen)

    #make a group to store bullets in & a group of aliens
    bullets = Group()
    aliens = Group()

    #create the fleat of aliens
    gf.createFleet(aiSettings, screen, ship, aliens)

    #start the main loop for the game
    while True:
        #Watch for keyboard/mouse events
        gf.checkEvents(aiSettings, screen, ship, bullets)
        ship.update()
        gf.updateBullets(bullets)
        gf.updateScreen(aiSettings, screen, ship, aliens, bullets)
Exemplo n.º 12
0
def run_game():
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("Alien Invaders")
    ship = Ship(screen, setting)
    bullets = Group()
    aliens = Group()

    play_button = Button(setting, screen, "Play")

    stats = GameStats(setting)

    sb = Scoreboard(setting, screen, stats)

    g_o = GameOver(screen, "Game Over")

    gf.create_fleet(setting, screen, aliens, ship)

    while True:
        gf.check_game(ship, setting, screen, bullets, aliens, stats,
                      play_button, sb)
        gf.screen_update(setting, screen, ship, bullets, aliens, stats,
                         play_button, sb)
        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets, aliens, setting, ship, screen, stats,
                              sb)
            gf.update_aliens(setting, aliens, ship, screen, bullets, stats, sb)
            gf.screen_update(setting, screen, ship, bullets, aliens, stats,
                             play_button, sb)
Exemplo n.º 13
0
def load_params(mud):
    """

    :type mud: Mud
    """
    bases = []
    ships = []
    space = []
    events = []
    try:
        with open(SAVE_FILE) as json_file:
            data = json.load(json_file)
    except OSError:
        print("Starting a new game!  Enter 'help' for commands.")
        return Action(mud)
    mud.ore = int(data['ore'])
    mud.bmat = int(data['bmat'])
    mud.fuel = int(data['fuel'])
    for b in data['bases']:
        bases.append(b)
    mud.bases = bases
    for s in data['ships']:
        ships.append(Ship.load(s))
    mud.ships = ships
    for s in data['space']:
        space.append(Ship.load(s))
    mud.space = space
    for e in data['events']:
        eve = MyEvent.load(e)
        events.append(eve)
    mud.events = events
    return Action(mud)
Exemplo n.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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.º 19
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.º 20
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.º 21
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.º 22
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.º 23
0
 def prep_ships(self):
     self.ships = Group()
     for ship_number in range(self.stats.ships_left):
         ship = Ship(self.confg, self.tela)
         ship.image = pygame.image.load("Images/Ship_Draw.bmp")
         ship.rect.x = 10 + ship_number * ship.rect.width
         ship.rect.y = 10
         self.ships.add(ship)
Exemplo n.º 24
0
    def __init__(self):
        pygame.init()

        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))

        self.ship = Ship(self)

        pygame.display.set_caption('Alien Invasion')
Exemplo n.º 25
0
 def initShip(self, x, y):
     self.theta = 90
     self.angle = -110
     self.shipFlag = True
     self.r = 120
     # # if self.shipCount<=5:
     # self.shipCount+=1
     Ship.init()
     ship = Ship(x, y)
     self.shipGroup = pygame.sprite.GroupSingle(ship)
Exemplo n.º 26
0
def loadAll(load_name):
	global system_list
	global planet_list
	global ship_list
	global crew_list
	global game_folder

	makePartsList()
	path_to_load = game_folder + '/' + 'Save' + '/' + str(load_name)

	file_to_read = open(path_to_load + '/' + 'system', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'state':
			system = System()
			system.load(tmp)
			system_list.append(system)
			tmp = []
	file_to_read.close()

	file_to_read = open(path_to_load + '/' + 'planet', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'resourse':
			planet = Planet()
			planet.load(tmp)
			planet_list.append(planet)
			tmp = []
	file_to_read.close()

	file_to_read = open(path_to_load + '/' + 'ship', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'spot':
			ship = Ship()
			ship.load(tmp)
			ship_list.append(ship)
			tmp = []
	file_to_read.close()

	file_to_read = open(path_to_load + '/' + 'crew', 'r')
	tmp = []
	for line in file_to_read:
		tmp.append(line.split(':')[1])
		if line.split(':')[0] == 'weapon':
			crew = Crew()
			crew.load(tmp)
			crew_list.append(crew)
			tmp = []
	file_to_read.close()

	gui.paintWindowGalaxy()
Exemplo n.º 27
0
def game_loop():
    global ship
    ship = Ship(gameDisplay)

    createAlien()

    global shotAliens  #Displayed in upper half
    shotAliens = 0

    gameExit = False
    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        keys = pygame.key.get_pressed()

        #TODO: OR MAYBE EVEN ALIENS IN FORMATION, ADD MOVEMENT LOGIC TO IT
        if keys[pygame.K_LEFT] and ship.x > velocity:
            ship.x -= 40
        if keys[pygame.K_RIGHT] and ship.x < display_width - 100 - velocity:
            ship.x += 40
        if keys[pygame.K_SPACE]:
            shootBullet()

        gameDisplay.fill(white)
        ship.updateShip()
        displayShotAliens(shotAliens)

        #Randomly creates aliens at a certain time
        randomNumber = random.randrange(1, 20)
        if (randomNumber == 1):
            createAlien()

        try:
            collisionCheckAliens()
        except UnboundLocalError as error:
            pass

        #Bullet update, add delay to amount of bullets you can shoot
        updateShipBullets()
        #Alien Updates\
        updateAliens()

        updateAlienBullets()

        if collisionCheckShip(ship):
            #message_display('You Died')
            pygame.time.delay(5000)  #TODO: Clear logic and restart
            pygame.quit()
            quit()

        pygame.display.update()
        clock.tick(60)
Exemplo n.º 28
0
    def __init__(self):
        """Initialize game."""

        self.settings = Settings()
        self.initScreen()

        self.ship = Ship(self.screen)

        self.bullets = Group()
        # Startup app sound
        pygame.mixer.music.load('sounds/start.mp3')
Exemplo n.º 29
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.º 30
0
def test_ship():
    test = Ship()
    test.crew = import_crew()
    test.current_satisfaction = .5
    test.priority = 0
    test.research = [1.0, 1.0, 1.0, 1.0,
                     1.0]  #health, safety, art, research, engine
    test.speed = .01
    test.distance = 50.0
    test.mission_year = 1000
    test.fuel = 2500000
    return test
Exemplo n.º 31
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.º 32
0
class LunarLander:
    def __init__(self):
        window = Tk()
        window.title("Lunar Lander")

        self.canvas = Canvas(window, bg='black', width=500, height=400)
        self.canvas.pack()

        landscape = Landscape(self.canvas)
        self.ship = Ship(self.canvas)

        window.bind("<Left>", self.left)
        window.bind("<Right>", self.right)
        window.bind("<Up>", self.thrust)

        window.bind("<Button-1>", self.p)
        window.bind("<B1-Motion>", self.m)

        self.isStopped = False
        self.sleepTime = 100
        self.rad = 0
        self.updateLoop()

        window.mainloop()

    def updateLoop(self):
        while not self.isStopped:
            self.canvas.after(self.sleepTime)
            self.rad += .2
            self.canvas.update()

    def p(self, event):
        print(event.x,'\t', event.y)
        self.ship.press(event.x, event.y)

    def m(self, event):
        print(event.x,'\t',event.y)
        self.ship.motion(event.x, event.y, self.rad)

    def left(self, event):
        self.ship.press(1,0)
        self.ship.motion(1,0)

    def right(self, event):
        print(self.angle)
        self.ship.motion(math.cos(self.angle), math.sin(self.angle))

    def thrust(self, event):
        print('thrust')
Exemplo n.º 33
0
def run_game():
    # Initialize the game and create screen.

    ai_settings=Settings()
    pygame.init()
    screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    ship=Ship(ai_settings,screen)

    while True:

        gf.check_events(ship)
        ship.update()
        gf.update_screen(ai_settings,screen,ship)
Exemplo n.º 34
0
    def init(self):
        self.bgColor = (0, 0, 0)
        Ship.init()
        ship = Ship(self.width / 2, self.height / 2)
        self.shipGroup = pygame.sprite.GroupSingle(ship)

        Asteroid.init()
        self.asteroids = pygame.sprite.Group()
        for i in range(5):
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            self.asteroids.add(Asteroid(x, y))

        self.bullets = pygame.sprite.Group()

        Explosion.init()
        self.explosions = pygame.sprite.Group()
Exemplo n.º 35
0
def deserializeShip(ship):
    retship = Ship(ship['location'], ship['bounds'], 0, 0, 0, 0)
    retship.direction = ship['direction']
    retship.death_timer = ship['death_timer']
    retship.moved = ship['moved']
    retship.shield_obj = deserializeRect(ship['shield_obj'])
    retship.velocity = ship['velocity']
    retship.id = ship['id']
    return retship
Exemplo n.º 36
0
class Asteroids(Game):
    def __init__(self, name, screen_x, screen_y, frames_per_second):
        Game.__init__(self, name, screen_x, screen_y)
        ship_position = Point(config.SCREEN_X/2, config.SCREEN_Y/2)
        self.ship = Ship(ship_position, config.SHIP_INITIAL_DIRECTION, config.SHIP_COLOR)
        self.bullet = Bullet(Point(0,0), config.BULLET_RADIUS, 0, config.BULLET_COLOR)
        self.stars = []
        for i in range(config.STAR_COUNT):
            s = Star()
            self.stars.append(s)
        self.rocks = []
        for i in range(config.ROCK_COUNT):
            (x,y) = random.randint(0, config.SCREEN_X), random.randint(0, config.SCREEN_Y)
            p = Point(x,y)
            r = Rock(p, random.uniform(0, 360.0), config.ROCK_COLOR, (random.uniform(0.0, config.ROCK_MAX_ROTATION_SPEED) * random.uniform(-1.0,1.0)), random.randint(0, config.ROCK_MAX_SPEED))
            self.rocks.append(r)

    def game_logic(self, keys, newkeys):
        for s in self.stars:
            s.game_logic(keys, newkeys)
        self.ship.game_logic(keys, newkeys)
        for rock in self.rocks:
            rock.game_logic(keys, newkeys)
            if rock.isActive() == True:
                if self.ship.intersect(rock) == True:
                    self.ship.set_inactive()
                if self.bullet.intersect(rock) == True:
                    rock.set_inactive()
                    self.bullet.set_inactive()
        if pygame.K_SPACE in newkeys:
            if self.ship.isActive() == True:
                points = self.ship.getPoints()
                self.bullet.fire(points[0], self.ship.rotation)
        self.bullet.game_logic(keys,newkeys)

    def paint(self, surface):
        self.screen.fill(config.BACKGROUND_COLOR)
        for s in self.stars:
            s.paint(surface)
        self.ship.paint(surface)
        self.bullet.paint(surface)
        for rock in self.rocks:
            rock.paint(surface)
Exemplo n.º 37
0
def run():
	pygame.init()   
	start = 1
	w = 1024
	h = 600
	screen = pygame.display.set_mode((w, h))
	ship = Ship(screen, w, h)
	npc=NPCAsteroids(w,h/2,Vec2(64,64),Vec2(32,32))
    
	while start:
		pygame.time.wait(5)
		event = pygame.event.poll()
		if event.type == pygame.QUIT:
			running = 0
		screen.fill((0, 0, 0))
		key = pygame.key.get_pressed()
		#update logic
		ship.move(key, w)
		npc.move()
		#update graphics
		ship.draw(screen)
		npc.draw(screen)
		pygame.display.flip()
Exemplo n.º 38
0
def generateShip(race,model):
	global ship_list
	global system_list
	ship = Ship()
	ship.id = len(ship_list) + 100
	ship.name = 'SHIP NAME ' + str(ship.id)
	ship.race = race
	ship.model = model
	ship.size = 10
	start_system = random.choice(system_list)
	ship.position_on_galaxy = start_system.position
	ship.coures_on_galaxy = ship.position_on_galaxy
	for i in range(0, 40):
		for j in range(0, 40):
			ship.spot.append([i, j, 0, 0, 0, 0, 0])
	ship_list.append(ship)
Exemplo n.º 39
0
    def nuevaPartida(self):
        
        if (not self.marcadorFinalNP is None):
            self.marcadorFinalNP.detachNode()
            self.marcadorFinalNP.remove()

        if (not self.rankingNP is None):
            self.rankingNP.detachNode()
            self.rankingNP.remove()

        self.ship = Ship(self.inputManager)
        self.mostrarInfo()

        taskMgr.add(self.actualizarInfo, "Actualizar Puntuacion")
Exemplo n.º 40
0
    def __init__(self, player_ship, font, small_font, window_size, enemies=None):
        self.player_ship = player_ship
        self.font = font
        self.small_font = small_font
        self.window_size = window_size
        self.center = (self.window_size[0]/2, self.window_size[1]/2)

        if player_ship is None:
            print "You have no ship and you lose somehow"

        self.melee_range = Range(distance=100, center=self.center, ring_color=Color.red)
        self.close_range = Range(distance=150, center=self.center, ring_color=Color.gray)
        self.far_range = Range(distance=200, center=self.center, ring_color=Color.d_gray)
        self.scanner_range = Range(distance=250, center=self.center, ring_color=Color.black, ship_color=Color.d_gray)

        self.ranges = [self.melee_range, self.close_range, self.far_range, self.scanner_range]

        self.enemy_ships = []

        if enemies:
            for enemy in enemies:
                en_ship = Ship(size_x=40, size_y=40)
                en_ship.load("{0}{1}".format(settings.main_path, enemy["ship_file"]))
                self.scanner_range.enemies.append(en_ship)
                self.enemy_ships.append(en_ship)

        for ship in self.enemy_ships:
            print 'attack: {0} - armor: {1} - speed: {2} - shield: {3}'.format(ship.ship_stats['attack'],
                                                                               ship.ship_stats['armor'],
                                                                               ship.ship_stats['speed'],
                                                                               ship.ship_stats["shield"])

        self.side_panel = SpaceBattlePanel(self)

        self.target = None
        self.battle_state = {'move': 1,
                             'decide': 2}
Exemplo n.º 41
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.º 42
0
 def __init__(self, name, screen_x, screen_y, frames_per_second):
     Game.__init__(self, name, screen_x, screen_y)
     ship_position = Point(config.SCREEN_X/2, config.SCREEN_Y/2)
     self.ship = Ship(ship_position, config.SHIP_INITIAL_DIRECTION, config.SHIP_COLOR)
     self.bullet = Bullet(Point(0,0), config.BULLET_RADIUS, 0, config.BULLET_COLOR)
     self.stars = []
     for i in range(config.STAR_COUNT):
         s = Star()
         self.stars.append(s)
     self.rocks = []
     for i in range(config.ROCK_COUNT):
         (x,y) = random.randint(0, config.SCREEN_X), random.randint(0, config.SCREEN_Y)
         p = Point(x,y)
         r = Rock(p, random.uniform(0, 360.0), config.ROCK_COLOR, (random.uniform(0.0, config.ROCK_MAX_ROTATION_SPEED) * random.uniform(-1.0,1.0)), random.randint(0, config.ROCK_MAX_SPEED))
         self.rocks.append(r)
Exemplo n.º 43
0
	def __init__(self, w=800, h=600):
		if platform.system() == 'Windows':
		    os.environ['SDL_VIDEODRIVER'] = 'windib'
		os.environ['SDL_VIDEO_WINDOW_POS'] = "100,100"
		pygame.init()
		self.clock = pygame.time.Clock()
		self.window = pygame.display.set_mode((w, h), pygame.DOUBLEBUF|pygame.HWSURFACE)
		pygame.display.set_caption('Brick Break!')

		self.ship = Ship(w/2, h-14)
		self.ball = Ball((self.ship.x, self.ship.y-self.ship.height/2), (400., 0.))
		self.backgroundColor = pygame.Color(255,255,255)

		pygame.mouse.set_visible(False)
		pygame.mouse.set_pos(100+w/2, 100+h/2)

		self.blocks = BlockArray(16,11) 
		self.shipx = pygame.mouse.get_pos()[0]
		self.goLeft = self.goRight = False
Exemplo n.º 44
0
    def generateShips(self):
        num = 0
        while num < 4:
            self.find = False
            orientation = self.determineOrientation()
            size = num + 2
            x = randint(1, 9)
            y = randint(1, 9)
            ship = Ship(size, orientation, x, y)
            ship.createShip()
            coord = ship.getCoordinates()

            for point in coord:
                for occupied in self.occupied:
                    if point == occupied:
                        self.find = True
                        break

                if self.find:
                    break

            if self.find:
                continue

            if size == 2:
                self.ship_2 = ship.getCoordinates()

            elif size == 3:
                self.ship_3 = ship.getCoordinates()

            elif size == 4:
                self.ship_4 = ship.getCoordinates()

            else:
                self.ship_5 = ship.getCoordinates()

            num += 1
            for point in coord:
                self.occupied.append(point)
Exemplo n.º 45
0
    def __init__(self):
        window = Tk()
        window.title("Lunar Lander")

        self.canvas = Canvas(window, bg='black', width=500, height=400)
        self.canvas.pack()

        landscape = Landscape(self.canvas)
        self.ship = Ship(self.canvas)

        window.bind("<Left>", self.left)
        window.bind("<Right>", self.right)
        window.bind("<Up>", self.thrust)

        window.bind("<Button-1>", self.p)
        window.bind("<B1-Motion>", self.m)

        self.isStopped = False
        self.sleepTime = 100
        self.rad = 0
        self.updateLoop()

        window.mainloop()
Exemplo n.º 46
0
def main():
    ship_list_file = open("ship_list.txt", "r")
    # ship_list_file =  ["Algos"]
    importfile = open("anki_import.txt", "a")
    eve_uni = Eveuni_parser()

    for ship_name in ship_list_file:
        ship_name = ship_name.replace(" ", "_")
        ship_name = ship_name.strip()
        ship = Ship(ship_name)
        eve_uni.fetch_ship_info(ship.name)
        ship.bonuses = eve_uni.get_bonuses()
        ship.faction = eve_uni.get_faction()
        ship.ecm = eve_uni.get_ecm()
        ship.hull = eve_uni.get_hull()
        ships.append(ship)

        importfile.write(ship.print_ship());
        importfile.flush()
        print ship_name
        time.sleep(0.5)
Exemplo n.º 47
0
import sys
import pygame
from Ship import Ship
from Settings import SIZE, FPS


run = True
pygame.init()
pygame.display.set_mode(SIZE.bottomright)
screen = pygame.display.get_surface()

ship = Ship((SIZE.w / 2, SIZE.h / 2))
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                sys.exit()
        ship.events(event)
    dt = clock.tick(FPS)
    ship.update()
    screen.fill((0, 0, 0))
    ship.render(screen)
    pygame.display.flip()
Exemplo n.º 48
0
	def __init__(self):
		self.ship = Ship(1)
		self.ship.addPlugin(0,StandardGun())
		self.enemy = Ship()
		self.enemy.addPlugin(0,StandardGun())
Exemplo n.º 49
0
# camera = {'location':(320, 240), 'bounds':camera_bounds}
camera = Camera(camera_start_location, camera_bounds)

#we legit now son
pygame.display.set_caption("VV Pilot")

icon = pygame.Surface((32, 32))
icon.fill(WHITE)
pygame.gfxdraw.polygon(icon, ((3, 29), (29, 29), (16, 3)), BLACK)
pygame.gfxdraw.polygon(icon, ((4, 28), (28, 28), (16, 3)), BLACK)
pygame.gfxdraw.aapolygon(icon, ((2, 30), (30, 30), (15, 2)), BLACK)
pygame.display.set_icon(icon)

display = pygame.display.set_mode(camera_bounds)

player_ship = Ship((320, 240), (15, 15), SHOOT_DELAY, SPEED, VELOCITY_CAP, ANGULAR_VELOCITY, respawn_func)
DEATH_TIME = 120

clock = pygame.time.Clock()

bulletList = []

wall_list = []

debris = []
        

for i in range(0, 100):
    x = random.randint(player_ship.location[0], 3200)
    y = random.randint(player_ship.location[1], 1800)
    w = random.randint(100, 200)
Exemplo n.º 50
0
from Engine import Engine
from FuelTank import FuelTank
from Controller import Controller
from Ship import Ship
from Stats import Stats

import pygame
from pygame.locals import *

main_surface = pygame.display.set_mode(RESOLUTION)

test_fuel_tank_1 = FuelTank('small_tank')
test_fuel_tank_2 = FuelTank('medium_tank')
test_engine = Engine('basic_engine')
test_ship = Ship([test_fuel_tank_1,
                  test_fuel_tank_1,
                  test_fuel_tank_2,
                  test_engine])

keyboard = Controller()
stats = Stats(test_ship)

clock = pygame.time.Clock()
running = True
while running:

    clock.tick(MAX_FPS)
    keyboard.update()

    main_surface.fill([255, 255, 255])

    if keyboard.exit:
Exemplo n.º 51
0
class TestShip(TestCase):

  def setUp(self):
    self.ship = Ship()

  def tearDown(self):
    if isinstance(self.ship, NodePath):
      self.ship.visualNode.removeNode()

  def testInit(self):
    self.failUnless(self.ship)
    self.failUnlessEqual(self.ship.name, Ship.NAME_DEFAULT)
    self.failUnless(self.ship.collisionSphere)

  def testGetVisualNode(self):
    node = self.ship.getVisualNode()
    self.failUnless(node)

  def testCreateVisualNode(self):
    self.ship.createVisualNode()
    node = self.ship.getVisualNode()
    self.failUnless( isinstance(node, NodePath) )

  def testIsVisible(self):
    self.ship.createVisualNode()
    self.failUnless( self.ship.isVisible() )

  def testSetCollisionHandler(self):
    f = lambda x, y: 0
    self.ship.setCollisionHandler(f)
    self.failUnlessEqual(self.ship.collisionHandler, f)
    
  def getCollisions(self):
    self.failifEqual(self.ship.collisions, None)
    
  def testSetPos(self):
    pos = (4, 7)
    self.ship.setPos(pos)
    self.failUnlessEqual( self.ship.getPos(), pos )
    
  def testGetPos(self):
    pos = self.ship.getPos()
    self.failUnless( isinstance(pos, tuple) )

  def testGetVel(self):
    vel = self.ship.getVel()
    self.failUnless( isinstance(vel, tuple) )

  def testGetAcc(self):
    acc = self.ship.getAcc()
    self.failUnless( isinstance(acc, float) )

  def testGetHeading(self):
    heading = self.ship.getHeading()
    self.failUnless( isinstance(heading, float) )

  def testShoot(self):
    bullets = self.ship.bullets
    before = len(bullets)
    # In the beginning there are no bullets
    self.failIf(before != 0)
    self.ship.shoot()
    after = len(bullets)
    self.failUnless(before < after)
    self.failUnless(after == 1)
    self.failUnless( bullets[0]['vel'] )
    self.failUnless( bullets[0]['visual'] )
    self.failUnless( bullets[0]['isAlive'] )

  def testBulletHit(self):
    healthBefore = self.ship.health
    self.ship.bulletHit()
    healthAfter = self.ship.health
    self.failUnless(healthBefore > healthAfter)

    # Test that the ship will be destroyed if it's hit enough times
    while(True):
      # Hit with bullets until health is 0
      self.ship.bulletHit()
      if self.ship.health <= 0:
        break
    self.failIf(self.ship.isAlive)

  def testDestroyBullet(self):
    self.ship.shoot()
    bullet = self.ship.bullets[0]
    visual = bullet['visual']
    physical = bullet['physical']
    self.failUnless( len(self.ship.bullets) == 1 )
    self.failUnless(visual)
    self.failUnless(physical)
    self.ship.destroyBullet(bullet)
    self.failUnless( len(self.ship.bullets) == 0 )

  def testDestroy(self):
    before = self.ship.isAlive
    self.ship.destroy()
    after = self.ship.isAlive
    self.failUnless(before == True)
    self.failUnless(after == False)

  def testThrustOn(self):
    before = self.ship.getAcc()
    self.ship.thrustOn()
    after = self.ship.getAcc()
    self.failUnless(before != after)

  def testThrustOff(self):
    self.ship.thrustOn()
    before = self.ship.getAcc()
    self.ship.thrustOff()
    after = self.ship.getAcc()
    self.failUnless(before != after)

  def testRotateLeftOn(self):
    before = self.ship.isRotatingLeft()
    self.ship.rotateLeftOn()
    after = self.ship.isRotatingLeft()
    self.failIf(before == after)
    self.failIf(before == True)
    self.failIf(after == False)

  def testRotateLeftOff(self):
    self.ship.rotateLeftOn()
    before = self.ship.isRotatingLeft()
    self.ship.rotateLeftOff()
    after = self.ship.isRotatingLeft()    
    self.failIf(before == after)
    self.failIf(before == False)
    self.failIf(after == True)

  def testIsRotatingLeft(self):
    isRotatingLeft = self.ship.isRotatingLeft()
    self.failUnless( isinstance(isRotatingLeft, bool) )

  def testRotateRightOn(self):
    before = self.ship.isRotatingRight()
    self.ship.rotateRightOn()
    after = self.ship.isRotatingRight()
    self.failIf(before == after)
    self.failIf(before == True)
    self.failIf(after == False)

  def testRotateRightOff(self):
    self.ship.rotateRightOn()
    before = self.ship.isRotatingRight()
    self.ship.rotateRightOff()
    after = self.ship.isRotatingRight()    
    self.failIf(before == after)
    self.failIf(before == False)
    self.failIf(after == True)

  def testIsRotatingRight(self):
    isRotatingRight = self.ship.isRotatingRight()
    self.failUnless( isinstance(isRotatingRight, bool) )

  def testUpdate(self):
    # Test thrustOn and visual node position changing
    velBefore = self.ship.getVel()
    posBefore = self.ship.getPos()
    visualNodePosBefore = self.ship.getVisualNode().getPos()
    self.ship.thrustOn()
    self.ship.update(1.0) # 1.0 seconds has passed.
    velAfter = self.ship.getVel()
    posAfter = self.ship.getPos()
    visualNodePosAfter = self.ship.getVisualNode().getPos()
    self.failUnless(velBefore < velAfter)
    self.failUnless(posBefore != posAfter)
    self.failUnless(visualNodePosAfter != visualNodePosBefore)

    # Test rotating left
    headingBefore = self.ship.heading
    visualNodeHeadingBefore = self.ship.getVisualNode().getH()
    self.ship.rotateLeftOn()
    self.ship.update(1.0)
    headingAfter = self.ship.heading
    visualNodeHeadingAfter = self.ship.getVisualNode().getH()
    self.failUnless(headingBefore != headingAfter)
    self.failUnless(visualNodeHeadingBefore != visualNodeHeadingAfter)

  def testLimitVelocity(self):
    vel = (1,1)
    self.ship.setVel(vel)
    self.ship.limitVelocity()
    newVel = self.ship.getVel()
    newVelScalar = tupleLength(newVel)
    self.failIf(newVelScalar > Ship.SPEED_MAX)
    self.failIf(newVelScalar < 0)

    vel = (Ship.SPEED_MAX, Ship.SPEED_MAX)
    self.ship.setVel(vel)
    self.ship.limitVelocity()
    newVel = self.ship.getVel()
    newVelScalar = tupleLength(newVel)
    self.failUnless( abs(newVelScalar - Ship.SPEED_MAX) < 0.01)

    
  def testAddCollision(self):
    self.ship.addCollision( point3ToTuple( Point3(1, 2, 0) ) )
    self.failIfEqual( self.ship.getCollisions(), [] )
    
  def testApplyForce(self):
    self.ship.applyForce( (1, 5) )
    self.failIfEqual( self.ship.forces, [] )

  # ####################################################################
  # Feature tests
  #
  # These tests don't necessarily test any single method, but rather
  # features. They are slightly more complex in that the focus of a
  # feature test is a higher level concept, such as gravity, collisions
  # or forces.
  # ####################################################################
  def testForce(self):
    oldPos = self.ship.getPos()
    self.ship.update(.01)
    newPos = self.ship.getPos()
    self.failUnlessEqual( oldPos, newPos )
    
    self.ship.applyForce( (4, 6) )
    oldPos = self.ship.getPos()
    self.ship.update(.01)
    newPos = self.ship.getPos()
    self.failIfEqual( oldPos, newPos )
Exemplo n.º 52
0
class Fighter(DirectObject):
    def __init__(self):
        
        base.disableMouse()

        # Carga el fondo del juego
        self.bg = loader.loadModel("models/plane")
        self.bg.reparentTo(camera)
        self.bg.setPos(0, 200, 0)
        self.bg.setScale(300, 0, 146)
        self.bg.setTexture(loader.loadTexture("models/Backgrounds/farback.png"), 1)
        
        # Inicializa el gestor de teclado y los objetos del juego
        self.inputManager = InputManager()

        # Inicializa el menu del juego
        self.inicializarMenu()

        self.marcador = None
        self.barraEnergia = None
        self.marcadorFinalNP = None
        self.entrada = None
        self.rankingNP = None

        self.mostrarMenuJuego()
        self.accept("m", self.cambiarMenuJuego)
        self.accept("q", self.salir)

    # Inicializa el menu
    def inicializarMenu(self):
        self.menuGraphics = loader.loadModel("models/MenuGraphics")
        self.fonts = {"silver" : loader.loadFont("fonts/LuconSilver"),
                      "blue" : loader.loadFont("fonts/LuconBlue"),
                      "orange" : loader.loadFont("fonts/LuconOrange")}
        self.menu = Menu(self.menuGraphics, self.fonts, self.inputManager)
        self.menu.initMenu([0, None, 
            ["Nueva Partida", "Salir"],
            [[self.nuevaPartida], [self.salir]],
            [[None], [None]]])

    # Comienza una partida
    def nuevaPartida(self):
        
        if (not self.marcadorFinalNP is None):
            self.marcadorFinalNP.detachNode()
            self.marcadorFinalNP.remove()

        if (not self.rankingNP is None):
            self.rankingNP.detachNode()
            self.rankingNP.remove()

        self.ship = Ship(self.inputManager)
        self.mostrarInfo()

        taskMgr.add(self.actualizarInfo, "Actualizar Puntuacion")

    # Inicializa y muestra el marcador del jugador
    def mostrarInfo(self):

        self.marcador = TextNode("Marcador")
        self.marcador.setText("Puntos: " + str(self.ship.puntos))
        self.marcador.setCardColor(0, 0, 0, 1)
        self.marcador.setCardDecal(True)
        self.marcador.setCardAsMargin(0.4, 0.4, 0.4, 0.4)
        self.marcadorNP = aspect2d.attachNewNode(self.marcador)
        self.marcadorNP.reparentTo(base.a2dTopLeft)
        self.marcadorNP.setPos(0.02, 0, -0.05)
        self.marcadorNP.setScale(0.07)

        self.barraEnergia = DirectWaitBar(text = "Energia", value = 5, 
            range = 5, scale = 0.3, pos = (0, 0, 0.95))

    # Actualiza la puntuacion del jugador en pantalla
    def actualizarInfo(self, tarea):
        self.marcador.setText("Puntos: " + str(self.ship.puntos))
        self.barraEnergia["value"] = self.ship.vida
        self.barraEnergia.setValue()

        # Termina la partida
        if (self.ship.terminarPartida):
            self.terminarPartida()
            return tarea.done

        return tarea.cont

    # Termina partida liberando recursos para poder empezar una nueva
    # sin reiniciar el juego
    def terminarPartida(self):
        # Solicita al usuario un nombre para la tabla de puntuaciones
        self.entrada = DirectEntry(width = 15, numLines = 1, scale = 0.07,
            cursorKeys = 1, frameSize = (0, 15, 0, 1), command = self.almacenarPuntuacion,
            pos = (-0.3, 0, 0.1), focus = True, text_pos = (0.2, 0.2))
        self.puntos = self.ship.puntos

        self.ship.ship.detachNode()
        self.ship.ship.remove()
        taskMgr.remove("Mover Nave")
        taskMgr.remove("Generar Enemigos")
        taskMgr.remove("Comprobar Impactos")
        taskMgr.remove("Actualizar Puntuacion")
        taskMgr.remove("Explosionar*")

        self.mostrarFinPartida()

        # Libera los recursos de la partida que ha terminado
        self.ship.eliminarObjetos()
        del self.ship
        del self.menuGraphics
        del self.menu
        self.marcadorNP.detachNode()
        self.marcadorNP.remove()
        self.barraEnergia.destroy()
        del self.marcador
        del self.barraEnergia

        #self.inicializarMenu()

    # Almacena la puntuacion del jugador
    def almacenarPuntuacion(self, valor):

        self.crearBDD()

        db = sqlite3.connect("datos.db")
        cursor = db.cursor()
        parametros = (valor, self.puntos)
        cursor.execute("insert into puntuaciones values (?, ?)", parametros)
        db.commit()
        cursor.close()

        self.entrada.destroy()

        self.mostrarTopPuntuacion()

        self.inicializarMenu()

    # Crea la Base de Datos si no existe ya
    def crearBDD(self):
        db = sqlite3.connect("datos.db")
        cursor = db.cursor()
        args = ("puntuaciones",)
        cursor.execute("select name from sqlite_master where name = ?", args)
        if len(cursor.fetchall()) == 0:
            cursor.execute("create table puntuaciones (nombre text, puntuacion numeric)")
            db.commit()
        cursor.close()

    # Muestra las 10 mejores puntuaciones
    def mostrarTopPuntuacion(self):
        # Extrae las 10 mejores puntuaciones de la base de datos
        db = sqlite3.connect("datos.db")
        cursor = db.cursor()
        cursor.execute("select nombre, puntuacion from puntuaciones order by puntuacion desc limit 10")
        puntuaciones = cursor.fetchall()
        cursor.close()
        resultado = "-- MEJORES PUNTUACIONES --\n-Jugador-  -Puntuacion-\n\n"
        for nombre, puntuacion in puntuaciones:
            resultado += nombre + " " + str(puntuacion) + "\n"

        # Muestra las 10 mejores puntuaciones
        self.ranking = TextNode("Ranking")
        self.ranking.setText(resultado)
        self.ranking.setCardColor(0, 0, 0, 1)
        self.ranking.setCardDecal(True)
        self.ranking.setCardAsMargin(0.4, 0.4, 0.4, 0.4)
        self.rankingNP = aspect2d.attachNewNode(self.ranking)
        self.rankingNP.reparentTo(base.a2dTopLeft)
        self.rankingNP.setPos(1, 0, -1)
        self.rankingNP.setScale(0.07)

    # Muestra el mensaje de fin de partida
    def mostrarFinPartida(self):
        self.marcadorFinal = TextNode("Marcador Final")
        self.marcadorFinal.setText("Game Over!\nPuntuacion: " + str(self.ship.puntos) +"\n\n" +
            "Escribe tu nombre:")
        self.marcadorFinal.setCardColor(0, 0, 0, 1)
        self.marcadorFinal.setCardDecal(True)
        self.marcadorFinal.setCardAsMargin(0.4, 0.4, 0.4, 0.4)
        self.marcadorFinalNP = aspect2d.attachNewNode(self.marcadorFinal)
        self.marcadorFinalNP.setPos(-0.3, 0, 0.5)
        self.marcadorFinalNP.setScale(0.07)

    # Muestra un menu con las opciones durante el juego
    def mostrarMenuJuego(self):
        self.textoMenu = {}
        self.textoMenu["titulo"] = OnscreenText(text = "", pos = (0, 0.92), scale = 0.08, 
            fg = (1, 1, 1, 1), bg = (0, 0, 1, 0.7))
        self.textoMenu["descripcion"] = OnscreenText(text = "", pos = (0, 0.84), scale = 0.05,
            fg = (1, 1, 0, 1), bg = (0, 0, 0, 0.5))
        self.textoMenu["opciones"] = OnscreenText(text = "", pos = (-1.3, 0), scale = 0.05,
            fg = (1, 1, 1, 1), bg = (1, 0.3, 0, 0.6), align=TextNode.ALeft, wordwrap = 15)

        self.textoMenu["opciones"].setText("** OPCIONES **\n" + 
            "m = ocultar menu\n" +
            "q = salir")

        # Inicialmente el menu se deja oculto
        for linea in self.textoMenu.values():
            linea.hide()

    # Muestra / Oculta el menu de juego
    def cambiarMenuJuego(self):
        for linea in self.textoMenu.values():
            if linea.isHidden():
                linea.show()
            else:
                linea.hide()

    # Sale del juego
    def salir(self):
        print("Saliendo . . .")
        sys.exit()
Exemplo n.º 53
0
pygame.display.set_caption("Space Clear")
print "Space Clear Loading..."

screen = pygame.display.set_mode((480,320))
clock=pygame.time.Clock()

pygame.display.set_icon(pygame.image.load("gpx/ship.png").convert())

stage=pygame.sprite.Group()
stagebg=pygame.sprite.Group()
bullets=pygame.sprite.Group()
enems=pygame.sprite.Group()
enemBuls=pygame.sprite.Group()
coins=pygame.sprite.Group()
bg=MultiStar(stagebg)
nave=Ship(20,50,stage,bullets)
level=1
last=False
sld=[] #SpaceClear Levels Data
stageMenu=GameBar(screen,nave,enems,level)

pygame.mouse.set_visible(False)

def loadAllLevelsData(ruta):
	global sld
	sld=[]
	a=open(ruta)
	c=0
	for line in a:
		if line[0:-1]=="L"+str(c+1)+":":
			c+=1
Exemplo n.º 54
0
from Ship import Ship, output, listToFloat

test = Ship()#these parenthesis necessary, they allow the class
                #to instantiate

print("Data is expressed as Location (x,y), Velocity <x,y>, Angle")
input("Press [ENTER] to continue")

loc = input("Set Location (x y): ").split()
listToFloat(loc)
test.setLocation(loc)

vel = input("Set Velocity (x y): ").split()
listToFloat(vel)
test.setVelocity(vel)

ang = int(input("Set Angle (0 to 359): "))
test.setAngle(ang)

output(test)
#####################################################################
while True:
    ang = int(input("Enter degress to turn (+left): "))
    if ang > 0:
        for i in range(ang):
            test.turnLeft()
    elif ang < 0:
        for i in range(abs(ang)):
            test.turnRight()
    test.updateLocation()
    output(test)
Exemplo n.º 55
0
 def setUp(self):
   self.ship = Ship()
Exemplo n.º 56
0
class BrickBreakGame:
	def __init__(self, w=800, h=600):
		if platform.system() == 'Windows':
		    os.environ['SDL_VIDEODRIVER'] = 'windib'
		os.environ['SDL_VIDEO_WINDOW_POS'] = "100,100"
		pygame.init()
		self.clock = pygame.time.Clock()
		self.window = pygame.display.set_mode((w, h), pygame.DOUBLEBUF|pygame.HWSURFACE)
		pygame.display.set_caption('Brick Break!')

		self.ship = Ship(w/2, h-14)
		self.ball = Ball((self.ship.x, self.ship.y-self.ship.height/2), (400., 0.))
		self.backgroundColor = pygame.Color(255,255,255)

		pygame.mouse.set_visible(False)
		pygame.mouse.set_pos(100+w/2, 100+h/2)

		self.blocks = BlockArray(16,11) 
		self.shipx = pygame.mouse.get_pos()[0]
		self.goLeft = self.goRight = False


	def run(self):
		while True:
			self.mainLoop()

	def mainLoop(self):
		#EVENTS
		for event in pygame.event.get():
			if event.type == MOUSEMOTION:
				self.shipx = event.pos[0]
			elif event.type == KEYDOWN:
				if event.key == K_LEFT:
					self.goLeft = True
				elif event.key == K_RIGHT:
					self.goRight = True
				elif event.key == K_ESCAPE:
					pygame.event.post(pygame.event.Event(QUIT))
			elif event.type == KEYUP:
				if event.key == K_LEFT:
					self.goLeft = False
				elif event.key == K_RIGHT:
					self.goRight = False
			elif event.type == QUIT:
				pygame.quit()
				sys.exit(0)

		if self.goLeft:
			self.shipx -= self.clock.get_time()*2/3
		elif self.goRight:
			self.shipx += self.clock.get_time()*2/3

		#LOGIC
		self.ball.update(self.clock.get_time()/1000., self.window)
		self.ship.update(self.shipx)
		self.blocks.update(self.ball)
		self.ship.checkBallCollision(self.ball)

		if self.ball.y > self.window.get_height():
			pygame.event.post(pygame.event.Event(QUIT))

		#DRAW
		self.window.fill(self.backgroundColor)
		self.blocks.draw(self.window)
		self.ship.draw(self.window)
		self.ball.draw(self.window)

		pygame.display.update()
		self.clock.tick(60)
Exemplo n.º 57
0
class ControlPanel(object):
    def __init__(self, main_window_width=800, main_window_height=600, main_white_space=50, side_window_width=350,
                 side_window_height=650, side_white_space=50, font=None, small_font=None):
        self.big_font_size = 24
        self.small_font_size = 16
        self.main_window = None
        self.main_width = main_window_width
        self.main_height = main_window_height
        self.console_height = 120
        self.side_window = None
        self.font = font
        self.small_font = small_font

        # keeps buttons from being pressed when they aren't supposed to
        self.window_lock = False

        # some events consants
        self.intro_event_file = os.path.join(settings.main_path, 'data', 'intro.eve')
        self.intro_event_id = 'INTRO_1'
        self.station = None

        self.window_dict = {'console': False,
                            'Messages': True,
                            'email': False,
                            'Ship': True,
                            'System': True,
                            'planet': False,
                            'Battle': False,
                            'Warp': True,
                            'Debug': True,
                            'Station': True}

        self.window_list = {}
        self.sidebar_list = {}

        for window in self.window_dict:
            self.window_list[window] = Window((main_white_space, main_white_space),
                                              (main_window_width, main_window_height-self.console_height),
                                              name=window)
            self.sidebar_list[window] = Window((main_white_space + main_window_width + side_white_space,
                                                side_white_space),
                                               (side_window_width, side_window_height),
                                               name=window,
                                               border_color=Color.d_gray)

        # console
        self.the_big_board = Box(pygame.Rect(0, 0, main_window_width, main_window_height-self.console_height),
                                 box_color=None, border_color=None, highlight_color=None, active_color=None)
        self.board_bottom = Box(pygame.Rect(main_white_space, main_white_space+main_window_height-self.console_height,
                                            main_window_width, self.console_height), box_color=Color.d_gray,
                                border_color=Color.gray, highlight_color=Color.gray, active_color=Color.gray,
                                border=3, name='Console-back')
        self.console = TextBoxList(pygame.Rect(main_white_space+10, main_white_space+main_window_height -
                                               self.console_height+10, main_window_width, self.console_height),
                                   name='Console', text_color=Color.white, text_outline=True, font=self.small_font,
                                   list_size=5, line_size=20)

        self.event = Event(panel=self, picture=self.the_big_board, text=self.console)

        self.window_list['console'].sprites.append(self.the_big_board)
        # self.window_list['console'].sprites.append(self.board_bottom)
        # self.window_list['console'].sprites.append(self.console)
        # main navigation buttons
        self.nav_button = {}
        y_offset = 0
        # self.big_font_size+4)/2*len(window)
        for window, visible in self.window_dict.iteritems():
            if visible:
                self.nav_button[window] = TextBox(pygame.Rect(20, 50+y_offset, 200, 45),
                                                  Color.d_gray, border_color=None, highlight_color=Color.white,
                                                  active_color=None, message=window, text_color=Color.white,
                                                  text_outline=True, font=self.font)
                y_offset += 55

        for button in self.nav_button:
            self.sidebar_list['console'].components.append(self.nav_button[button])

        self.back_to_console = TextBox(pygame.Rect(10, 10, 50, 30), Color.d_gray, border_color=None,
                                       highlight_color=Color.blue, active_color=None, message='< <',
                                       text_color=Color.white, font=self.font)

        # email  client  construct
        # self.email = EmailClient()
        self.sidebar_list['Messages'].components.append(self.back_to_console)

        # ship construct
        self.ship = Ship(size_x=40, size_y=40)
        self.window_list['Ship'].components.append(self.ship.main_screen)
        self.sidebar_list['Ship'].components.append(self.ship)
        self.sidebar_list['Ship'].components.append(self.back_to_console)

        # system construct
        self.system = None
        self.warp_to_system(x=6541, y=43322)

        self.screen_title = None
        self.switch_window('console')

        # battle screen
        self.space_battle = None
        '''
        self.space_battle = SpaceBattle(player_ship=self.ship, font=self.font, small_font=self.small_font,
                                        window_size=(main_window_width, main_window_height - self.console_height))
        self.window_list['Battle'].components.append(self.space_battle)
        self.sidebar_list['Battle'].components.append(self.space_battle.side_panel)
        '''

        # warp menu
        self.sidebar_list['Warp'].components.append(self.back_to_console)
        self.warp = Warp(self, font=self.font, small_font=self.small_font)
        self.sidebar_list['Warp'].components.append(self.warp)
        # self.window_list['Warp'].sprites.append(self.board_bottom)
        # self.window_list['Warp'].sprites.append(self.console)

        # debug
        self.debug_console = TextBoxList(pygame.Rect(10, main_window_height-300, main_window_width, 300),
                                         name='D_con', text_color=Color.white, text_outline=True, font=self.small_font,
                                         list_size=14, line_size=20)
        self.debug = Debug(self.debug_console, self, self.ship, self.font)

        self.window_list['Debug'].sprites.append(Box(pygame.Rect(5, main_window_height-310, main_window_width-10, 5),
                                                     box_color=Color.white, name='LINE'))
        self.window_list['Debug'].sprites.append(self.debug_console)
        self.sidebar_list['Debug'].components.append(self.debug)
        self.sidebar_list['Debug'].components.append(self.back_to_console)

    def load_event(self, event_file, event_name):
        self.event.read_event_file(event_file)
        self.event.run_event(event_name)

    def new_game(self, captain=None):
        self.ship.load(os.path.join(settings.main_path, 'data', 'start.shp'))
        if captain is not None:
            del self.ship.crew[:]
            self.ship.add_crew(captain)
        self.load_event(event_file=self.intro_event_file, event_name=self.intro_event_id)

    def warp_to_system(self, x, y):
        del self.window_list['System'].components[:]
        del self.sidebar_list['System'].components[:]
        self.station = None
        self.system = System(panel=self, font=self.font, small_font=self.small_font, x=x, y=y, add_station=True)
        self.window_list['System'].components.append(self.system.system_map)
        self.sidebar_list['System'].components.append(self.system)
        # self.system_map_index = len(self.window_list['System'].components)-1
        self.sidebar_list['System'].components.append(self.back_to_console)
        self.event.adhoc_event(picture=self.system.family_portrait(),
                               text='Warped to system: {0}'.format(self.system.name),
                               goto='console')

    def dock_with_station(self, station=None):
        if station:
            self.station = station
            self.event.adhoc_event(picture=self.station.image,
                                   text='You have docked with {0}'.format(self.station.name),
                                   goto='console')

    def start_space_battle(self, battle_params=None):
        del self.window_list["Battle"].components[:]
        del self.sidebar_list["Battle"].components[:]
        enemies = None
        if battle_params:
            if "enemies" in battle_params:
                enemies = battle_params["enemies"]
        self.space_battle = SpaceBattle(player_ship=self.ship, font=self.font, small_font=self.small_font,
                                        window_size=(self.main_width, self.main_height - self.console_height),
                                        enemies=enemies)

        self.window_list["Battle"].components.append(self.space_battle)
        self.sidebar_list["Battle"].components.append(self.space_battle.side_panel)
        self.switch_window(new_window="Battle")

    def switch_window(self, new_window):
        self.window_lock = True
        try:
            self.main_window = self.window_list[new_window]
            self.side_window = self.sidebar_list[new_window]
            sleep(0.1)
        except Exception as e:
            print e
            pass
        self.screen_title = self.main_window.name
        self.window_lock = False

    def always(self):
        self.main_window.always()

    def update(self, key, mouse):
        if not self.window_lock:
            self.main_window.update(key=key, mouse=mouse)
            self.side_window.update(key=key, mouse=mouse)

            if self.back_to_console.update(key=key, mouse=mouse, offset=self.side_window.position):
                self.switch_window('console')

            if self.screen_title == 'console':
                for button in self.nav_button:
                    if self.nav_button[button].update(key=key, mouse=mouse, offset=self.side_window.position):
                        if button == 'Station' and self.station is None:
                            self.event.adhoc_event(text='You are currently not docked at a station.')
                        else:
                            self.switch_window(button)

    def draw(self, screen):
        self.main_window.draw(screen)
        # always draw console probably
        self.board_bottom.draw(screen)
        self.console.draw(screen)
        self.side_window.draw(screen)
Exemplo n.º 58
0
    def __init__(self, main_window_width=800, main_window_height=600, main_white_space=50, side_window_width=350,
                 side_window_height=650, side_white_space=50, font=None, small_font=None):
        self.big_font_size = 24
        self.small_font_size = 16
        self.main_window = None
        self.main_width = main_window_width
        self.main_height = main_window_height
        self.console_height = 120
        self.side_window = None
        self.font = font
        self.small_font = small_font

        # keeps buttons from being pressed when they aren't supposed to
        self.window_lock = False

        # some events consants
        self.intro_event_file = os.path.join(settings.main_path, 'data', 'intro.eve')
        self.intro_event_id = 'INTRO_1'
        self.station = None

        self.window_dict = {'console': False,
                            'Messages': True,
                            'email': False,
                            'Ship': True,
                            'System': True,
                            'planet': False,
                            'Battle': False,
                            'Warp': True,
                            'Debug': True,
                            'Station': True}

        self.window_list = {}
        self.sidebar_list = {}

        for window in self.window_dict:
            self.window_list[window] = Window((main_white_space, main_white_space),
                                              (main_window_width, main_window_height-self.console_height),
                                              name=window)
            self.sidebar_list[window] = Window((main_white_space + main_window_width + side_white_space,
                                                side_white_space),
                                               (side_window_width, side_window_height),
                                               name=window,
                                               border_color=Color.d_gray)

        # console
        self.the_big_board = Box(pygame.Rect(0, 0, main_window_width, main_window_height-self.console_height),
                                 box_color=None, border_color=None, highlight_color=None, active_color=None)
        self.board_bottom = Box(pygame.Rect(main_white_space, main_white_space+main_window_height-self.console_height,
                                            main_window_width, self.console_height), box_color=Color.d_gray,
                                border_color=Color.gray, highlight_color=Color.gray, active_color=Color.gray,
                                border=3, name='Console-back')
        self.console = TextBoxList(pygame.Rect(main_white_space+10, main_white_space+main_window_height -
                                               self.console_height+10, main_window_width, self.console_height),
                                   name='Console', text_color=Color.white, text_outline=True, font=self.small_font,
                                   list_size=5, line_size=20)

        self.event = Event(panel=self, picture=self.the_big_board, text=self.console)

        self.window_list['console'].sprites.append(self.the_big_board)
        # self.window_list['console'].sprites.append(self.board_bottom)
        # self.window_list['console'].sprites.append(self.console)
        # main navigation buttons
        self.nav_button = {}
        y_offset = 0
        # self.big_font_size+4)/2*len(window)
        for window, visible in self.window_dict.iteritems():
            if visible:
                self.nav_button[window] = TextBox(pygame.Rect(20, 50+y_offset, 200, 45),
                                                  Color.d_gray, border_color=None, highlight_color=Color.white,
                                                  active_color=None, message=window, text_color=Color.white,
                                                  text_outline=True, font=self.font)
                y_offset += 55

        for button in self.nav_button:
            self.sidebar_list['console'].components.append(self.nav_button[button])

        self.back_to_console = TextBox(pygame.Rect(10, 10, 50, 30), Color.d_gray, border_color=None,
                                       highlight_color=Color.blue, active_color=None, message='< <',
                                       text_color=Color.white, font=self.font)

        # email  client  construct
        # self.email = EmailClient()
        self.sidebar_list['Messages'].components.append(self.back_to_console)

        # ship construct
        self.ship = Ship(size_x=40, size_y=40)
        self.window_list['Ship'].components.append(self.ship.main_screen)
        self.sidebar_list['Ship'].components.append(self.ship)
        self.sidebar_list['Ship'].components.append(self.back_to_console)

        # system construct
        self.system = None
        self.warp_to_system(x=6541, y=43322)

        self.screen_title = None
        self.switch_window('console')

        # battle screen
        self.space_battle = None
        '''
        self.space_battle = SpaceBattle(player_ship=self.ship, font=self.font, small_font=self.small_font,
                                        window_size=(main_window_width, main_window_height - self.console_height))
        self.window_list['Battle'].components.append(self.space_battle)
        self.sidebar_list['Battle'].components.append(self.space_battle.side_panel)
        '''

        # warp menu
        self.sidebar_list['Warp'].components.append(self.back_to_console)
        self.warp = Warp(self, font=self.font, small_font=self.small_font)
        self.sidebar_list['Warp'].components.append(self.warp)
        # self.window_list['Warp'].sprites.append(self.board_bottom)
        # self.window_list['Warp'].sprites.append(self.console)

        # debug
        self.debug_console = TextBoxList(pygame.Rect(10, main_window_height-300, main_window_width, 300),
                                         name='D_con', text_color=Color.white, text_outline=True, font=self.small_font,
                                         list_size=14, line_size=20)
        self.debug = Debug(self.debug_console, self, self.ship, self.font)

        self.window_list['Debug'].sprites.append(Box(pygame.Rect(5, main_window_height-310, main_window_width-10, 5),
                                                     box_color=Color.white, name='LINE'))
        self.window_list['Debug'].sprites.append(self.debug_console)
        self.sidebar_list['Debug'].components.append(self.debug)
        self.sidebar_list['Debug'].components.append(self.back_to_console)