使用pygame製做打地鼠遊戲

使用pygame製做打地鼠遊戲

一、運行結果預覽

開始界面

第一關

第二關

第三關

第四關

第五關

遊戲結束

二、遊戲功能介紹

2.1開發環境:

python版本:python3.7python

2.2相關模塊:

pygame模塊,以及一些Python自帶的模塊。ios

2.3遊戲介紹:

遊戲採用120秒計時進行,dom

前40秒爲第一關,老鼠的出現速度爲很慢;ide

40-60秒爲第二關,老鼠的出現速度爲慢;函數

60-80秒爲第三關,老鼠的出現速度爲中等;字體

80-100秒爲第四關,老鼠的出現速度爲快;ui

100秒後爲第五關,老鼠的出現速度爲很快;rest

倒計時結束時候遊戲結束,比較分數。code

三、開發思路

3.1定義的py文件

3.1.1 mouse.py(主函數入口)

經過mouse.py文件進行整個打地鼠功能的連接。orm

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.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()
相關文章
相關標籤/搜索