Python 语言 用 Pygame 制作打地鼠游戏 地鼠随机出现 + 点击计分

Python阿木 发布于 2025-06-09 11 次阅读


Python Pygame 打地鼠游戏开发教程

打地鼠游戏是一款经典的街机游戏,玩家通过点击屏幕上的地鼠来得分。在这个教程中,我们将使用Python的Pygame库来制作一个简单的打地鼠游戏。我们将实现地鼠的随机出现和点击计分功能。

准备工作

在开始之前,请确保你已经安装了Python和Pygame库。如果没有安装,可以通过以下命令进行安装:

bash
pip install pygame

游戏设计

游戏界面

游戏界面将包括以下元素:

- 地鼠:随机出现在屏幕上的圆形图标。
- 计分板:显示玩家的得分。
- 游戏区域:地鼠出现的区域。

游戏逻辑

- 地鼠随机出现在游戏区域内。
- 当地鼠出现时,玩家点击地鼠,计分板上的分数增加。
- 地鼠消失后,等待一段时间再次出现。

代码实现

导入库

python
import pygame
import random
import sys

初始化Pygame

python
pygame.init()

设置屏幕

python
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("打地鼠游戏")

定义颜色

python
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

定义地鼠类

python
class Mole:
def __init__(self):
self.image = pygame.Surface((50, 50))
self.image.fill(GREEN)
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.topleft = (random.randint(0, screen_width - 50), random.randint(0, screen_height - 50))
self.visible = False

def draw(self, surface):
if self.visible:
surface.blit(self.image, self.rect)

def update(self):
if not self.visible:
self.rect.topleft = (random.randint(0, screen_width - 50), random.randint(0, screen_height - 50))
self.visible = True
else:
self.visible = False

定义游戏主循环

python
def main():
clock = pygame.time.Clock()
mole = Mole()
score = 0
running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
if mole.rect.collidepoint(mouse_pos):
score += 1
mole.update()

screen.fill(BLACK)
mole.draw(screen)
font = pygame.font.Font(None, 36)
text = font.render(f"Score: {score}", True, WHITE)
screen.blit(text, (10, 10))
pygame.display.flip()
clock.tick(60)

pygame.quit()
sys.exit()

if __name__ == "__main__":
main()

总结

在这个教程中,我们使用Python和Pygame库制作了一个简单的打地鼠游戏。游戏实现了地鼠的随机出现和点击计分功能。通过这个教程,你可以学习到如何使用Pygame库来制作简单的游戏,并了解游戏开发的基本流程。

扩展

以下是一些可以扩展游戏功能的建议:

- 增加地鼠的种类和数量。
- 实现游戏难度等级。
- 添加背景音乐和音效。
- 实现游戏结束后的得分排名。

通过不断学习和实践,你可以制作出更加丰富和有趣的游戏。