Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pygame import *
- # Background music
- mixer.init()
- mixer.music.load('space.ogg')
- mixer.music.play()
- # Load images
- img_back = "galaxy.jpg" #game background
- img_hero = "rocket.png" #hero
- # Create a window
- win_width = 700
- win_height = 500
- window = display.set_mode((win_width, win_height))
- display.set_caption("Space shooter")
- background = transform.scale(image.load(img_back), (win_width, win_height))
- # GameSprite class - inheriting from class Sprite
- class GameSprite(sprite.Sprite):
- def __init__(self, player_image, player_x, player_y, size_x, size_y, player_speed):
- # Call for the class (Sprite) constructor:
- sprite.Sprite.__init__(self)
- # Every sprite must store the image property
- self.image = transform.scale(image.load(player_image), (size_x, size_y))
- self.speed = player_speed
- # Every sprite must have the rect property – the rectangle it is fitted in
- self.rect = self.image.get_rect()
- self.rect.x = player_x
- self.rect.y = player_y
- # Puts the character in the window
- def reset(self):
- window.blit(self.image, (self.rect.x, self.rect.y))
- # Player class - inherits from GameSprite
- class Player(GameSprite):
- # Function to control the sprite with arrow keys - only LEFT and RIGHT needed
- def update(self):
- keys = key.get_pressed()
- if keys[K_LEFT] and self.rect.x > 5:
- self.rect.x -= self.speed
- if keys[K_RIGHT] and self.rect.x < win_width - 80:
- self.rect.x += self.speed
- # Function to "shoot" (use the player position to create a bullet there)
- def fire(self):
- pass
- # Create sprites
- ship = Player(img_hero, 5, win_height - 100, 80, 100, 10)
- # The "game is over" variable
- # As soon as it becomes True, all sprites stop working in the main loop
- finish = False
- # Main game loop
- # The game is reset by the window close button
- run = True
- while run:
- # "Close" button press event
- for e in event.get():
- if e.type == QUIT:
- run = False
- if not finish:
- # Update the background
- window.blit(background,(0,0))
- # Start sprite movements
- ship.update()
- # Update them in a new location in each loop iteration
- ship.reset()
- display.update()
- # The loop is executed each 0.05 sec
- time.delay(50)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement