Exemplo n.º 1
0
    def run_game():
        # Initialize game and create a screen object.
        pygame.init()
        settings = Settings()
        screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))
        pygame.display.set_caption("Domesday")

        # Make the play button.
        play_button = PlayButton(screen, "PLAY")

        # Create an instance to store game statistics and create scoreboard.
        stats = GameStats(settings)
        sb = Scoreboard(settings, screen, stats)

        # Make a spaceship, a group of bullets and a group of aliens.
        spaceship = SpaceShip(settings, screen)
        bullets = Group()
        aliens = Group()

        # Create the fleet of aliens.
        gf = GameFunctions()
        gf.create_fleet(settings, screen, spaceship, aliens)

        # Start the main loop for the game.
        while True:
            gf.check_events(settings, screen, stats, sb, play_button, spaceship, aliens, bullets)

            if stats.game_active:
                spaceship.update()
                # bullets.update() -> to-do old version of updating bullets.
                # Get rid of bullets that have disappeared.
                gf.update_bullets(settings, screen, stats, sb, spaceship, aliens, bullets)
                gf.update_aliens(settings, screen, stats, sb, spaceship, aliens, bullets)

            gf.update_screen(settings, screen, stats, sb, spaceship, aliens, bullets, play_button)
Exemplo n.º 2
0
    def __init__(self, space_game, **kwargs):
        kwargs['orientation'] = 0
        SpaceShip.__init__(self, space_game, **kwargs)
        self.score = 0
        self.gun_fire_interval = 0.1
        if self._keyboard == None and platform not in ("android", "ios"):
            self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
            self._keyboard.bind(on_key_down=self._on_key_down)
            self._keyboard.bind(on_key_up=self._on_key_up)

        self.gun = RepeaterGun(space_game=self.space_game)
        self.add_widget(self.gun)
        self.gun.center_x = self.center_x
        self.gun.center_y = self.center_y
        self.boom = load_sound('sounds/boom.ogg', volume=FX_VOLUME)

        # Add touch events layer
        self.player_speed = Vector(0, 0)
        self.bullet_rate = 0.0
        self.player_motion = None
        self.bullet_fire = None
        touch_layer = FloatLayout(pos_hint=(0, 0), size_hint=(1., 1.))
        touch_layer.bind(
            on_touch_down=self.on_touch_down,
            on_touch_move=self.on_touch_move,
            on_touch_up=self.on_touch_up,
        )
        self.add_widget(touch_layer)

        self._update_event = Clock.schedule_interval(self.update, FPS)
Exemplo n.º 3
0
 def _create_spaceship(self, spaceship_number, row_number):
     """Create an spaceship and place it in the row."""
     spaceship = SpaceShip(self)
     spaceship_width, spaceship_height = spaceship.rect.size
     spaceship.x = spaceship_width + 2 * spaceship_width * spaceship_number
     spaceship.rect.x = spaceship.x
     spaceship.rect.y = 3.5 * spaceship.rect.height + 2 * spaceship.rect.height * row_number
     self.spaceships.add(spaceship)
Exemplo n.º 4
0
 def prep_spaceships(self):
     """Show how many ships are left."""
     self.spaceships = Group()
     for spaceship_number in range(self.stats.spaceships_left):
         spaceship = SpaceShip(self.settings, self.screen)
         spaceship.rect.x = 10 + spaceship_number * spaceship.rect.width
         spaceship.rect.y = 10
         self.spaceships.add(spaceship)
Exemplo n.º 5
0
 def create_player(self):
     self.players.append(
         SpaceShip(x=10,
                   y=10,
                   w=self.player_img.get_width(),
                   h=self.player_img.get_height(),
                   v=10,
                   win=self.win,
                   img=self.player_img,
                   proj_img=self.proj_img))
Exemplo n.º 6
0
 def create_enemy(self):
     self.enemies.append(
         SpaceShip(x=randint(0, config.WIN_SIZE[0] - 50),
                   y=randint(0, config.WIN_SIZE[1] / 2),
                   w=self.enemy_img.get_width(),
                   h=self.enemy_img.get_height(),
                   v=randint(3, 10),
                   win=self.win,
                   img=self.enemy_img,
                   proj_img=self.proj_img))
Exemplo n.º 7
0
    def __init__ (self):

        self.screensize   = self.assembleImages()
        self.screen       = pygame.display.set_mode(self.screensize, 0, 32)
        self.volume       = 0.5
        self.player       = SpaceShip(self.screensize)
        HealthBar(self.player, self.screen, True)
        self.clock        = pygame.time.Clock()
        self.level        = 1
        self.boss         = None
        self.font         = pygame.font.Font("GearsOfPeace.ttf", 12)
        self.med_font     = pygame.font.Font("GearsOfPeace.ttf", 30)
        self.big_font     = pygame.font.Font("GearsOfPeace.ttf", 50)
        self.notify       = {"msg": None, "timer": [60*3, 0]}
        self.spawner      = {"max_enemies": 2,
                             "enemy_killed": 0,
                             "spawn_delay": (60 * 2.2),
                             "spawn_counter": 0,
                             "boss_out": False,}
        self.running = True
Exemplo n.º 8
0
    def _create_fleet(self):
        """Create the fleet of spaceships."""

        # Create an spaceship and find the number of spaceships in a row.
        # Spacing between each spaceship is equal to one spaceship width.
        spaceship = SpaceShip(self)
        spaceship_width, spaceship_height = spaceship.rect.size

        # Calculate the number of spaceships in a row
        # (2 * spaceship_width) creates margins on either side of a screen
        available_space_x = self.settings.screen_width - (2 * spaceship_width)
        number_spaceships_x = available_space_x // (2 * spaceship_width)
        
        # Determine the number of rows of spaceships that fit on the screen.
        rocket_height = self.rocket.rect.height
        available_space_y = (self.settings.screen_height -
                                (18 * spaceship_height) - rocket_height)
        number_rows = available_space_y // (2 * spaceship_height)
        
        # Create the full fleet of spaceships.
        for row_number in range(number_rows):
            for spaceship_number in range(number_spaceships_x):
                self._create_spaceship(spaceship_number, row_number)
Exemplo n.º 9
0
 def __init__(self, space_game, **kwargs):
     SpaceShip.__init__(self, space_game)
     Actor.__init__(self, **kwargs)
     self.min_y = dp(200)
     self.boom = load_sound("sounds/boom.ogg")
Exemplo n.º 10
0
def main():

    # Conncets to the server
    n = Network()
    print("Connected to the server.")
    bullets = []

    game = n.connect()

    # Configures the window
    win = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("SpaceShip Game")

    # Creates the spaceships at the beginning
    if n.id == 0:
        e_id = 1
        spaceship = SpaceShip(0, 0)
        enemy_spaceship = SpaceShip(1, 1)

    else:
        e_id = 0
        spaceship = SpaceShip(0, 1)
        enemy_spaceship = SpaceShip(1, 0)

    clock = pygame.time.Clock()

    # Starts the game loop
    run = True
    lost = False
    while run:
        clock.tick(500)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

        if game.finished():
            font = pygame.font.SysFont("timesnewroman", 100)
            if game.lost[n.id]:
                text = font.render("You lost!", 1, (255, 255, 255))

            else:
                text = font.render("You won!", 1, (255, 255, 255))

            x_text = WIDTH / 2 - text.get_width() / 2
            y_text = HEIGHT / 2 - text.get_height() / 2
            win.blit(text, (x_text, y_text))
            pygame.display.update()
            sleep(3)
            quit()

        elif game.isready():
            # Updates the spaceship
            if game.spaceships[n.id] is not None:
                spaceship = game.spaceships[n.id]
            if game.spaceships[e_id] is not None:
                enemy_spaceship.x = (WIDTH - game.spaceships[e_id].x -
                                     enemy_spaceship.width)
                enemy_spaceship.hp = game.spaceships[e_id].hp

            #Updates the bullets

            bullets = game.bullets
            for bullet in bullets:
                if bullet.id == n.id:
                    bullet.x = (1200 - bullet.x - 10)
                    bullet.y = (900 - bullet.y - 30)

            # Checks for moves
            spaceship.move()
            spaceship.shoot(bullets, n)

            # Draws things
            win.fill((0, 0, 0))
            spaceship.draw(win)
            for bullet in bullets:
                bullet.draw(win, n.id)
            enemy_spaceship.draw(win)

            #Displays Hp
            font = pygame.font.SysFont("timesnewroman", 50)
            text = font.render(f"HP: {spaceship.hp}", 1, (255, 255, 255))
            x_text = WIDTH * 0.02
            y_text = HEIGHT * 0.02
            win.blit(text, (x_text, y_text))
            pygame.display.update()

            # Sends the spaceship to the server
            game = n.communicate(spaceship)

            if spaceship.hp <= 0:
                game = n.communicate("Lost")

        else:
            font = pygame.font.SysFont("timesnewroman", 100)
            text = font.render("Waiting for player...", 1, (255, 255, 255))
            x_text = WIDTH / 2 - text.get_width() / 2
            y_text = HEIGHT / 2 - text.get_height() / 2
            win.blit(text, (x_text, y_text))
            pygame.display.update()

            game = n.communicate("Waiting")
Exemplo n.º 11
0
from constants import *
from spaceship import SpaceShip
from player import Player
from shot import Shot
from enemies import Enemies

WIDTH=800
HEIGHT=600
TITLE="Space shooter game"
ICON="spacecrafticon.png"

scroll_speed = 2

player = Player()

spacecraft = SpaceShip("spacecraft", (400,480))
spacecraft.set_speed(4)

enemies = Enemies((WIDTH,HEIGHT), "enemies.dat")

# List to track shots
shots = []
# shot last fired  timestamp - to ensure don't fire too many shots
shot_last_fired = 0
# time in seconds
time_between_shots = 0.5

scroll_position = 0

# spacecraft hit points
# positions relative to spacecraft centre which classes as a collide
Exemplo n.º 12
0
class Game:

    def __init__ (self):

        self.screensize   = self.assembleImages()
        self.screen       = pygame.display.set_mode(self.screensize, 0, 32)
        self.volume       = 0.5
        self.player       = SpaceShip(self.screensize)
        HealthBar(self.player, self.screen, True)
        self.clock        = pygame.time.Clock()
        self.level        = 1
        self.boss         = None
        self.font         = pygame.font.Font("GearsOfPeace.ttf", 12)
        self.med_font     = pygame.font.Font("GearsOfPeace.ttf", 30)
        self.big_font     = pygame.font.Font("GearsOfPeace.ttf", 50)
        self.notify       = {"msg": None, "timer": [60*3, 0]}
        self.spawner      = {"max_enemies": 2,
                             "enemy_killed": 0,
                             "spawn_delay": (60 * 2.2),
                             "spawn_counter": 0,
                             "boss_out": False,}
        self.running = True

    def openingScene (self):

        to_play = [sfx.AI_greeting, sfx.AI_mission]
        running = True
        for index, sound in enumerate(to_play):
            sound.play()
            while running:
                self.time_passed = self.clock.tick(60)/1000.0
                if not pygame.mixer.get_busy():
                    break
                for event in pygame.event.get():
                    if event.type == QUIT:
                        running = False
                        self.running = False
                        return
                    if event.type == KEYDOWN and event.key == K_ESCAPE:
                        running = False
                        sound.stop()
                        return
                
                self.manageSprite(Background.container)
                text = "SPACEBAR = FIRE ZE LASERS"
                surface = self.font.render(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]/2-120, 250))
                text = "M = FIRE A MISSILE"
                surface = self.font.render(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]/2-120, 280))
                text = "N = LAUNCH NUCLEAR WARHEAD"
                surface = self.font.render(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]/2-120, 310))
                text = "E = EMP (Scorpion Upgrade Line)"
                surface = self.font.render(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]/2-120, 340))
                text = "R = Repair (Collect Wrenches)"
                surface = self.font.render(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]/2-120, 370))
                text = "PRESS Esc TO SKIP INTRO"
                surface = self.med_font.render(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]/2-250, 450))
                self.manageSprite(self.player.container)
                pygame.display.flip()


    def assembleImages(self):

        image_path = os.path.join("backgrounds", choice(BACKGROUNDS))

        backgroundTL = ScrollingBackground(image_path)
        backgroundBL = ScrollingBackground(image_path)
        backgroundTL.rect.bottom = backgroundBL.rect.top
        width = backgroundTL.rect.width
        height = backgroundTL.rect.height

        global screenrect
        screenrect = Rect(0,0,backgroundTL.rect.width,backgroundTL.rect.height)
        display = pygame.display.Info()
        if display.current_h < 1000:
            height = display.current_h 
        return (width, height)

    def manageSprite (self, container):

        container.update(self.time_passed)
        container.draw(self.screen)

    def spawnEnemies (self):

        spwn = self.spawner
        if spwn["spawn_counter"] >= spwn["spawn_delay"]:
            if len(Enemy.container) < spwn["max_enemies"]:
                if self.level -3 in range(3):
                    enemy = choice([Drone, Warship])(self.screensize,
                                                     self.player,
                                                     self.level)
                elif self.level > 6:
                    enemy = choice([Drone, Warship, Bomber])(self.screensize, 
                                                             self.player, 
                                                             self.level)
                else:
                    enemy = Drone(self.screensize, self.player, self.level)
                if self.level > 10:
                    enemy.armor["T"] *= 2
                    enemy.armor["M"] *= 2
                HealthBar(enemy, self.screen)
                spwn["spawn_counter"] = 0
        else:
            if not spwn["boss_out"]:
                spwn["spawn_counter"] += 1

        if spwn["enemy_killed"] >= spwn["max_enemies"]+(
                5+self.level*3) and (spwn["boss_out"] == False):
            sfx.stab.play()
            self.boss = Boss(self.screensize, self.player, self.level)
            self.boss.rect.midbottom = (self.screensize[0]/2, 0)
            spwn["enemy_killed"] = 0
            spwn["boss_out"] = True
            spwn["max_enemies"] += 1
            HealthBar(self.boss, self.screen)

    def gameOver (self):

        # Do all the game over stuff here...
        self.running = False # True for debugging purposes - set to False to end game

    def playerDamage (self, enemy, projectiles):

        for proj in projectiles:
            proj.explode()
            if enemy.decreaseHealth(proj.damage) <= 0:
                if type(enemy).__name__ == "Guard":
                    self.boss.guards_out -= 1
                    self.player.exp += enemy.armor["M"]
                    enemy.die(sfx.muffled_explosion)
                    return
                self.spawner["enemy_killed"] += 1
                if type(enemy).__name__ == "Drone":
                    self.player.exp += enemy.armor["M"]+1
                else:
                    self.player.exp += enemy.armor["M"]
                chance = randint(1,13)
                if chance in [12, 13]:
                    new_powerup = Wrench()
                    new_powerup.rect.center = enemy.rect.center
                    PowerUpGlow(new_powerup)
                elif chance == 2:
                    new_powerup = Bullet()
                    new_powerup.rect.center = enemy.rect.center
                    PowerUpGlow(new_powerup)
                elif chance == 3:
                    new_powerup = MissileReload()
                    new_powerup.rect.center = enemy.rect.center
                    PowerUpGlow(new_powerup)
                elif chance == 4:
                    new_powerup = GunUpgrade()
                    new_powerup.rect.center = enemy.rect.center
                    PowerUpGlow(new_powerup)
                enemy.die(sfx.muffled_explosion)
                break

    def collisionCheck (self, collide):

        # Check if the player has shot an enemy (non boss)
        kpow = collide(Enemy.container, Fireball.container, False, True)
        if kpow:
            for enemy in kpow:
                self.playerDamage(enemy, kpow[enemy])
        # Check if an enemy has shot the player
        boom = collide(EnemyFireball.container, self.player.container, True, False)
        if boom:
            if self.player.decreaseHealth(1) <= 0:
                self.player.die()
        # Check if the player crashed into an enemy
        bang = collide(Enemy.container, self.player.container, False, False)
        if bang:
            for enemy in bang:
                e_armor = enemy.armor["T"]
                if type(enemy).__name__ == "Guard":
                    self.boss.guards_out -= 1
                enemy.die(sfx.muffled_explosion)
                if self.player.decreaseHealth(e_armor) <= 0:
                    self.player.die()
        # Check if the player has shot a boss
        bash = collide(Fireball.container, Boss.container, True, False)
        if bash:
            for projectile in bash:
                if not self.boss.invincible:
                    if self.boss.decreaseHealth(projectile.damage) <= 0:
                        self.spawner["boss_out"] = False
                        self.player.exp += self.boss.armor["M"]
                        self.level += 1
                        self.boss.die(sfx.muffled_explosion)
                        self.boss = None
                        self.player.ranks["remaining"] += 1
                        text = "New Upgrades! (Press ESC)"
                        self.notify["msg"] = self.med_font.render(text, True, (255,255,255))
                        break
                    projectile.explode()
        # Check if the player has grabbed a PowerUp
        ding = collide(PowerUp.container, self.player.container, True, False)
        if ding:
            for power in ding:
                power.effect(self.player)

    def showStats (self):

        fr = self.font.render
        if self.player.lives < 0:
            text = "Game Over..."
            surface = self.big_font.render(text, True, (255,255,255))
            self.screen.blit(surface, (200, self.screensize[1]/2-75))
            text = "EXP: %s -- LEVEL: %s" %(game.player.exp, game.level)
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (350, self.screensize[1]/2))
        else:
            text = "Level: %s" %(game.level)
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (10, 10))
            text = "EXP: %s" %(int(round(game.player.exp)))
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (10, 30))
            text = "Escape Pods: %s" %(game.player.lives)
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (10, 50))
            text = game.player.getHitPercentage()
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (10, 70))
            text = "Armor: %s/%s" % (game.player.armor["T"], game.player.armor["M"])
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (10, self.screensize[1]-50))
            text = "Missiles: %s" %(self.player.missiles)
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (self.screensize[0]-180, 10))
            text = "Repair Drones: %s" %(self.player.wrenches)
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (self.screensize[0]-180, 30))
            text = "Nukes: %s" %(game.player.nukes)
            surface = fr(text, True, (255,255,255))
            self.screen.blit(surface, (self.screensize[0]-180, 50))
            if self.player.missile:
                text = "NEXT MISSILE: 0:%s" %(round(game.player.missile_timer[1],1))
                surface = fr(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]-180, 70))
            if self.player.emp:
                text = "NEXT EMP: 0:%s" %(round(game.player.emp["timer"][1],1))
                surface = fr(text, True, (255,255,255))
                self.screen.blit(surface, (self.screensize[0]-180, 90))


    def displayNotifications (self):

        if not self.notify["msg"]: return
        if self.notify["timer"][1] >= self.notify["timer"][0]:
            self.notify["msg"] = None
            self.notify["timer"][1] = 0
        else:
            self.screen.blit(self.notify["msg"], (275, int(self.screensize[1]/3-50)))
            self.notify["timer"][1] += 1

    def eventCheck(self, event):

        if event.type == QUIT:
            self.running = False
        if event.type == KEYDOWN:
            if event.key == K_p or event.key == K_ESCAPE: # Pause the game and open the menu
                self.menu = MainMenu(self)
                self.menu.run()
            if event.key == K_SPACE:
                self.player.shooting = True
            if event.key == K_UP:
                self.player.moving.add("forward")
            if event.key == K_DOWN:
                self.player.moving.add("back")
            if event.key == K_RIGHT:
                self.player.moving.add("right")
            if event.key == K_LEFT:
                self.player.moving.add("left")
            if event.key == K_e:
                if self.player.emp:
                    self.player.triggerEmp(self.screen, Enemy.container, self.boss)
            if event.key == K_m:
                self.player.missile(Enemy.container, self.boss)
            if event.key == K_n:
                self.player.nuke(self.screen, Enemy.container, self.boss)
            if event.key == K_r:
                self.player.repair()
            if event.key == K_EQUALS:
                self.volume += 0.1
                if self.volume > 1:
                    self.volume = 1.0
                pygame.mixer.music.set_volume(self.volume)
            if event.key == K_MINUS:
                self.volume -= 0.1
                if self.volume < 0:
                    self.volume = 0.0
                pygame.mixer.music.set_volume(self.volume)
        if event.type == KEYUP:
            if event.key == K_SPACE:
                self.player.shooting = False
            if event.key == K_UP:
                self.player.moving.remove("forward")
            if event.key == K_DOWN:
                self.player.moving.remove("back")
            if event.key == K_RIGHT:
                self.player.moving.remove("right")
            if event.key == K_LEFT:
                self.player.moving.remove("left")

    def run (self):

        #self.notify["msg"] = self.med_font.render("Pew Pew Space", True, (255,255,255))
        self.openingScene()

        sfx.play_music()
        collide = pygame.sprite.groupcollide

        while self.running:
            self.time_passed = self.clock.tick(60)/1000.0
            pygame.display.set_caption("[FPS -- %s]" %(int(self.clock.get_fps())))
            for event in pygame.event.get():
                self.eventCheck(event)

            self.spawnEnemies()
            self.manageSprite(Background.container)           # Background
            self.showStats()                                  # Stats
            self.displayNotifications()                       # Notifications
            self.manageSprite(Passive.container)              # Passive sprites
            self.manageSprite(Animation.container)            # Animations
            self.manageSprite(Fireball.container)             # Player's bullets
            self.manageSprite(Missile.container)              # Player missiles
            self.manageSprite(Boss.container)                 # Boss
            self.manageSprite(EnemyFireball.container)        # Enemy's bullets
            self.manageSprite(Enemy.container)                # Enemies
            self.manageSprite(HealthBar.container)            # Healthbars
            self.manageSprite(PowerUp.container)              # PowerUps
            self.manageSprite(self.player.container)          # Player
            self.collisionCheck(collide)                      # Collisions
            pygame.display.flip()                             # Update dislplay
Exemplo n.º 13
0
def main():
    game = SpaceShip()
    game.setup()
    arcade.run()
Exemplo n.º 14
0
from turtle import Screen
from time import sleep
from spaceship import SpaceShip
from aliens import Invaders
from scoreboard import ScoreBoard

# setting up the game screen
game_screen = Screen()
game_screen.setup(width=600, height=650)
game_screen.bgcolor("black")
game_screen.title("Space Invaders")
game_screen.tracer(0)
game_screen.listen()

# setup and display each game component
space_ship = SpaceShip()

aliens = Invaders()
scores = ScoreBoard()
game_on = True
loops = 0


def end_game():
    """A function that ends the game abruptly"""

    global game_on
    game_on = False


# move the spaceship left and right on key presses
Exemplo n.º 15
0
class Game():
    def __init__(self,root,canvas,settings={},cursor_scroll=False):
        # tkinter properties that are passed down
        self.root = root
        self.canvas = canvas
        # 3d graphics engine
        self.engine = Engine(self.canvas,WIDTH,HEIGHT)
        self.stopped = False

        self.cursor_scroll = cursor_scroll

        ### BEGIN SETTINGS values ###
        self.settings = settings
        self.fps_speed_adjustment = 1

        # movement
        self.speed = 1
        self.rot_velocity = math.pi/180/5
        self.noclip = False
        ###  END SETTINGS values  ###

        self.objects = []

        # key bindings / checking
        self.keys_down = []
        self.key_mapping = {
            KEYS["W"]:           self.forward,
            KEYS["S"]:           self.backward,
            KEYS["A"]:           self.left,
            KEYS["D"]:           self.right,
            KEYS["SHIFT"]:       self.down,
            KEYS["SPACE"]:       self.up,
            KEYS["ESC"]:         self.stop,
            KEYS["R"]:           self.reset,
            KEYS["LEFT_ARROW"]:  self.rot_left,
            KEYS["RIGHT_ARROW"]: self.rot_right,
            KEYS["UP_ARROW"]:    self.rot_up,
            KEYS["DOWN_ARROW"]:  self.rot_down
        }

        # methods to be run once a key has stopped being pressed
        self.key_up_mapping = {
            KEYS["W"]:     self.kill_zvelocity,
            KEYS["S"]:     self.kill_zvelocity,
            KEYS["A"]:     self.kill_xvelocity,
            KEYS["D"]:     self.kill_xvelocity,
            KEYS["SHIFT"]: self.kill_yvelocity,
            KEYS["SPACE"]: self.kill_yvelocity,
            KEYS["T"]:     self.toggle_noclip
        }

        # rotation based on whether or not the mouse will be used
        # event bindings
        self.canvas.bind("<KeyPress>",self.keydown)
        self.canvas.bind("<KeyRelease>",self.keyup)
        if self.cursor_scroll:
            self.canvas.bind("<Motion>",self.rot)

        # camera init values
        self.xvelocity = 0
        self.zvelocity = 0
        self.yvelocity = 0

        # camera's offset from the spaceship's position
        self.xoffset = 10
        self.yoffset = 20
        self.zoffset = -10

        # space ship
        self.ship = SpaceShip(
            (0,0,0),
            self.speed,
            self.rot_velocity,
            self.engine,
            ObjectFile("objects/spaceship.obj",
                scale=0.25,
                pos=(10,0,20)
            )
        )
        self.objects.append(self.ship)

        # game stats
        self.fps = 0
        self.mousex = 0
        self.mousey = 0
        
        # init canvas
        self.canvas.pack()
        self.canvas.focus_set()

    def add_object(self,obj):
        obj.init(self.engine)
        self.objects.append(obj)

    def reset(self):
        self.engine.roty = 0
        self.engine.rotz = 0

    def get_adjusted_speed(self,speed):
        """Returns the speed adjusted to the frame rate, so if frames drop or spike, the in game speed remains the same."""
        # for whatever reason, I've found that the relationship between speed and fps
        # does not feel normal when it is linear, so I've played around and landed on this equation that feels natural
        return speed * math.sqrt(self.fps_speed_adjustment/self.fps)

    def toggle_noclip(self):
        self.noclip = not self.noclip
    def rot_up(self):
        if self.noclip:
            self.engine.roty += self.get_adjusted_speed(self.rot_velocity)
        else:
            self.ship.rot_up()
    def rot_down(self):
        if self.noclip:
            self.engine.roty -= self.get_adjusted_speed(self.rot_velocity)
        else:
            self.ship.rot_down()
    def rot_left(self):
        if self.noclip:
            self.engine.rotz -= self.get_adjusted_speed(self.rot_velocity)
        else:
            self.ship.rot_left()
    def rot_right(self):
        if self.noclip:
            self.engine.rotz += self.get_adjusted_speed(self.rot_velocity)
        else:
            self.ship.rot_right()
    def up(self):
        if self.noclip:
            self.yvelocity = self.get_adjusted_speed(self.speed)
        else:
            self.ship.up()

    def down(self):
        if self.noclip:
            self.yvelocity = -self.get_adjusted_speed(self.speed)
        else:
            self.ship.down()

    def stop(self):
        self.root.destroy()
        self.stopped = True
        sys.exit(0)

    def rot(self,event):
        if not self.intro:
            win32api.SetCursorPos((int(WIDTH/2),int(HEIGHT/2)))
        x,y = event.x, event.y
        self.mousex += x - WIDTH/2
        self.mousey += y - HEIGHT/2
        if self.noclip:
            self.engine.rotz = self.mousex*(math.pi*2/WIDTH) 
            self.engine.roty = -(self.mousey*(math.pi*2/HEIGHT))

    def forward(self):
        if self.noclip:
            self.zvelocity = self.get_adjusted_speed(self.speed)
        else:
            self.ship.forward()

    def backward(self):
        if self.noclip:
            self.zvelocity = -self.get_adjusted_speed(self.speed)
        else:
            self.ship.backward()

    def right(self):
        if self.noclip:
            self.xvelocity = self.get_adjusted_speed(self.speed)
        else:
            self.ship.right()

    def left(self):
        if self.noclip:
            self.xvelocity = -self.get_adjusted_speed(self.speed)
        else:
            self.ship.left()

    def kill_zvelocity(self):
        if self.noclip:
            self.zvelocity = 0
        else:
            self.ship.kill_zvelocity()

    def kill_xvelocity(self):
        if self.noclip:
            self.xvelocity = 0
        else:
            self.ship.kill_xvelocity()

    def kill_yvelocity(self):
        if self.noclip:
            self.yvelocity = 0
        else:
            self.ship.kill_yvelocity()

    def update_pos(self):
        """
        Update the camera's position based velocity, 
        as well as incorperating the direction to make xz axis movement feel natural.
        """
        if self.noclip:
            xv, zv, yv = self.xvelocity, self.zvelocity, self.yvelocity
            rotz = self.engine.rotz
            self.engine.x += zv*math.sin(rotz) + xv*math.cos(rotz)
            self.engine.z += zv*math.cos(rotz) - xv*math.sin(rotz)
            self.engine.y += yv
        else:
            self.ship.update_pos()

    def move_to_ship(self):
        if not self.noclip:
            x = self.ship.x
            y = self.ship.y
            z = self.ship.z

            # rotate camera around ship
            # find the mid point of the xy axis to rotate around
            midx = x + (self.ship.upperx-self.ship.lowerx)/2
            midy = y + (self.ship.uppery-self.ship.lowery)/2
            midz = z + (self.ship.upperz-self.ship.lowerz)*0.75 # slightly off the middle to make it look nicer


            x += self.xoffset
            y += self.yoffset
            z += self.zoffset# + -0.25*self.ship.zvelocity

            x -= midx
            y -= midy
            z -= midz

            y,z = self.engine.rot2d((y,z),-self.ship.roty)
            x,z = self.engine.rot2d((x,z),-self.ship.rotz)

            x += midx
            y += midy
            z += midz

            self.engine.x = x
            self.engine.y = y
            self.engine.z = z
            
            self.engine.rotz = self.ship.rotz
            self.engine.roty = self.ship.roty

    def run_key_events(self):
        for i in self.keys_down:
            if i in self.key_mapping:
                self.key_mapping[i]()

    def keydown(self,event):
        """Appends key codes that are being pressed into the object's list, if they are not already there."""
        if event.keycode not in self.keys_down:
            self.keys_down.append(event.keycode)

    def keyup(self,event):
        """Removes key codes that are being pressed when the keys are released."""
        k = event.keycode
        if k in self.keys_down:
            if k in self.key_up_mapping:
                self.key_up_mapping[k]()
            self.keys_down.remove(k)

    def update_objects(self):
        objects = []
        for o in self.objects:
            o.update()
            objects += o.get_polygons()
        self.engine.update_objects(objects)

    def render(self):
        # clear the current screen
        self.engine.clear()
        # re load all the objects
        self.engine.render_objects()

    def intro(self):
        self.intro = True
        self.ship.x = -10
        self.ship.z = 20
        self.ship.rotx = 20*math.pi/180
        self.ship.velocity_rot = False

        title = self.canvas.create_text(WIDTH/2,100,text="Sanic Speed",font=("Fixedsys",69),fill="white")
        f = font.Font(family="Verdana",slant=font.ITALIC,size=10)
        subtitle = self.canvas.create_text(WIDTH/2,170,text="A three dimensional space flight simulator, in pure python tkinter.",font=f,fill="white")
        escape_phrase = self.canvas.create_text(5,10,text="[ESC] to Quit",font=("Courier New",14),fill="white",anchor="w")
        global done
        done = False
        INSTRUCTIONS = """
        Welcome to Sanic Speed!
        Standard WASD controls are used for movement.
        [W] : forward, [S] : backwards
        [A] : left, [D] : right
        The arrow keys are used for rotation. The forward and backward keys are inverted to give an intuitive feel to the flight.
        If at any point you wish to fly around the world not bound to the plane, simply press [t] to toggle "noclip".
        To quit, press escape [ESC]. Thanks for playing!
        """
        def test():
            global done
            done = True
        def instructions():
            toplevel = tkinter.Toplevel()
            toplevel.title("Sanic Speed Instructions")
            label1 = tkinter.Label(toplevel, text=INSTRUCTIONS, font=("Helvetica",14), height=0, width=100)
            label1.pack()
        b = tkinter.Button(self.root, text="OK", command=test, width=30, height=2)
        b.pack()
        b.place(x=WIDTH/2 - 100,y=HEIGHT*0.75)
        b2 = tkinter.Button(self.root, text="INSTRUCTIONS", command=instructions, width=30, height=2)
        b2.pack()
        b2.place(x=WIDTH/2 - 100, y=HEIGHT*0.75 + 50)

        while not done:
            if 27 in self.keys_down:
                self.stop()
            self.ship.rotz_velocity = 0.1
            self.update_pos()
            self.update_objects()
            self.render()

            self.root.update()
        self.intro = False

        # clear away intro screen stuff for gameplay
        # reset ship
        self.ship.rotz_velocity = 0
        self.ship.rotz = 0
        self.ship.roty = 0
        self.ship.rotx = 0
        # clear away widgets
        b.destroy()
        b2.destroy()
        self.canvas.delete(title)
        self.canvas.delete(escape_phrase)
        self.canvas.delete(subtitle)
        self.root.config(cursor='none')

    def run(self):
        t = time.clock()
        if self.cursor_scroll:
            win32api.SetCursorPos((int(WIDTH/2),int(HEIGHT/2)))
        self.root.config(cursor='none')

        fps_text = self.canvas.create_text(10,10,text="",font="ansifixed",anchor="w",fill="white")
        #zs = self.canvas.create_text(10,20,text="",font="ansifixed",anchor="w",fill="white")
        #xs = self.canvas.create_text(10,30,text="",font="ansifixed",anchor="w",fill="white")
        #rzs = self.canvas.create_text(10,40,text="",font="ansifixed",anchor="w",fill="white")

        while not self.stopped:
            # update the keys that are down
            self.run_key_events()
            # move the camera/spaceship based on keys
            self.update_pos()
            # move the camera based on the spaceship
            self.move_to_ship()

            # update all objects in the Game and the Engine
            self.update_objects()
            # then render
            self.render()

            # updating fps
            t2 = time.clock()
            self.fps = 1/(t2-t)

            # debugging messages
            self.canvas.itemconfig(fps_text,text="fps: " + str(int(self.fps)))
            #self.canvas.itemconfig(zs,text="zs: " + str(self.ship.zvelocity))
            #self.canvas.itemconfig(xs,text="xs: " + str(self.ship.xvelocity))
            #self.canvas.itemconfig(rzs,text="rzs: " + str(self.ship.rotz_velocity))
            # keep track of time for fps
            t = time.clock()
            # update the tkinter window (draw the buffer to the display)
            self.root.update()
Exemplo n.º 16
0
game_over = create_game_over_text()

# Create New hi-score text
hi_score = create_hiscore_text()

# Create wall groups
wall_group_list = []

for group in range(WALLS):
    wall_group_list.append(pygame.sprite.Group())

# Create walls, pixel by pixel
build_wall(wall_group_list)

# Create spaceship
spaceship = SpaceShip(SPACESHIP_PATH)

# Create shot group
shots = pygame.sprite.Group()

# Create alien shot group
alien_shots = pygame.sprite.Group()

# Create alien fleet
fleet_group = []
alien_count = 0

# Create fleet of aliens
alien_count = create_alien_fleet(fleet_group)

# Create boss - boss is randomly created during gameplay
Exemplo n.º 17
0
    def __init__(self,root,canvas,settings={},cursor_scroll=False):
        # tkinter properties that are passed down
        self.root = root
        self.canvas = canvas
        # 3d graphics engine
        self.engine = Engine(self.canvas,WIDTH,HEIGHT)
        self.stopped = False

        self.cursor_scroll = cursor_scroll

        ### BEGIN SETTINGS values ###
        self.settings = settings
        self.fps_speed_adjustment = 1

        # movement
        self.speed = 1
        self.rot_velocity = math.pi/180/5
        self.noclip = False
        ###  END SETTINGS values  ###

        self.objects = []

        # key bindings / checking
        self.keys_down = []
        self.key_mapping = {
            KEYS["W"]:           self.forward,
            KEYS["S"]:           self.backward,
            KEYS["A"]:           self.left,
            KEYS["D"]:           self.right,
            KEYS["SHIFT"]:       self.down,
            KEYS["SPACE"]:       self.up,
            KEYS["ESC"]:         self.stop,
            KEYS["R"]:           self.reset,
            KEYS["LEFT_ARROW"]:  self.rot_left,
            KEYS["RIGHT_ARROW"]: self.rot_right,
            KEYS["UP_ARROW"]:    self.rot_up,
            KEYS["DOWN_ARROW"]:  self.rot_down
        }

        # methods to be run once a key has stopped being pressed
        self.key_up_mapping = {
            KEYS["W"]:     self.kill_zvelocity,
            KEYS["S"]:     self.kill_zvelocity,
            KEYS["A"]:     self.kill_xvelocity,
            KEYS["D"]:     self.kill_xvelocity,
            KEYS["SHIFT"]: self.kill_yvelocity,
            KEYS["SPACE"]: self.kill_yvelocity,
            KEYS["T"]:     self.toggle_noclip
        }

        # rotation based on whether or not the mouse will be used
        # event bindings
        self.canvas.bind("<KeyPress>",self.keydown)
        self.canvas.bind("<KeyRelease>",self.keyup)
        if self.cursor_scroll:
            self.canvas.bind("<Motion>",self.rot)

        # camera init values
        self.xvelocity = 0
        self.zvelocity = 0
        self.yvelocity = 0

        # camera's offset from the spaceship's position
        self.xoffset = 10
        self.yoffset = 20
        self.zoffset = -10

        # space ship
        self.ship = SpaceShip(
            (0,0,0),
            self.speed,
            self.rot_velocity,
            self.engine,
            ObjectFile("objects/spaceship.obj",
                scale=0.25,
                pos=(10,0,20)
            )
        )
        self.objects.append(self.ship)

        # game stats
        self.fps = 0
        self.mousex = 0
        self.mousey = 0
        
        # init canvas
        self.canvas.pack()
        self.canvas.focus_set()
Exemplo n.º 18
0
# ###################################################################################
# Helper Functions End
# ###################################################################################

# ###################################################################################
# Game initialization
# ###################################################################################
pygame.init()
# The clock will be used to control how fast the screen updates
clock = pygame.time.Clock()
# area which displays game and score

background = pygame.image.load("assets/background.jpg").convert()
position = HEIGHT

hero = SpaceShip()
spaceships = pygame.sprite.Group()  # For multiplayer support
spaceships.add(hero)  # single player for now

missiles = pygame.sprite.Group()
missiles_alien = pygame.sprite.Group()

aliens = pygame.sprite.Group()
clock_alien = pygame.time.Clock()  # used to keep track of alien respawn
time_elapsed = spawn_alien(RESPAWN_TIME_ALIEN)  # start game with one alien

explosions = pygame.sprite.Group()

scores = pygame.sprite.Group()  # For multiplayer support
score = Score("Score", 0, HEIGHT - 30)
scores.add(score)
Exemplo n.º 19
0
pg.display.set_caption("Asteroids!")

font = pg.font.Font(None, 30)
clock = pg.time.Clock()

def spawnAsteroid() :
    randomAngle = math.radians(randrange(0, 360))
    randDist = randrange(200, 400)

    ax = 400 + (randDist * math.cos(randomAngle))
    ay = 300 + (randDist * math.sin(randomAngle))

    g.asteroids.append(Asteroid(ax, ay, randomAngle, 60))

for i in range(10) :
    g.ships.append(SpaceShip())

for i in range(10) :
    spawnAsteroid()

def update(dt) :

    for ship in g.ships :
        distances = []
        for asteroid in g.asteroids :
            g.distance(ship, asteroid)
            distances.append(g.distance(ship, asteroid))

        input = heapq.nsmallest(6, distances)
        ship.update(dt, input)