欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Python制作打地鼠小游戲

 更新時(shí)間:2022年03月05日 15:25:47   作者:Charles的皮卡丘  
這篇文章主要為大家介紹了如何利用Python實(shí)現(xiàn)打地鼠小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

效果展示

打地鼠小游戲

簡(jiǎn)介

打地鼠的游戲規(guī)則相信大家都知道,這里就不多介紹了,反正就是不停地拿錘子打洞里鉆出來(lái)的地鼠唄~

首先,讓我們確定一下游戲中有哪些元素。打地鼠打地鼠,地鼠當(dāng)然得有啦,那我們就寫(xiě)個(gè)地鼠的游戲精靈類(lèi)唄:

'''地鼠'''
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
    '''設(shè)置位置'''
    def setPosition(self, pos):
        self.rect.left, self.rect.top = pos
    '''設(shè)置被擊中'''
    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

顯然,地鼠有被錘子擊中和未被錘子擊中這兩種狀態(tài),所以需要加載兩張圖,當(dāng)?shù)厥蟊粨糁袝r(shí)從未被擊中的地鼠狀態(tài)圖切換到被擊中后的地鼠狀態(tài)圖(我找的圖可能不太像地鼠,請(qǐng)各位老哥見(jiàn)諒)。然后我們?cè)賮?lái)定義一下錘子這個(gè)游戲精靈類(lèi),和地鼠類(lèi)似,錘子也有未錘下去和已錘下去兩種狀態(tài),只不過(guò)錘下去之后需要迅速恢復(fù)回未錘下去的狀態(tài),具體而言,代碼實(shí)現(xiàn)如下:

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
        # 用于顯示錘擊時(shí)的特效
        self.hammer_count = 0
        self.hammer_last_time = 4
        self.is_hammering = False
    '''設(shè)置位置'''
    def setPosition(self, pos):
        self.rect.centerx, self.rect.centery = pos
    '''設(shè)置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,定義完游戲精靈之后,我們就可以開(kāi)始寫(xiě)主程序啦。首先自然是游戲初始化:

'''游戲初始化'''
def initGame():
  pygame.init()
  pygame.mixer.init()
  screen = pygame.display.set_mode(cfg.SCREENSIZE)
  pygame.display.set_caption('Whac A Mole-微信公眾號(hào):Charles的皮卡丘')
  return screen

然后加載必要的游戲素材和定義必要的游戲變量(我都注釋的比較詳細(xì)了,就不在文章里贅述一遍了,自己看注釋唄~)

  # 加載背景音樂(lè)和其他音效
  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)
  # 開(kāi)始界面
  startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
  # 地鼠改變位置的計(jì)時(shí)
  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))
  # 時(shí)鐘
  clock = pygame.time.Clock()
  # 分?jǐn)?shù)
  your_score = 0

接著就是游戲主循環(huán)啦:

# 游戲主循環(huán)
while True:
  # --游戲時(shí)間為60s
  time_remain = round((61000 - pygame.time.get_ticks()) / 1000.)
  # --游戲時(shí)間減少, 地鼠變位置速度變快
  if time_remain == 40:
    pygame.time.set_timer(change_hole_event, 650)
  elif time_remain == 20:
    pygame.time.set_timer(change_hole_event, 500)
  # --倒計(jì)時(shí)音效
  if time_remain == 10:
    audios['count_down'].play()
  # --游戲結(jié)束
  if time_remain < 0: break
  count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
  # --按鍵檢測(cè)
  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)
  # --碰撞檢測(cè)
  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
  # --分?jǐn)?shù)
  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)

每一部分我也都做了注釋?zhuān)壿嫼芎?jiǎn)單,就不多廢話了。60s后,游戲結(jié)束,我們就可以統(tǒng)計(jì)分?jǐn)?shù)以及和歷史最高分做對(duì)比了:

# 讀取最佳分?jǐn)?shù)(try塊避免第一次游戲無(wú).rec文件)
try:
  best_score = int(open(cfg.RECORD_PATH).read())
except:
  best_score = 0
# 若當(dāng)前分?jǐn)?shù)大于最佳分?jǐn)?shù)則更新最佳分?jǐn)?shù)
if your_score > best_score:
  f = open(cfg.RECORD_PATH, 'w')
  f.write(str(your_score))
  f.close()

為了使游戲看起來(lái)更“正式”,再隨手添個(gè)開(kāi)始界面和結(jié)束界面唄:

'''游戲開(kāi)始界面'''
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()


'''結(jié)束界面'''
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制作打地鼠小游戲的詳細(xì)內(nèi)容,更多關(guān)于Python打地鼠游戲的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python爬蟲(chóng)獲取基金基本信息

    Python爬蟲(chóng)獲取基金基本信息

    這篇文章主要介紹了Python爬蟲(chóng)獲取基金基本信息,文章基于上一篇文章內(nèi)容基于python的相關(guān)資料展開(kāi)主題,需要的小伙伴可以參考一下
    2022-05-05
  • CentOS系統(tǒng)Python卸載攻略大揭秘

    CentOS系統(tǒng)Python卸載攻略大揭秘

    想要徹底卸載?CentOS?上的?Python?嗎?不用擔(dān)心,我們來(lái)幫你搞定!本指南將教你如何在?CentOS?系統(tǒng)上完全清理?Python,讓你的系統(tǒng)煥然一新,跟著我們的步驟,讓你的系統(tǒng)煥然一新吧!
    2023-11-11
  • 淺談Python 的枚舉 Enum

    淺談Python 的枚舉 Enum

    下面小編就為大家?guī)?lái)一篇淺談Python 的枚舉 Enum。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-06-06
  • 淺談PyQt5 的幫助文檔查找方法,可以查看每個(gè)類(lèi)的方法

    淺談PyQt5 的幫助文檔查找方法,可以查看每個(gè)類(lèi)的方法

    今天小編就為大家分享一篇淺談PyQt5 的幫助文檔查找方法,可以查看每個(gè)類(lèi)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • python里glob模塊知識(shí)點(diǎn)總結(jié)

    python里glob模塊知識(shí)點(diǎn)總結(jié)

    在本篇文章里小編給大家整理的是一篇關(guān)于python里glob模塊知識(shí)點(diǎn)總結(jié),有需要的朋友們可以參考下。
    2021-01-01
  • Python使用pandas將表格數(shù)據(jù)進(jìn)行處理

    Python使用pandas將表格數(shù)據(jù)進(jìn)行處理

    這篇文章主要介紹了Python使用pandas將表格數(shù)據(jù)進(jìn)行處理,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下
    2022-08-08
  • Python利用imshow制作自定義漸變填充柱狀圖(colorbar)

    Python利用imshow制作自定義漸變填充柱狀圖(colorbar)

    這篇文章主要介紹了Python利用imshow制作自定義漸變填充柱狀圖(colorbar),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • django 2.0更新的10條注意事項(xiàng)總結(jié)

    django 2.0更新的10條注意事項(xiàng)總結(jié)

    Django 是 Python Web 開(kāi)發(fā)最常用的框架之一,跟進(jìn)它的最新變化絕對(duì)是必須的。下面這篇文章主要給大家介紹了關(guān)于django 2.0更新的10條注意事項(xiàng),文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2018-01-01
  • python不相等的兩個(gè)字符串的 if 條件判斷為T(mén)rue詳解

    python不相等的兩個(gè)字符串的 if 條件判斷為T(mén)rue詳解

    這篇文章主要介紹了python不相等的兩個(gè)字符串的 if 條件判斷為T(mén)rue詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-03-03
  • Python中PyExecJS(執(zhí)行JS代碼庫(kù))的具體使用

    Python中PyExecJS(執(zhí)行JS代碼庫(kù))的具體使用

    pyexecjs是一個(gè)用Python來(lái)執(zhí)行JavaScript代碼的工具庫(kù),本文主要介紹了Python中PyExecJS(執(zhí)行JS代碼庫(kù))的具體使用,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02

最新評(píng)論