Python Pygame实现打地鼠游戏完整教程

小林子
小林子
发布时间:2026-10-15| 6人浏览过
原创

本文详细介绍如何使用Python和Pygame库开发一款经典的打地鼠小游戏。内容涵盖游戏精灵类(地鼠与锤子)的状态管理、游戏初始化配置、主循环逻辑及分数统计机制。通过完整的代码示例,帮助开发者掌握Pygame基础应用,包括事件处理、图像加载与碰撞检测,适合Python初学者进行实战练习。

效果展示

打地鼠小游戏

游戏简介与规则

简介

对于打地鼠游戏的规则,大家应当十分熟悉:玩家需使用锤子不断击打从洞中随机钻出的地鼠。本教程将基于此规则,利用Python语言及Pygame图形库构建该游戏。

定义地鼠与锤子精灵类

首先明确游戏中的核心元素。既然名为打地鼠,地鼠自然是主角。我们需要定义一个地鼠的游戏精灵类,具体实现如下:

'''地鼠'''
class Mole(pygame.sprite.Sprite):
    def __init__(self, image_paths, position, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.images = [pygame.transform.scale(pygame.image.load(image_paths[0]), (101, 103)), 
                       pygame.transform.scale(pygame.image.load(image_paths[-1]), (101, 103))]
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.setPosition(position)
        self.is_hammer = False
    '''设置位置'''
    def setPosition(self, pos):
        self.rect.left, self.rect.top = pos
    '''设置被击中'''
    def setBeHammered(self):
        self.is_hammer = True
    '''显示在屏幕上'''
    def draw(self, screen):
        if self.is_hammer: self.image = self.images[1]
        screen.blit(self.image, self.rect)
    '''重置'''
    def reset(self):
        self.image = self.images[0]
        self.is_hammer = False

地鼠存在两种状态:未被击中与被击中。因此,代码中加载了两张对应的图片。当地鼠被击中时,图像会从“未击中”状态切换为“击中”状态(注:示例图片可能并非真实地鼠,敬请谅解)。此外,还需定义锤子精灵类。锤子同样具备“未挥下”和“已挥下”两种状态,区别在于挥下后需迅速复位。具体代码实现如下:

class Hammer(pygame.sprite.Sprite):
    def __init__(self, image_paths, position, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.images = [pygame.image.load(image_paths[0]), pygame.image.load(image_paths[1])]
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.images[1])
        self.rect.left, self.rect.top = position
        # 用于显示锤击时的特效
        self.hammer_count = 0
        self.hammer_last_time = 4
        self.is_hammering = False
    '''设置位置'''
    def setPosition(self, pos):
        self.rect.centerx, self.rect.centery = pos
    '''设置hammering'''
    def setHammering(self):
        self.is_hammering = True
    '''显示在屏幕上'''
    def draw(self, screen):
        if self.is_hammering:
            self.image = self.images[1]
            self.hammer_count += 1
            if self.hammer_count > self.hammer_last_time:
                self.is_hammering = False
                self.hammer_count = 0
        else:
            self.image = self.images[0]
        screen.blit(self.image, self.rect)

游戏初始化与素材加载

定义完游戏精灵类后,即可编写主程序。第一步是进行游戏初始化:

'''游戏初始化'''
def initGame():
  pygame.init()
  pygame.mixer.init()
  screen = pygame.display.set_mode(cfg.SCREENSIZE)
  pygame.display.set_caption('Whac A Mole-微信公众号:Charles的皮卡丘')
  return screen

随后加载必要的游戏素材并定义相关变量。代码中已包含详细注释,此处不再赘述,请读者参考代码注释理解:

  # 加载背景音乐和其他音效
  pygame.mixer.music.load(cfg.BGM_PATH)
  pygame.mixer.music.play(-1)
  audios = {
        'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
        'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
      }
  # 加载字体
  font = pygame.font.Font(cfg.FONT_PATH, 40)
  # 加载背景图片
  bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
  # 开始界面
  startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
  # 地鼠改变位置的计时
  hole_pos = random.choice(cfg.HOLE_POSITIONS)
  change_hole_event = pygame.USEREVENT
  pygame.time.set_timer(change_hole_event, 800)
  # 地鼠
  mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
  # 锤子
  hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
  # 时钟
  clock = pygame.time.Clock()
  # 分数
  your_score = 0

游戏主循环与逻辑控制

接下来是游戏的主循环逻辑:

# 游戏主循环
while True:
  # --游戏时间为60s
  time_remain = round((61000 - pygame.time.get_ticks()) / 1000.)
  # --游戏时间减少, 地鼠变位置速度变快
  if time_remain == 40:
    pygame.time.set_timer(change_hole_event, 650)
  elif time_remain == 20:
    pygame.time.set_timer(change_hole_event, 500)
  # --倒计时音效
  if time_remain == 10:
    audios['count_down'].play()
  # --游戏结束
  if time_remain < 0: break
  count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
  # --按键检测
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()
    elif event.type == pygame.MOUSEMOTION:
      hammer.setPosition(pygame.mouse.get_pos())
    elif event.type == pygame.MOUSEBUTTONDOWN:
      if event.button == 1:
        hammer.setHammering()
    elif event.type == change_hole_event:
      hole_pos = random.choice(cfg.HOLE_POSITIONS)
      mole.reset()
      mole.setPosition(hole_pos)
  # --碰撞检测
  if hammer.is_hammering and not mole.is_hammer:
    is_hammer = pygame.sprite.collide_mask(hammer, mole)
    if is_hammer:
      audios['hammering'].play()
      mole.setBeHammered()
      your_score += 10
  # --分数
  your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
  # --绑定必要的游戏元素到屏幕(注意顺序)
  screen.blit(bg_img, (0, 0))
  screen.blit(count_down_text, (875, 8))
  screen.blit(your_score_text, (800, 430))
  mole.draw(screen)
  hammer.draw(screen)
  # --更新
  pygame.display.flip()
  clock.tick(60)

主循环中的各部分均添加了注释,逻辑较为直观。游戏时长设定为60秒,时间结束后将统计玩家分数并与历史最高分进行对比:

# 读取最佳分数(try块避免第一次游戏无.rec文件)
try:
  best_score = int(open(cfg.RECORD_PATH).read())
except:
  best_score = 0
# 若当前分数大于最佳分数则更新最佳分数
if your_score > best_score:
  f = open(cfg.RECORD_PATH, 'w')
  f.write(str(your_score))
  f.close()

界面优化与完整代码

为了提升游戏的完整度,我们额外添加了开始界面和结束界面:

'''游戏开始界面'''
def startInterface(screen, begin_image_paths):
    begin_images = [pygame.image.load(begin_image_paths[0]), pygame.image.load(begin_image_paths[1])]
    begin_image = begin_images[0]
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                mouse_pos = pygame.mouse.get_pos()
                if mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    begin_image = begin_images[1]
                else:
                    begin_image = begin_images[0]
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    return True
        screen.blit(begin_image, (0, 0))
        pygame.display.update()


'''结束界面'''
def endInterface(screen, end_image_path, again_image_paths, score_info, font_path, font_colors, screensize):
    end_image = pygame.image.load(end_image_path)
    again_images = [pygame.image.load(again_image_paths[0]), pygame.image.load(again_image_paths[1])]
    again_image = again_images[0]
    font = pygame.font.Font(font_path, 50)
    your_score_text = font.render('Your Score: %s' % score_info['your_score'], True, font_colors[0])
    your_score_rect = your_score_text.get_rect()
    your_score_rect.left, your_score_rect.top = (screensize[0] - your_score_rect.width) / 2, 215
    best_score_text = font.render('Best Score: %s' % score_info['best_score'], True, font_colors[1])
    best_score_rect = best_score_text.get_rect()
    best_score_rect.left, best_score_rect.top = (screensize[0] - best_score_rect.width) / 2, 275
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                mouse_pos = pygame.mouse.get_pos()
                if mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    again_image = again_images[1]
                else:
                    again_image = again_images[0]
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    return True
        screen.blit(end_image, (0, 0))
        screen.blit(again_image, (416, 370))
        screen.blit(your_score_text, your_score_rect)
        screen.blit(best_score_text, best_score_rect)
        pygame.display.update()

至此,游戏开发基本完成。

完整源代码

以上即为基于Python制作打地鼠小游戏的详细内容,更多关于Python打地鼠游戏的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。