python游戏-space shooter
程序员文章站
2022-04-22 12:18:56
第一步:构建基本框架当前需要达到基本的模型:2.构建屏幕大小,可移动敌人与可移动游戏角色。# pygame template - skeleton for a new python project, shmup gameimport pygameimport random# define screen sizeWIDTH = 480 # 360HEIGHT = 600 # 480# FRAME PER SECONDFPS = 60 # define colorsWHI...
第一步:构建基本框架
-
当前需要达到基本的模型:
2.构建屏幕大小,可移动敌人与可移动游戏角色。
# pygame template - skeleton for a new python project, shmup game import pygame import random # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 40)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((30, 40)) self.image.fill(RED) self.rect = self.image.get_rect() self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) def update(self): self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False # update all_sprites.update() # Draw / render screen.fill(BLACK) # after drawing everything, flip the display # TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER all_sprites.draw(screen) pygame.display.flip() pygame.quit()
- 构建冲突, 碰撞后退出游戏
# pygame template - skeleton for a new python project, shmup game import pygame import random # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 40)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((30, 40)) self.image.fill(RED) self.rect = self.image.get_rect() self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) def update(self): self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((10, 20)) self.image.fill(YELLOW) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: m = Mob() all_sprites.add(m) mobs.add(m) # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, False) if hits: running = False # Draw / render screen.fill(BLACK) # after drawing everything, flip the display # TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER all_sprites.draw(screen) pygame.display.flip() pygame.quit()
-
增加图形界面,看起来更像游戏:
相关图片,可在pygame 官网下载
# pygame template - skeleton for a new python project, shmup game import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = meteor_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) def update(self): self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: m = Mob() all_sprites.add(m) mobs.add(m) # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, False) if hits: running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing # after drawing everything, flip the display # TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER all_sprites.draw(screen) pygame.display.flip() pygame.quit()
-
改善碰撞功能
构建完美碰撞:
# pygame template - skeleton for a new python project, shmup game import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = 20 # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = meteor_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = int(self.rect.width * .85 / 2) # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) def update(self): self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: m = Mob() all_sprites.add(m) mobs.add(m) # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle) if hits: running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing # after drawing everything, flip the display # TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER all_sprites.draw(screen) pygame.display.flip() pygame.quit()
-
增加动画效果, 增加不同石头
# pygame template - skeleton for a new python project, shmup game import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = 20 # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image_orig = random.choice(meteor_images) self.image_orig.set_colorkey(BLACK) self.image = self.image_orig.copy() self.rect = self.image.get_rect() self.radius = int(self.rect.width * .85 / 2) # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-150, -100) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) self.rot = 0 self.rot_speed = random.randrange(-8, 8) self.last_update = pygame.time.get_ticks() def rotate(self): now = pygame.time.get_ticks() if now - self.last_update > 50: self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360 new_image = pygame.transform.rotate(self.image_orig, self.rot) old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect() self.rect.center = old_center def update(self): self.rotate() self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) # meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) meteor_images = [] meteor_list = ['meteorBrown_big1.png', 'meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med2.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png', 'meteorBrown_tiny1.png'] for img in meteor_list: meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert()) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: m = Mob() all_sprites.add(m) mobs.add(m) # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle) if hits: running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing # after drawing everything, flip the display # TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER all_sprites.draw(screen) pygame.display.flip() pygame.quit()
-
增加打分功能, 并能够发射子弹
# pygame template - skeleton for a new python project, shmup game import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, WHITE) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = 20 # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image_orig = random.choice(meteor_images) self.image_orig.set_colorkey(BLACK) self.image = self.image_orig.copy() self.rect = self.image.get_rect() self.radius = int(self.rect.width * .85 / 2) # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-150, -100) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) self.rot = 0 self.rot_speed = random.randrange(-8, 8) self.last_update = pygame.time.get_ticks() def rotate(self): now = pygame.time.get_ticks() if now - self.last_update > 50: self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360 new_image = pygame.transform.rotate(self.image_orig, self.rot) old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect() self.rect.center = old_center def update(self): self.rotate() self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) # meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) meteor_images = [] meteor_list = ['meteorBrown_big1.png', 'meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med2.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png', 'meteorBrown_tiny1.png'] for img in meteor_list: meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert()) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) score = 0 # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: score += 50 - hit.radius
m = Mob() all_sprites.add(m) mobs.add(m) # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle) if hits: running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing # after drawing everything, flip the display # TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER all_sprites.draw(screen) draw_text(screen, str(score), 18, WIDTH / 2, 10) pygame.display.flip() pygame.quit()
- 增加背景音乐和音效
# pygame template - skeleton for a new python project, shmup game # music : Instrument samples in this recording are from the Garritan Personal Orchestra. import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') snd_dir = path.join(img_dir, 'snd2') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, WHITE) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = 20 # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) shoot_sound.play() class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image_orig = random.choice(meteor_images) self.image_orig.set_colorkey(BLACK) self.image = self.image_orig.copy() self.rect = self.image.get_rect() self.radius = int(self.rect.width * .85 / 2) # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-150, -100) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) self.rot = 0 self.rot_speed = random.randrange(-8, 8) self.last_update = pygame.time.get_ticks() def rotate(self): now = pygame.time.get_ticks() if now - self.last_update > 50: self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360 new_image = pygame.transform.rotate(self.image_orig, self.rot) old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect() self.rect.center = old_center def update(self): self.rotate() self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) # meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) meteor_images = [] meteor_list = ['meteorBrown_big1.png', 'meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med2.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png', 'meteorBrown_tiny1.png'] for img in meteor_list: meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert()) # load all game sounds shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'Laser_Shoot30.wav')) expl_sounds = [] for snd in ['Explosion30.wav', 'Explosion41.wav']: expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd))) # ;oad music pygame.mixer.music.load(path.join(snd_dir, 'little_town.ogg')) pygame.mixer.music.set_volume(0.6) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): m = Mob() all_sprites.add(m) mobs.add(m) score = 0 pygame.mixer.music.play(loops = -1) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: score += 50 - hit.radius
random.choice(expl_sounds).play() m = Mob() all_sprites.add(m) mobs.add(m) # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle) if hits: running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing # after drawing everything, flip the display # TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER all_sprites.draw(screen) draw_text(screen, str(score), 18, WIDTH / 2, 10) pygame.display.flip() pygame.quit()
-
增加血量,不然一击必死
# pygame template - skeleton for a new python project, shmup game # music : Instrument samples in this recording are from the Garritan Personal Orchestra. import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') snd_dir = path.join(img_dir, 'snd2') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, WHITE) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) def newmob(): m = Mob() all_sprites.add(m) mobs.add(m) def draw_shield_bar(surf, x, y, pct): if pct < 0: pct = 0 BAR_LENGTH = 100 BAR_HEIGHT = 10 fill = (pct / 100) * BAR_LENGTH
outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT) fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT) pygame.draw.rect(surf, GREEN, fill_rect) pygame.draw.rect(surf, WHITE, outline_rect, 2) class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = 20 # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 self.shield = 100 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -5 if keystate[pygame.K_RIGHT]: self.speedx = 5 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) shoot_sound.play() class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image_orig = random.choice(meteor_images) self.image_orig.set_colorkey(BLACK) self.image = self.image_orig.copy() self.rect = self.image.get_rect() self.radius = int(self.rect.width * .85 / 2) # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-150, -100) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) self.rot = 0 self.rot_speed = random.randrange(-8, 8) self.last_update = pygame.time.get_ticks() def rotate(self): now = pygame.time.get_ticks() if now - self.last_update > 50: self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360 new_image = pygame.transform.rotate(self.image_orig, self.rot) old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect() self.rect.center = old_center def update(self): self.rotate() self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) # meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) meteor_images = [] meteor_list = ['meteorBrown_big1.png', 'meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med2.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png', 'meteorBrown_tiny1.png'] for img in meteor_list: meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert()) # load all game sounds shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'Laser_Shoot30.wav')) expl_sounds = [] for snd in ['Explosion30.wav', 'Explosion41.wav']: expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd))) # ;oad music pygame.mixer.music.load(path.join(snd_dir, 'little_town.ogg')) pygame.mixer.music.set_volume(0.6) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): newmob() score = 0 pygame.mixer.music.play(loops = -1) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.shoot() # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: score += 50 - hit.radius
random.choice(expl_sounds).play() newmob() # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle) for hit in hits: player.shield -= hit.radius * 2 newmob() if player.shield <= 0: running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing all_sprites.draw(screen) draw_text(screen, str(score), 18, WIDTH / 2, 10) draw_shield_bar(screen, 5, 5, player.shield) # after drawing everything, flip the display, TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER pygame.display.flip() pygame.quit()
-
增加爆炸效果,增加生命数量
# pygame template - skeleton for a new python project, shmup game # music : Instrument samples in this recording are from the Garritan Personal Orchestra. import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') snd_dir = path.join(img_dir, 'snd2') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, WHITE) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) def newmob(): m = Mob() all_sprites.add(m) mobs.add(m) def draw_shield_bar(surf, x, y, pct): if pct < 0: pct = 0 BAR_LENGTH = 100 BAR_HEIGHT = 10 fill = (pct / 100) * BAR_LENGTH
outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT) fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT) pygame.draw.rect(surf, GREEN, fill_rect) pygame.draw.rect(surf, WHITE, outline_rect, 2) def draw_lives(surf, x, y, lives, img): for i in range(lives): img_rect = img.get_rect() img_rect.x = x + 30 * i
img_rect.y = y
surf.blit(img, img_rect) class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = 20 # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 self.shield = 100 self.shoot_delay = 250 # hold space keep shooting self.last_shot = pygame.time.get_ticks() self.lives = 3 self.hidden = False self.hide_timer = pygame.time.get_ticks() def update(self): # unhide if hidden if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000: self.hidden = False self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -8 if keystate[pygame.K_RIGHT]: self.speedx = 8 if keystate[pygame.K_SPACE]: self.shoot() self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): now = pygame.time.get_ticks() if now - self.last_shot > self.shoot_delay: self.last_shot = now # self.last_shoot = now , keep shooting bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) shoot_sound.play() def hide(self): # hide the player temporarily self.hidden = True self.hide_timer = pygame.time.get_ticks() self.rect.center = (WIDTH / 2, HEIGHT + 200) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image_orig = random.choice(meteor_images) self.image_orig.set_colorkey(BLACK) self.image = self.image_orig.copy() self.rect = self.image.get_rect() self.radius = int(self.rect.width * .85 / 2) # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-150, -100) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) self.rot = 0 self.rot_speed = random.randrange(-8, 8) self.last_update = pygame.time.get_ticks() def rotate(self): now = pygame.time.get_ticks() if now - self.last_update > 50: self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360 new_image = pygame.transform.rotate(self.image_orig, self.rot) old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect() self.rect.center = old_center def update(self): self.rotate() self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() class Explosion(pygame.sprite.Sprite): def __init__(self, center, size): pygame.sprite.Sprite.__init__(self) self.size = size
self.image = explosion_anim[self.size][0] self.rect = self.image.get_rect() self.rect.center = center
self.frame = 0 self.last_update = pygame.time.get_ticks() self.frame_rate = 75 def update(self): now = pygame.time.get_ticks() if now - self.last_update > self.frame_rate: self.last_update = now
self.frame += 1 if self.frame == len(explosion_anim[self.size]): self.kill() else: center = self.rect.center
self.image = explosion_anim[self.size][self.frame] self.rect = self.image.get_rect() self.rect.center = center # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) player_mini_img = pygame.transform.scale(player_img, (25, 19)) player_mini_img.set_colorkey(BLACK) # meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) meteor_images = [] meteor_list = ['meteorBrown_big1.png', 'meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med2.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png', 'meteorBrown_tiny1.png'] for img in meteor_list: meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert()) explosion_anim = {} explosion_anim['lg'] = [] explosion_anim['sm'] = [] explosion_anim['player'] = [] for i in range(1, 11): filename = 'bubble_explo{}.png'.format(i) img = pygame.image.load(path.join(img_dir, filename)).convert() img.set_colorkey(BLACK) img_lg = pygame.transform.scale(img, (75, 75)) explosion_anim['lg'].append(img_lg) img_sm = pygame.transform.scale(img, (32, 32)) explosion_anim['sm'].append(img_sm) filename = 'E{}.png'.format(i) img = pygame.image.load(path.join(img_dir, filename)).convert() img.set_colorkey(BLACK) explosion_anim['player'].append(img) # load all game sounds shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'Laser_Shoot30.wav')) expl_sounds = [] for snd in ['Explosion30.wav', 'Explosion41.wav']: expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd))) player_die_sound = pygame.mixer.Sound(path.join(snd_dir, 'Explosion49.wav')) # load music pygame.mixer.music.load(path.join(snd_dir, 'little_town.ogg')) pygame.mixer.music.set_volume(0.4) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): newmob() score = 0 pygame.mixer.music.play(loops = -1) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False # elif event.type == pygame.KEYDOWN: # if event.key == pygame.K_SPACE: # player.shoot() # use holding space key to control # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: score += 50 - hit.radius
random.choice(expl_sounds).play() expl = Explosion(hit.rect.center, 'lg') all_sprites.add(expl) newmob() # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle) for hit in hits: player.shield -= hit.radius * 2 expl = Explosion(hit.rect.center, 'sm') all_sprites.add(expl) newmob() if player.shield <= 0: player_die_sound.play() death_explosion = Explosion(hit.rect.center, 'player') all_sprites.add(death_explosion) player.hide() player.lives -= 1 player.shield = 100 # running = False # if the player died and expo finished if player.lives == 0 and not death_explosion.alive(): running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing all_sprites.draw(screen) draw_text(screen, str(score), 18, WIDTH / 2, 10) draw_shield_bar(screen, 5, 5, player.shield) draw_lives(screen, WIDTH - 100, 5, player.lives, player_mini_img) # after drawing everything, flip the display, TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER pygame.display.flip() pygame.quit()
-
增加开始界面,开始界面音效, 增加保护罩, 子弹加强功能
```# pygame template - skeleton for a new python project, shmup game # music : Instrument samples in this recording are from the Garritan Personal Orchestra. import pygame import random from os import path # find path if file game_folder = path.dirname('C:\\Users\\ZZJ\\img') img_dir = path.join(game_folder, 'img') snd_dir = path.join(img_dir, 'snd2') # define screen size WIDTH = 480 # 360 HEIGHT = 600 # 480 # FRAME PER SECOND FPS = 60 POWERUP_TIME = 5000 # define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # initialize pygame and create wiindow pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Space Shooter') clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, WHITE) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) def newmob(): m = Mob() all_sprites.add(m) mobs.add(m) def draw_shield_bar(surf, x, y, pct): if pct < 0: pct = 0 BAR_LENGTH = 100 BAR_HEIGHT = 10 fill = (pct / 100) * BAR_LENGTH
outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT) fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT) pygame.draw.rect(surf, GREEN, fill_rect) pygame.draw.rect(surf, WHITE, outline_rect, 2) def draw_lives(surf, x, y, lives, img): for i in range(lives): img_rect = img.get_rect() img_rect.x = x + 30 * i
img_rect.y = y
surf.blit(img, img_rect) class Player(pygame.sprite.Sprite): # sprite for the player def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(player_img, (50, 38)) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.radius = 20 # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 self.shield = 100 self.shoot_delay = 250 # hold space keep shooting self.last_shot = pygame.time.get_ticks() self.lives = 3 self.hidden = False self.hide_timer = pygame.time.get_ticks() self.power = 1 self.power_time = pygame.time.get_ticks() def update(self): # timeout for powerups if self.power >= 2 and pygame.time.get_ticks() - self.power_time > POWERUP_TIME: self.power -= 1 self.power_time = pygame.time.get_ticks() # unhide if hidden if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000: self.hidden = False self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -8 if keystate[pygame.K_RIGHT]: self.speedx = 8 if keystate[pygame.K_SPACE]: self.shoot() self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def powerup(self): self.power += 1 self.power_time = pygame.time.get_ticks() def shoot(self): now = pygame.time.get_ticks() if now - self.last_shot > self.shoot_delay: self.last_shot = now # self.last_shoot = now , keep shooting if self.power == 1: bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) shoot_sound.play() if self.power >= 2: bullet1 = Bullet(self.rect.left, self.rect.centery) bullet2 = Bullet(self.rect.right, self.rect.centery) all_sprites.add(bullet1) all_sprites.add(bullet2) bullets.add(bullet1) bullets.add(bullet2) shoot_sound.play() def hide(self): # hide the player temporarily self.hidden = True self.hide_timer = pygame.time.get_ticks() self.rect.center = (WIDTH / 2, HEIGHT + 200) class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image_orig = random.choice(meteor_images) self.image_orig.set_colorkey(BLACK) self.image = self.image_orig.copy() self.rect = self.image.get_rect() self.radius = int(self.rect.width * .85 / 2) # pygame.draw.circle(self.image, RED, self.rect.center, self.radius) self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-150, -100) self.speedy = random.randrange(1, 8) self.speedx = random.randrange(-3, 3) self.rot = 0 self.rot_speed = random.randrange(-8, 8) self.last_update = pygame.time.get_ticks() def rotate(self): now = pygame.time.get_ticks() if now - self.last_update > 50: self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360 new_image = pygame.transform.rotate(self.image_orig, self.rot) old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect() self.rect.center = old_center def update(self): self.rotate() self.rect.x += self.speedx
self.rect.y += self.speedy if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.x = random.randrange(WIDTH - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 8) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = bullet_img
self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.bottom < 0: self.kill() class Pow(pygame.sprite.Sprite): def __init__(self, center): pygame.sprite.Sprite.__init__(self) self.type= random.choice(['shield', 'gold']) self.image = powerup_images[self.type] self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.center = center
self.speedy = 2 def update(self): self.rect.y += self.speedy # kill if it moves off the top of the screen if self.rect.top > HEIGHT: self.kill() class Explosion(pygame.sprite.Sprite): def __init__(self, center, size): pygame.sprite.Sprite.__init__(self) self.size = size
self.image = explosion_anim[self.size][0] self.rect = self.image.get_rect() self.rect.center = center
self.frame = 0 self.last_update = pygame.time.get_ticks() self.frame_rate = 75 def update(self): now = pygame.time.get_ticks() if now - self.last_update > self.frame_rate: self.last_update = now
self.frame += 1 if self.frame == len(explosion_anim[self.size]): self.kill() else: center = self.rect.center
self.image = explosion_anim[self.size][self.frame] self.rect = self.image.get_rect() self.rect.center = center # load all game graphics background = pygame.image.load(path.join(img_dir, 'blue.png')).convert() background = pygame.transform.scale(background, (480, 600)) # change the size background_rect = background.get_rect() player_img = pygame.image.load(path.join(img_dir, 'playerShip1_orange.png')) player_mini_img = pygame.transform.scale(player_img, (25, 19)) player_mini_img.set_colorkey(BLACK) # meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')) bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')) meteor_images = [] meteor_list = ['meteorBrown_big1.png', 'meteorBrown_big2.png', 'meteorBrown_med1.png', 'meteorBrown_med2.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png', 'meteorBrown_tiny1.png'] for img in meteor_list: meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert()) explosion_anim = {} explosion_anim['lg'] = [] explosion_anim['sm'] = [] explosion_anim['player'] = [] for i in range(1, 11): filename = 'bubble_explo{}.png'.format(i) img = pygame.image.load(path.join(img_dir, filename)).convert() img.set_colorkey(BLACK) img_lg = pygame.transform.scale(img, (75, 75)) explosion_anim['lg'].append(img_lg) img_sm = pygame.transform.scale(img, (32, 32)) explosion_anim['sm'].append(img_sm) filename = 'E{}.png'.format(i) img = pygame.image.load(path.join(img_dir, filename)).convert() img.set_colorkey(BLACK) explosion_anim['player'].append(img) powerup_images = {} powerup_images['shield'] = pygame.image.load(path.join(img_dir, 'shield.png')).convert() powerup_images['gold'] = pygame.image.load(path.join(img_dir, 'gun.png')).convert() # load all game sounds shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'Laser_Shoot30.wav')) shield_sound = pygame.mixer.Sound(path.join(snd_dir, 'Powerup33.wav')) power_sound = pygame.mixer.Sound(path.join(snd_dir, 'Powerup46.wav')) expl_sounds = [] for snd in ['Explosion30.wav', 'Explosion41.wav']: expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd))) player_die_sound = pygame.mixer.Sound(path.join(snd_dir, 'Explosion49.wav')) # load music pygame.mixer.music.load(path.join(snd_dir, 'little_town.ogg')) pygame.mixer.music.set_volume(0.4) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() powerups = pygame.sprite.Group() powerups = pygame.sprite.Group() player = Player() all_sprites.add(player) for i in range(8): newmob() score = 0 pygame.mixer.music.play(loops = -1) # Game loop running = True while running: # keep loop running at the right speed clock.tick(FPS) # process input (event) for event in pygame.event.get(): # check for closing windows if event.type == pygame.QUIT: running = False # elif event.type == pygame.KEYDOWN: # if event.key == pygame.K_SPACE: # player.shoot() # use holding space key to control # update all_sprites.update() # check to see if a bullet hit a mob hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: score += 50 - hit.radius
random.choice(expl_sounds).play() expl = Explosion(hit.rect.center, 'lg') all_sprites.add(expl) if random.random() > 0.9: pow = Pow(hit.rect.center) all_sprites.add(pow) powerups.add(pow) newmob() # check if a mob hit a player hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle) for hit in hits: player.shield -= hit.radius * 2 expl = Explosion(hit.rect.center, 'sm') all_sprites.add(expl) newmob() if player.shield <= 0: player_die_sound.play() death_explosion = Explosion(hit.rect.center, 'player') all_sprites.add(death_explosion) player.hide() player.lives -= 1 player.shield = 100 # running = False # if a player hits a powerup hits = pygame.sprite.spritecollide(player, powerups, True) for hit in hits: if hit.type == 'shield': shield_sound.play() player.shield += random.randrange(10, 30) if player.shield >= 100: player.shield = 100 if hit.type == 'gold': power_sound.play() player.powerup() # if the player died and expo finished if player.lives == 0 and not death_explosion.alive(): running = False # Draw / render screen.fill(BLACK) screen.blit(background, background_rect) # copy pixel of one thing to another thing all_sprites.draw(screen) draw_text(screen, str(score), 18, WIDTH / 2, 10) draw_shield_bar(screen, 5, 5, player.shield) draw_lives(screen, WIDTH - 100, 5, player.lives, player_mini_img) # after drawing everything, flip the display, TWO SIDE OF SCREEN ONE FOR PROGRAMMER ONE FOR PLAYER pygame.display.flip() pygame.quit() 最终效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200827135030258.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzAxMjc5Ng==,size_16,color_FFFFFF,t_70#pic_center) --总结:学习如何使用Python pygame
本文地址:https://blog.csdn.net/weixin_43012796/article/details/108257568