欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python Pygame实战之打地鼠小游戏

程序员文章站 2022-06-17 17:38:58
目录前言开发工具环境搭建原理简介前言今天给大家写一个个打地鼠小游戏,废话不多说直接开始~开发工具python版本:3.6.4相关模块:pygame模块;以及一些python自带的模块。环境搭建安装py...

前言

今天给大家写一个个打地鼠小游戏,废话不多说直接开始~

开发工具

python版本: 3.6.4

相关模块:

pygame模块;

以及一些python自带的模块。

环境搭建

安装python并添加到环境变量,pip安装需要的相关模块即可。

原理简介

打地鼠的游戏规则相信大家都知道,这里就不多介绍了,反正就是不停地拿锤子打洞里钻出来的地鼠~

首先,让我们确定一下游戏中有哪些元素。打地鼠打地鼠,地鼠当然得有啦,那我们就写个地鼠的游戏精灵类:

'''地鼠'''
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

显然,地鼠有被锤子击中和未被锤子击中这两种状态,所以需要加载两张图,当地鼠被击中时从未被击中的地鼠状态图切换到被击中后的地鼠状态图(ps:图可能不像地鼠)。

然后我们再来定义一下锤子这个游戏精灵类,和地鼠类似,锤子也有未锤下去和已锤下去两种状态,只不过锤下去之后需要迅速恢复回未锤下去的状态,具体而言,代码实现如下:

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)

ok,定义完游戏精灵之后,我们就可以开始写主程序啦。首先自然是游戏初始化:

'''游戏初始化'''
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)

每一部分我也都做了注释,逻辑很简单,就不多废话了。60s后,游戏结束,我们就可以统计分数以及和历史最高分做对比了:

# 读取最佳分数(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 pygame实战之打地鼠小游戏的文章就介绍到这了,更多相关python pygame打地鼠内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!