这篇文章主要介绍了python简单射击小游戏代码,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获,下面让小编带着大家一起了解一下。
Source code download: 本文相关源码
本博客使用了Pygame库来创建游戏窗口和处理游戏逻辑。
目录
一、代码的详细解释:
创建游戏窗口:
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bee")
创建了一个名为"Bee"的游戏窗口,窗口的大小由WIDTH
和HEIGHT
变量决定用python画皮卡丘代码。
蜜蜂的定义与循环出现:
class Enemy():
# 构造函数
def __init__(self):
self.img = pygame.image.load('bee.png')
self.x = random.randint(200, 600)
self.y = random.randint(50, 250)
self.step = random.randint(2, 6)
# 重置蜜蜂位置
def reset(self):
self.x = random.randint(200, 600)
self.y = random.randint(50, 200)
enemies = []
for i in range(number_of_bee):
enemies.append(Enemy())
定义了一个名为Enemy
的类,每个蜜蜂对象有图像、x坐标、y坐标和步长。蜜蜂的循环出现在enemies
列表中,初始位置随机。
显示蜜蜂和处理碰撞:
def show_bee():
for e in enemies:
screen.blit(e.img, (e.x, e.y))
e.x += e.step
if e.x > 736 or e.x < 0:
e.step *= -1
e.y += 40
if e.y >= 450:
over, over_rect = init_item('game over.jpg', 0, 0)
txt_restart, txt_restart_rect = show_text("Restart", 300, 300, 32)
screen.blit(over, over_rect) ##显示gameover图片
screen.blit(txt_restart, txt_restart_rect)
quit()
这个函数用于显示蜜蜂,并在蜜蜂到达窗口边缘时,让其改变方向并向下移动。如果蜜蜂的y坐标超过了450,则游戏结束,显示"game over"图片