Python3+Pygame实现射击游戏完整代码

论坛 期权论坛     
niminba   2021-5-22 16:53   5   0
<p>之前看到过很多人写的飞机大战,当然了之前我也写过多个版本,总体来说功能是实现了,但总感觉不够“炫”</p>
<p>今天浏览Python资料的时候,意外发现了这个很好的“射击”类游戏,看上去类似飞机大战,但更好玩</p>
<h2>一、游戏特点</h2>
<p>1. 运行非常流畅</p>
<p>2. 默认有3条命,每条命的HP可以增加(吃补品)也可以减少(被击中)</p>
<p>3. 有碰撞时的音效</p>
<p>4. 有碰撞时的爆炸效果</p>
<h2>二、运行效果展示</h2>
<p style="text-align: center"><img alt="" src="https://beijingoptbbs.oss-cn-hangzhou.aliyuncs.com/jb/2426819-c2275b839f4a8f7cfdd96add39360d76.gif"></p>
<h2>三、完整代码</h2>
<div class="blockcode">
<pre class="brush:py;">
from __future__ import division
import pygame
import random
from os import path

## assets folder
img_dir = path.join(path.dirname(__file__), 'assets')
sound_folder = path.join(path.dirname(__file__), 'sounds')

###############################
## to be placed in "constant.py" later
WIDTH = 480
HEIGHT = 600
FPS = 60
POWERUP_TIME = 5000
BAR_LENGTH = 100
BAR_HEIGHT = 10

# 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)
###############################

###############################
## to placed in "__init__.py" later
## initialize pygame and create window
pygame.init()
pygame.mixer.init() ## For sound
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter")
clock = pygame.time.Clock()   ## For syncing the FPS
###############################

font_name = pygame.font.match_font('arial')

def main_menu():
  global screen

  menu_song = pygame.mixer.music.load(path.join(sound_folder, "menu.ogg"))
  pygame.mixer.music.play(-1)

  title = pygame.image.load(path.join(img_dir, "main.png")).convert()
  title = pygame.transform.scale(title, (WIDTH, HEIGHT), screen)

  screen.blit(title, (0,0))
  pygame.display.update()

  while True:
    ev = pygame.event.poll()
    if ev.type == pygame.KEYDOWN:
      if ev.key == pygame.K_RETURN:
        break
      elif ev.key == pygame.K_q:
        pygame.quit()
        quit()
    else:
      draw_text(screen, "Press [ENTER] To Begin", 30, WIDTH/2, HEIGHT/2)
      draw_text(screen, "or [Q] To Quit", 30, WIDTH/2, (HEIGHT/2)+40)
      pygame.display.update()

  #pygame.mixer.music.stop()
  ready = pygame.mixer.Sound(path.join(sound_folder,'getready.ogg'))
  ready.play()
  screen.fill(BLACK)
  draw_text(screen, "GET READY!", 40, WIDTH/2, HEIGHT/2)
  pygame.display.update()


def draw_text(surf, text, size, x, y):
  ## selecting a cross platform font to display the score
  font = pygame.font.Font(font_name, size)
  text_surface = font.render(text, True, WHITE)    ## True denotes the font to be anti-aliased
  text_rect = text_surface.get_rect()
  text_rect.midtop = (x, y)
  surf.blit(text_surface, text_rect)


def draw_shield_bar(surf, x, y, pct):
  # if pct &lt; 0:
  #   pct = 0
  pct = max(pct, 0)
  ## moving them to top
  # 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)



def newmob():
  mob_element = Mob()
  all_sprites.add(mob_element)
  mobs.add(mob_element)

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 &gt; 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


class Player(pygame.sprite.Sprite):
  def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    ## scale the player img down
    self.image = pygame.transform.scale(player_img, (50, 38))
    self.image.set_colorkey(BLACK)
    self.rect = self.image.get_rect()
    self.radius = 20
    self.rect.centerx = WIDTH / 2
    self.rect.bottom = HEIGHT - 10
    self.speedx = 0
    self.shield = 100
    self.shoot_delay = 250
    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_timer = pygame.time.get_ticks()

  def update(self):
    ## time out for powerups
    if self.power &gt;=2 and pygame.time.get_ticks() - self.power_time &gt; POWERUP_TIME:
      self.power -= 1
      self.power_time = pygame.time.get_ticks()

    ## unhide
    if self.hidden and pygame.time.get_ticks() - self.hide_timer &gt; 1000:
      self.hidden = False
      self.rect.centerx = WIDTH / 2
      self.rect.bottom = HEIGHT - 30

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1060120
帖子:212021
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP