使用python完成一个射击类游戏“小黄人保卫战”

发布时间 2023-04-21 21:26:57作者: Noiimplant

1.项目开发环境

  • 下载Python且保证能够正常工作,为了能用Python来写一个游戏,需要安装PyGame。
  • PyGame是一个Python的库,能够让我们容易的写出一个游戏。它提供的功能包括图片处理和声音重放的功能,并且它们能很容易的整合进你的游戏里。

2.项目功能介绍

通过设计一款塔防游戏“小黄人保卫战”,来提升和巩固自己的Python技术水平。在这个塔防游戏,小黄人作为英雄,需要在城堡里射出香蕉,抵御老鼠的进攻。

3.项目设计思路

  1. 导入pygame库,这一步能让你使用库里提供的功能
  2. 初始化pygame,设置展示窗口
  3. 加载作为小黄人的图片
  4. 不停地循环执行接下来的部分
  5. 在给屏幕画任何东西之前用黑色进行填充
  6. 在屏幕的(100,100)坐标出添加你加载的小黄人的图片
  7. 更新屏幕
  8. 检查一些新的事件,如果有退出命令,则终止程序的执行。
  9. 开始给游戏的背景加上一些风景。这可以通过一些 screen.blit() 的调用来实现。
  10. 这段代码加载图片并将它们放在变量里。现在它们需要被画在屏幕上。但是当你检查了背景的图片后,发现它不会覆盖整个屏幕,它的分辨率是640 x 480。

4.项目流程

设置老鼠的出现,保证随机性。

并且随着游戏时间增加,游戏难度也得随之增加。

那么,老鼠就得出现的频率更快,血条掉血也更快,射击难度加大。

5.游戏说明

  • 首先:让小黄人能够移动
  • 为了做到这一点,首先,需要实现一个方法,用来记录在某一时刻那个键被按下。可以通过新建一个按键状态的队列来存放每个想在游戏里用到的按键。
  • 然后,让小黄人转变攻击方向
  • 小黄人在玩家按键的时候可以移动了,但是如果能用鼠标让小黄人朝向你选择的方向不是更酷吗?这样它就不会总是朝向一个方向了。用三角定理实现它会非常简单。

6.项目界面

image

鼠标控制箭头转向
image
血条结束就显示“GAME OVER”
image

7.代码实现

#coding:utf-8
#导入pygame库和一些常用的函数和常量
#1
import pygame
from pygame.locals import *
import math
import random

#2
#初始化pygame,创建了一个窗口
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
pygame.display.set_caption("20177710409*樊晓琳")
keys = [False, False, False, False]
playerpos=[100,100]
acc=[0,0]
arrows=[]
#定义一个定时器,使得游戏里可以经过一段时间后就新建一只老鼠
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194
pygame.mixer.init()

#3
#加载本地图片
player = pygame.image.load("E:/BB_Resources/sources/images/dude.png")
grass = pygame.image.load("E:/BB_Resources/sources/images/grass.jpg")
castle = pygame.image.load("E:/BB_Resources/sources/images/castl.png")
arrow = pygame.image.load("E:/BB_Resources/sources/images/bullet.png")
#加载老鼠图片
badguyimg1 = pygame.image.load("E:/BB_Resources/sources/images/badguy.png")
badguyimg=badguyimg1
#加载血条图片
healthbar = pygame.image.load("E:/BB_Resources/sources/images/healthbar.png")
health = pygame.image.load("E:/BB_Resources/sources/images/health.png")
#加载输赢图片
gameover = pygame.image.load("E:/BB_Resources/sources/images/gameover.png")
youwin = pygame.image.load("E:/BB_Resources/sources/images/youwin.png")
#加载声音
hit = pygame.mixer.Sound("E:/BB_Resources/sources/audio/explode.wav")
enemy = pygame.mixer.Sound("E:/BB_Resources/sources/audio/enemy.wav")
shoot = pygame.mixer.Sound("E:/BB_Resources/sources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('E:/BB_Resources/sources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)

#4
# 进入循环
running = 1
exitcode = 0
while running:
    badtimer-=1


#5 设置黑色背景
    screen.fill(0)

#6
# 循环画上背景
    for x in range(width//grass.get_width()+1):
        for y in range(height//grass.get_height()+1):
            screen.blit(grass,(x*100,y*100))
#画上四个城堡
    screen.blit(castle,(0,30))
    screen.blit(castle,(0,135))
    screen.blit(castle,(0,240))
    screen.blit(castle,(0,345 ))
#画上小黄人
#玩家旋转小黄人
    position = pygame.mouse.get_pos()
    angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
    playerrot = pygame.transform.rotate(player, 360-angle*57.29)
    playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
    screen.blit(playerrot, playerpos1)
#画出射出的香蕉
    for bullet in arrows:
        index=0
        velx=math.cos(bullet[0])*10
        vely=math.sin(bullet[0])*10
        bullet[1]+=velx
        bullet[2]+=vely
        if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
            arrows.pop(index)
        index+=1
        for projectile in arrows:
            arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
            screen.blit(arrow1, (projectile[1], projectile[2]))
#画上老鼠
    if badtimer==0:
        badguys.append([640, random.randint(50,430)])
        badtimer=100-(badtimer1*2)
        if badtimer1>=35:
            badtimer1=35
        else:
            badtimer1+=5
    index=0
    for badguy in badguys:
        if badguy[0]<-64:
            badguys.pop(index)
        badguy[0]-=7
        #老鼠冲过来并且在碰到城堡的时候会消失。尽管你看不到,老鼠实际上会降低你的健康值。
        badrect=pygame.Rect(badguyimg.get_rect())
        badrect.top=badguy[1]
        badrect.left=badguy[0]
        if badrect.left<64:
            hit.play()
            healthvalue -= random.randint(5,20)
            badguys.pop(index)
        #检查射出的香蕉
        index1=0
        for bullet in arrows:
            bullrect=pygame.Rect(arrow.get_rect())
            bullrect.left=bullet[1]
            bullrect.top=bullet[2]
            if badrect.colliderect(bullrect):
                enemy.play()
                acc[0]+=1
                badguys.pop(index)
                arrows.pop(index1)
            index1+=1

        index+=1
        for badguy in badguys:
            screen.blit(badguyimg, badguy)

# 添加时钟用来计时
    font = pygame.font.Font(None, 24)
    survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
    textRect = survivedtext.get_rect()
    textRect.topright=[635,5]
    screen.blit(survivedtext, textRect)
    #添加生命值显示
    screen.blit(healthbar, (5,5))
    for health1 in range(healthvalue):
        screen.blit(health, (health1+8,8))
#7
# 刷新屏幕
    pygame.display.flip()

#8设置游戏退出条件
    for event in pygame.event.get():
            if event.type == QUIT:
              exit()
    #定义玩家wasd四个按键用来控制方向
    if event.type == pygame.KEYDOWN:
        if event.key==K_w:
            keys[0]=True
        elif event.key==K_a:
            keys[1]=True
        elif event.key==K_s:
            keys[2]=True
        elif event.key==K_d:
            keys[3]=True
    if event.type == pygame.KEYUP:
        if event.key==pygame.K_w:
            keys[0]=False
        elif event.key==pygame.K_a:
            keys[1]=False
        elif event.key==pygame.K_s:
            keys[2]=False
        elif event.key==pygame.K_d:
            keys[3]=False
#玩家移动按键
    if keys[0]:
        playerpos[1]-=5
    elif keys[2]:
        playerpos[1]+=5
    if keys[1]:
        playerpos[0]-=5
    elif keys[3]:
        playerpos[0]+=5
#跟踪射出的香蕉
    if event.type==pygame.MOUSEBUTTONDOWN:
        shoot.play()
        position=pygame.mouse.get_pos()
        acc[1]+=1
        arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])


#检查输赢
    if pygame.time.get_ticks()>=90000:
        running=0
        exitcode=1
    if healthvalue<=0:
        running=0
        exitcode=0
    if acc[1]!=0:
        accuracy=acc[0]*1.0/acc[1]*100
    else:
        accuracy=0
# 输赢显示
if exitcode==0:
    pygame.font.init()
    font = pygame.font.Font(None, 24)
    text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery+24
    screen.blit(gameover, (0,0))
    screen.blit(text, textRect)
else:
    pygame.font.init()
    font = pygame.font.Font(None, 24)
    text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery+24
    screen.blit(youwin, (0,0))
    screen.blit(text, textRect)
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
    pygame.display.flip()