0% found this document useful (0 votes)
12 views

Function 1

This document describes a Whac-A-Mole game built in Python with Pygame. It includes a Config class to define game parameters and paths. The WhacAMoleGame class inherits from PygameBaseGame and runs the game interface, which displays moles popping up randomly that the player tries to hammer for points within a 60 second time limit. The game interface handles events, collision detection, displays elements, and plays sounds. After the time ends, an end interface shows the score before allowing the player to restart.

Uploaded by

Allen Wu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Function 1

This document describes a Whac-A-Mole game built in Python with Pygame. It includes a Config class to define game parameters and paths. The WhacAMoleGame class inherits from PygameBaseGame and runs the game interface, which displays moles popping up randomly that the player tries to hammer for points within a 60 second time limit. The game interface handles events, collision detection, displays elements, and plays sounds. After the time ends, an end interface shows the score before allowing the player to restart.

Uploaded by

Allen Wu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

'''

Function:
打地鼠(Whac-A-Mole)小游戏
Author:
Charles
微信公众号:
Charles 的皮卡丘
'''
import os
import pygame
import random
from utils import QuitGame
from base import PygameBaseGame
from modules import Mole, Hammer, endInterface, startInterface

'''配置类'''
class Config(object):
def __init__(self):
# 根目录
self.rootdir = os.path.split(os.path.abspath(__file__))[0]
# FPS
self.FPS = 100
# 屏幕大小
self.SCREENSIZE = (993, 477)
# 标题
self.TITLE = '打地鼠 —— Charles 的皮卡丘'
# 游戏常量参数
self.HOLE_POSITIONS = [(90, -20), (405, -20), (720, -20), (90, 140), (405, 140), (720, 140),
(90, 290), (405, 290), (720, 290)]
self.BROWN = (150, 75, 0)
self.WHITE = (255, 255, 255)
self.RED = (255, 0, 0)
self.RECORD_PATH = os.path.join(self.rootdir, 'score.rec')
# 背景音乐路径
self.BGM_PATH = os.path.join(self.rootdir, 'resources/audios/bgm.mp3')
# 游戏声音路径
self.SOUND_PATHS_DICT = {
'count_down': os.path.join(self.rootdir, 'resources/audios/count_down.wav'),
'hammering': os.path.join(self.rootdir, 'resources/audios/hammering.wav'),
'question': os.path.join(self.rootdir, 'resources/audios/question.wav'),
}
# 字体路径
self.FONT_PATH = os.path.join(self.rootdir.replace('whacamole', 'base'),
'resources/fonts/Gabriola.ttf')
# 游戏图片路径
self.IMAGE_PATHS_DICT = {
'hammer': [os.path.join(self.rootdir, 'resources/images/hammer0.png'),
os.path.join(self.rootdir, 'resources/images/hammer1.png')],
'begin': [os.path.join(self.rootdir, 'resources/images/begin.png'),
os.path.join(self.rootdir, 'resources/images/begin1.png')],
'again': [os.path.join(self.rootdir, 'resources/images/again1.png'),
os.path.join(self.rootdir, 'resources/images/again2.png')],
'background': os.path.join(self.rootdir, 'resources/images/background.png'),
'end': os.path.join(self.rootdir, 'resources/images/end.png'),
'mole': [
os.path.join(self.rootdir, 'resources/images/mole_1.png'), os.path.join(self.rootdir,
'resources/images/mole_laugh1.png'),
os.path.join(self.rootdir, 'resources/images/mole_laugh2.png'),
os.path.join(self.rootdir, 'resources/images/mole_laugh3.png')
]
}

'''打地鼠(Whac-A-Mole)小游戏'''
class WhacAMoleGame(PygameBaseGame):
game_type = 'whacamole'

def __init__(self, **kwargs):


self.cfg = Config()
super(WhacAMoleGame, self).__init__(config=self.cfg, **kwargs)

'''运行游戏'''
def run(self):
while True:
is_restart = self.GamingInterface(self.screen, self.resource_loader, self.cfg)
if not is_restart:
break

'''游戏进行界面'''
def GamingInterface(self, screen, resource_loader, cfg):
# 播放背景音乐
resource_loader.playbgm()
audios = resource_loader.sounds
# 加载字体
font = pygame.font.Font(cfg.FONT_PATH, 40)
# 加载背景图片
bg_img = resource_loader.images['background']
# 开始界面
startInterface(screen, resource_loader.images['begin'])
# 地鼠改变位置的计时
hole_pos = random.choice(cfg.HOLE_POSITIONS)
change_hole_event = pygame.USEREVENT
pygame.time.set_timer(change_hole_event, 800)
# 地鼠
mole = Mole(resource_loader.images['mole'], hole_pos)
# 锤子
hammer = Hammer(resource_loader.images['hammer'], (500, 250))
# 时钟
clock = pygame.time.Clock()
# 分数
your_score = 0
flag = False
# 初始时间
init_time = pygame.time.get_ticks()
# 游戏主循环
while True:
# 游戏时间为 60s
time_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.)
# 游戏时间减少, 地鼠变位置速度变快
if time_remain == 40 and not flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 650)
flag = True
elif time_remain == 20 and flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 500)
flag = False
# 倒计时音效
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:
QuitGame()
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, (10, 10))
screen.blit(your_score_text, (800, 10))
hammer.update()
mole.update()
# 刷新画面
pygame.display.flip()
# 设置帧率
clock.tick(cfg.FPS)
# 结束界面
endInterface(screen, resource_loader.images['end'], your_score)
# 停止背景音乐
resource_loader.stopbgm()
# 写入最高分
with open(cfg.RECORD_PATH, 'w') as f:
f.write(str(your_score))
# 是否重新开始
return self.restartInterface(screen, resource_loader.images['again'], cfg)

'''运行游戏'''
if __name__ == '__main__':
game = WhacAMoleGame()
game.run()

You might also like