0 項(xiàng)目簡(jiǎn)介
?? Hi,各位同學(xué)好呀,這里是L學(xué)長(zhǎng)!
??今天向大家分享一個(gè)今年(2022)最新完成的畢業(yè)設(shè)計(jì)項(xiàng)目作品
python小游戲畢設(shè) 打地鼠小游戲設(shè)計(jì)與實(shí)現(xiàn) (源碼)
?? 學(xué)長(zhǎng)根據(jù)實(shí)現(xiàn)的難度和等級(jí)對(duì)項(xiàng)目進(jìn)行評(píng)分(最低0分,滿分5分)
-
難度系數(shù):3分
-
工作量:3分
-
創(chuàng)新點(diǎn):4分
-
項(xiàng)目獲?。?/strong>https://gitee.com/sinonfin/system-sharing
1 游戲介紹
打地鼠的游戲規(guī)則相信大家都知道,這里就不多介紹了,反正就是不停地拿錘子打洞里鉆出來的地鼠。
今天我們利用Python實(shí)現(xiàn)打地鼠游戲。
2 實(shí)現(xiàn)效果
3 開發(fā)工具
3.1 環(huán)境配置
-
Python版本:3.6.4
-
相關(guān)模塊:
-
pygame模塊;
-
以及一些Python自帶的模塊。
3.2 Pygame介紹
簡(jiǎn)介
Pygame是一系列專門為編寫電子游戲而設(shè)計(jì)的Python模塊(modules)。Pygame在已經(jīng)非常優(yōu)秀的SDL庫的基礎(chǔ)上增加了許多功能。這讓你能夠用Python語言編寫出豐富多彩的游戲程序。
Pygame可移植性高,幾乎能在任何平臺(tái)和操作系統(tǒng)上運(yùn)行。
Pygame已經(jīng)被下載過數(shù)百萬次。
Pygame免費(fèi)開源。它在LGPL許可證(Lesser General Public License,GNU寬通用公共許可證)下發(fā)行。使用Pygame,你可以創(chuàng)造出免費(fèi)開源,可共享,或者商業(yè)化的游戲。詳情請(qǐng)見LGPL許可證。
優(yōu)點(diǎn)
-
能夠輕松使用多核CPU(multi core CPUs) :如今雙核CPU很常用,8核CPU在桌面系統(tǒng)中也很便宜,而利用好多核系統(tǒng),能讓你在你的游戲中實(shí)現(xiàn)更多東西。特定的pygame函數(shù)能夠釋放令人生畏的python GIL(全局解釋器鎖),這幾乎是你用C語言才能做的事。
-
核心函數(shù)用最優(yōu)化的C語言或匯編語言編寫:C語言代碼通常比Python代碼運(yùn)行速度快10-20倍。而匯編語言編寫的代碼(assembly code)比Python甚至快到100多倍。
-
安裝便捷:一般僅需包管理程序或二進(jìn)制系統(tǒng)程序便能安裝。
-
真正地可移植:支持Linux (主要發(fā)行版), Windows (95, 98, ME, 2000, XP, Vista, 64-bit Windows,), Windows CE, BeOS, MacOS, Mac OS X, FreeBSD, NetBSD, OpenBSD, BSD/OS, Solaris, IRIX, and QNX等操作系統(tǒng).也能支持AmigaOS, Dreamcast, Atari, AIX, OSF/Tru64, RISC OS, SymbianOS and OS/2,但是還沒有受到官方認(rèn)可。你也可以在手持設(shè)備,游戲控制臺(tái), One Laptop Per Child (OLPC) computer項(xiàng)目的電腦等設(shè)備中使用pygame.
-
用法簡(jiǎn)單:無論是小孩子還是大人都能學(xué)會(huì)用pygame來制作射擊類游戲。
-
很多Pygame游戲已發(fā)行:其中包括很多游戲大賽入圍作品、非常受歡迎的開源可分享的游戲。
-
由你來控制主循環(huán):由你來調(diào)用pygame的函數(shù),pygame的函數(shù)并不需要調(diào)用你的函數(shù)。當(dāng)你同時(shí)還在使用其他庫來編寫各種各種的程序時(shí),這能夠?yàn)槟闾峁O大的掌控權(quán)。
-
不需要GUI就能使用所有函數(shù):僅在命令行中,你就可以使用pygame的某些函數(shù)來處理圖片,獲取游戲桿輸入,播放音樂……
-
對(duì)bug反應(yīng)迅速:很多bug在被上報(bào)的1小時(shí)內(nèi)就能被我們修復(fù)。雖然有時(shí)候我們確實(shí)會(huì)卡在某一個(gè)bug上很久,但大多數(shù)時(shí)候我們都是很不錯(cuò)的bug修復(fù)者。如今bug的上報(bào)已經(jīng)很少了,因?yàn)樵S多bug早已被我們修復(fù)。
-
代碼量少:pygame并沒有數(shù)以萬計(jì)的也許你永遠(yuǎn)用不到的冗雜代碼。pygame的核心代碼一直保持著簡(jiǎn)潔特點(diǎn),其他附加物諸如GUI庫等,都是在核心代碼之外單獨(dú)設(shè)計(jì)研發(fā)的。
-
模塊化:你可以單獨(dú)使用pygame的某個(gè)模塊。想要換著使用一個(gè)別的聲音處理庫?沒問題。pygame的很多核心模塊支持獨(dú)立初始化與使用。
最小開發(fā)框架
import pygame,sys #sys是python的標(biāo)準(zhǔn)庫,提供Python運(yùn)行時(shí)環(huán)境變量的操控
pygame.init() #內(nèi)部各功能模塊進(jìn)行初始化創(chuàng)建及變量設(shè)置,默認(rèn)調(diào)用
size = width,height = 800,600 #設(shè)置游戲窗口大小,分別是寬度和高度
screen = pygame.display.set_mode(size) #初始化顯示窗口
pygame.display.set_caption("小游戲程序") #設(shè)置顯示窗口的標(biāo)題內(nèi)容,是一個(gè)字符串類型
while True: #無限循環(huán),直到Python運(yùn)行時(shí)退出結(jié)束
for event in pygame.event.get(): #從Pygame的事件隊(duì)列中取出事件,并從隊(duì)列中刪除該事件
if event.type == pygame.QUIT: #獲得事件類型,并逐類響應(yīng)
sys.exit() #用于退出結(jié)束游戲并退出
pygame.display.update() #對(duì)顯示窗口進(jìn)行更新,默認(rèn)窗口全部重繪
代碼執(zhí)行流程
4 具體實(shí)現(xiàn)
4.1 實(shí)現(xiàn)游戲精靈類
首先,讓我們確定一下游戲中有哪些元素。打地鼠打地鼠,地鼠當(dāng)然得有啦,那我們就寫個(gè)地鼠的游戲精靈類唄:
'''地鼠'''
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)各位老哥見諒)。然后我們?cè)賮矶x一下錘子這個(gè)游戲精靈類,和地鼠類似,錘子也有未錘下去和已錘下去兩種狀態(tài),只不過錘下去之后需要迅速恢復(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)
4.2 實(shí)現(xiàn)游戲主循環(huán)
OK,定義完游戲精靈之后,我們就可以開始寫主程序啦。首先自然是游戲初始化:
```python
'''游戲初始化'''
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ì)了,就不在文章里贅述一遍了,自己看注釋唄~)
# 加載背景音樂和其他音效
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)
# 地鼠改變位置的計(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)
每一部分我也都做了注釋,邏輯很簡(jiǎn)單,就不多廢話了。60s后,游戲結(jié)束,我們就可以統(tǒng)計(jì)分?jǐn)?shù)以及和歷史最高分做對(duì)比了:
# 讀取最佳分?jǐn)?shù)(try塊避免第一次游戲無.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()
4.3 制作簡(jiǎn)易的游戲開始和結(jié)束界面
為了使游戲看起來更“正式”,再隨手添個(gè)開始界面和結(jié)束界面唄:文章來源:http://www.zghlxwxcb.cn/news/detail-798160.html
'''游戲開始界面'''
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()
5 最后
項(xiàng)目獲取:https://gitee.com/sinonfin/system-sharing文章來源地址http://www.zghlxwxcb.cn/news/detail-798160.html
到了這里,關(guān)于python項(xiàng)目分享 打地鼠小游戲設(shè)計(jì)與實(shí)現(xiàn) (源碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!