使用pygame制作打地鼠游戏
1、运行结果预览
开始界面
第一关
第二关
第三关
第四关
第五关
游戏结束
2、游戏功能介绍
2.1开发环境:
python版本:python3.7
2.2相关模块:
pygame模块,以及一些Python自带的模块。
2.3游戏介绍:
游戏采用120秒计时进行,
前40秒为第一关,老鼠的出现速度为很慢;
40-60秒为第二关,老鼠的出现速度为慢;
60-80秒为第三关,老鼠的出现速度为中等;
80-100秒为第四关,老鼠的出现速度为快;
100秒后为第五关,老鼠的出现速度为很快;
倒计时结束时候游戏结束,比较分数。
3、开发思路
3.1定义的py文件
3.1.1 mouse.py(主函数入口)
通过mouse.py文件进行整个打地鼠功能的链接。
3.1.2cfg.py文件(字体等基础配置)
cfg文件中定义了基础的配置,字体,颜色,大小等等
3.1.3mole.py文件(地鼠)
mole定义了地鼠,包括地鼠的图片加载,地鼠的显示,重置等
3.1.4hammer.py文件(锤子)
hammer定义了锤子,包括锤子的图片加载,锤子的显示,击中时的效果,重置等
3.1.5endinterface.py文件(结束界面)
endinterface定义了结束时候的页面,包括分数显示和最高分显示
3.1.6startinterface.py文件(开始界面)
startinterface定义了开始的页面。
3.2定义的函数
3.2.1游戏初始化
def initGame():
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('袁鑫张晨恩的打地鼠游戏')
return screen
3.2.2游戏的主要入口
def main():
3.2.3 游戏中老鼠类
class Mole(pygame.sprite.Sprite):
3.2.4 游戏中锤子类
class Hammer(pygame.sprite.Sprite):
3.2.5 游戏中开始界面
def startInterface(screen, begin_image_paths):
3.2.6 游戏中结束界面
def endInterface(screen, end_image_path, again_image_paths, score_info, font_path, font_colors, screensize):
4、相关代码
4.1mouse.py(主函数入口)
def main():
# 初始化
screen = initGame()
4.1.1 加载背景音乐和其他音效
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)
}
4.1.2加载字体
font = pygame.font.Font(cfg.FONT_PATH, 40)
4.1.3 加载背景图片
bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
4.1.4 开始界面
startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
4.1.5 地鼠改变位置的计时
hole_pos = random.choice(cfg.HOLE_POSITIONS)
change_hole_event = pygame.USEREVENT
pygame.time.set_timer(change_hole_event, 800)
4.1.6 地鼠
mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
4.1.7 锤子
hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
4.1.8 时钟
clock = pygame.time.Clock()
4.1.9 分数
your_score = 0
4.1.10 关卡
number = 1
flag = False
4.1.11 游戏主循环
while True:
# --游戏时间为120s
time_remain = round((121000 - pygame.time.get_ticks()) / 1000.)
4.1.12 游戏时间减少, 地鼠变位置速度变快
# 第一关
if time_remain == 100 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 == 80 and not flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 600)
flag = True
# 第三关
elif time_remain == 60 and not flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 550)
flag = True
# 第四关
elif 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, 500)
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, 450)
flag = False
# 关卡显示
if time_remain == 100:
number = 1
elif time_remain == 80:
number = 2
elif time_remain == 60:
number = 3
elif time_remain == 40:
number = 4
elif time_remain == 20:
number = 5
4.1.13倒计时音效
if time_remain == 10:
audios['count_down'].play()
4.1.14游戏结束
if time_remain < 0:
break
count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
4.1.15按键检测
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)
4.1.16-碰撞检测
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
4.1.17分数
your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
your_number_text2 = font.render('第 '+str(number)+'关', True, cfg.WHITE)
4.1.18绑定必要的游戏元素到屏幕(注意顺序)
screen.blit(bg_img, (0, 0))
screen.blit(count_down_text, (800, 8))
screen.blit(your_score_text, (750, 430))
screen.blit(your_number_text2, (600, 430))
mole.draw(screen)
hammer.draw(screen)
4.1.19读取最佳分数
try:
best_score = int(open(cfg.RECORD_PATH).read())
except:
best_score = 0
4.1.20若当前分数大于最佳分数则更新最佳分数
if your_score > best_score:
f = open(cfg.RECORD_PATH, 'w')
f.write(str(your_score))
f.close()
4.1.21 结束界面
score_info = {'your_score': your_score, 'best_score': best_score}
is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE)
return is_restart
4.2cfg.py文件(字体等基础配置)
import os
CURPATH = os.getcwd()
SCREENSIZE = (993, 477)
HAMMER_IMAGEPATHS = [os.path.join(CURPATH, 'resources/images/hammer0.png'), os.path.join(CURPATH, 'resources/images/hammer1.png')]
GAME_BEGIN_IMAGEPATHS = [os.path.join(CURPATH, 'resources/images/begin.png'), os.path.join(CURPATH, 'resources/images/begin1.png')]
GAME_AGAIN_IMAGEPATHS = [os.path.join(CURPATH, 'resources/images/again1.png'), os.path.join(CURPATH, 'resources/images/again2.png')]
GAME_BG_IMAGEPATH = os.path.join(CURPATH, 'resources/images/background.png')
GAME_END_IMAGEPATH = os.path.join(CURPATH, 'resources/images/end.png')
MOLE_IMAGEPATHS = [os.path.join(CURPATH, 'resources/images/mole_1.png'), os.path.join(CURPATH, 'resources/images/mole_laugh1.png'),
os.path.join(CURPATH, 'resources/images/mole_laugh2.png'), os.path.join(CURPATH, 'resources/images/mole_laugh3.png')]
HOLE_POSITIONS = [(90, -20), (405, -20), (720, -20), (90, 140), (405, 140), (720, 140), (90, 290), (405, 290), (720, 290)]
BGM_PATH = 'resources/audios/bgm.mp3'
COUNT_DOWN_SOUND_PATH = 'resources/audios/count_down.wav'
HAMMERING_SOUND_PATH = 'resources/audios/hammering.wav'
FONT_PATH = 'resources/font/字体管家胖丫儿体.ttf'
BROWN = (150, 75, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
RECORD_PATH = 'score.rec'
4.3mole.py文件(地鼠)
import 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
4.3.1设置位置
def setPosition(self, pos):
self.rect.left, self.rect.top = pos
4.3.2设置被击中
def setBeHammered(self):
self.is_hammer = True
4.3.3显示在屏幕上
def draw(self, screen):
if self.is_hammer: self.image = self.images[1]
screen.blit(self.image, self.rect)
4.3.4重置
def reset(self):
self.image = self.images[0]
self.is_hammer = False
4.4hammer.py文件(锤子)
import pygame
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
4.4.1用于显示锤击时的特效
self.hammer_count = 0
self.hammer_last_time = 4
self.is_hammering = False
4.4.2设置位置
def setPosition(self, pos):
self.rect.centerx, self.rect.centery = pos
4.4.3设置hammering
def setHammering(self):
self.is_hammering = True
4.4.4显示在屏幕上
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)
4.5endinterface.py文件(结束界面)
import sys
import pygame
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()
4.6startinterface.py文件(开始界面)
import sys
import pygame
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()
来源:oschina
链接:https://my.oschina.net/u/4460763/blog/3221833