人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

使用python+pygame開發(fā)消消樂游戲附完整源碼

發(fā)布日期:2022-03-13 19:05 | 文章來(lái)源:腳本之家

效果是這樣的 ↓ ↓ ↓

一、環(huán)境要求

windows系統(tǒng),python3.6+ pip21+

開發(fā)環(huán)境搭建地址

一起來(lái)學(xué)pygame吧 游戲開發(fā)30例(開篇詞)——環(huán)境搭建+游戲效果展示

安裝游戲依賴模塊
pip install pygame

二、游戲簡(jiǎn)介

消消樂應(yīng)該大家都玩過(guò),或者看過(guò)。這個(gè)花里胡哨的小游戲

用python的pygame來(lái)實(shí)現(xiàn),很簡(jiǎn)單。

今天帶大家,用Python來(lái)實(shí)現(xiàn)一下這個(gè)花里胡哨的小游戲。

三、完整開發(fā)流程

1、項(xiàng)目主結(jié)構(gòu)

首先,先整理一下項(xiàng)目的主結(jié)構(gòu),其實(shí)看一下主結(jié)構(gòu),基本就清晰了

modules:相關(guān)定義的Python類位置
——game.py:主模塊
 
res:存放引用到的圖片、音頻等等
——audios:音頻資源
——imgs:圖片資源
——fonts:字體
 
cfg.py:為主配置文件
 
xxls.py:主程序文件
 
requirements.txt:需要引入的python依賴包

2、詳細(xì)配置

cfg.py

配置文件中,需要引入os模塊,并且配置打開游戲的屏幕大小。

'''主配置文件'''
import os
 
'''屏幕設(shè)置大小'''
SCREENSIZE = (700, 700)
'''元素尺寸'''
NUMGRID = 8
GRIDSIZE = 64
XMARGIN = (SCREENSIZE[0] - GRIDSIZE * NUMGRID) // 2
YMARGIN = (SCREENSIZE[1] - GRIDSIZE * NUMGRID) // 2
'''獲取根目錄'''
ROOTDIR = os.getcwd()
'''FPS'''
FPS = 30

3、消消樂所有圖形加載

game.py:第一部分

把整個(gè)項(xiàng)目放在一整個(gè)game.py模塊下了,把這個(gè)代碼文件拆開解讀一下。

拼圖精靈類:首先通過(guò)配置文件中,獲取方塊精靈的路徑,加載到游戲里。

定義move()移動(dòng)模塊的函數(shù),這個(gè)移動(dòng)比較簡(jiǎn)單。模塊之間,只有相鄰的可以相互移動(dòng)。

'''
Function:
 主游戲
'''
import sys
import time
import random
import pygame
 
 
'''拼圖精靈類'''
class pacerSprite(pygame.sprite.Sprite):
 def __init__(self, img_path, size, position, downlen, **kwargs):
  pygame.sprite.Sprite.__init__(self)
  self.image = pygame.image.load(img_path)
  self.image = pygame.transform.smoothscale(self.image, size)
  self.rect = self.image.get_rect()
  self.rect.left, self.rect.top = position
  self.downlen = downlen
  self.target_x = position[0]
  self.target_y = position[1] + downlen
  self.type = img_path.split('/')[-1].split('.')[0]
  self.fixed = False
  self.speed_x = 9
  self.speed_y = 9
  self.direction = 'down'
 def move(self):
 #下移
  if self.direction == 'down':
self.rect.top = min(self.target_y, self.rect.top+self.speed_y)
if self.target_y == self.rect.top:
 self.fixed = True
 #上移
  elif self.direction == 'up':
self.rect.top = max(self.target_y, self.rect.top-self.speed_y)
if self.target_y == self.rect.top:
 self.fixed = True
 #左移
  elif self.direction == 'left':
self.rect.left = max(self.target_x, self.rect.left-self.speed_x)
if self.target_x == self.rect.left:
 self.fixed = True
 #右移
  elif self.direction == 'right':
self.rect.left = min(self.target_x, self.rect.left+self.speed_x)
if self.target_x == self.rect.left:
 self.fixed = True
 '''獲取當(dāng)前坐標(biāo)'''
 def getPosition(self):
  return self.rect.left, self.rect.top
 '''設(shè)置星星坐標(biāo)'''
 def setPosition(self, position):
  self.rect.left, self.rect.top = position

4、隨機(jī)生成初始布局、相鄰消除、自動(dòng)下落

game.py 第二部分

設(shè)置游戲主窗口啟動(dòng)的標(biāo)題,設(shè)置啟動(dòng)游戲的主方法。

'''主游戲類'''
class pacerGame():
 def __init__(self, screen, sounds, font, pacer_imgs, cfg, **kwargs):
  self.info = 'pacer'
  self.screen = screen
  self.sounds = sounds
  self.font = font
  self.pacer_imgs = pacer_imgs
  self.cfg = cfg
  self.reset()
 '''開始游戲'''
 def start(self):
  clock = pygame.time.Clock()
  # 遍歷整個(gè)游戲界面更新位置
  overall_moving = True
  # 指定某些對(duì)象個(gè)體更新位置
  individual_moving = False
  # 定義一些必要的變量
  pacer_selected_xy = None
  pacer_selected_xy2 = None
  swap_again = False
  add_score = 0
  add_score_showtimes = 10
  time_pre = int(time.time())
  # 游戲主循環(huán)
  while True:
for event in pygame.event.get():
 if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
  pygame.quit()
  sys.exit()
 elif event.type == pygame.MOUSEBUTTONUP:
  if (not overall_moving) and (not individual_moving) and (not add_score):position = pygame.mouse.get_pos()if pacer_selected_xy is None:
pacer_selected_xy = self.checkSelected(position)else:
pacer_selected_xy2 = self.checkSelected(position)
if pacer_selected_xy2:
 if self.swappacer(pacer_selected_xy, pacer_selected_xy2):
  individual_moving = True
  swap_again = False
 else:
  pacer_selected_xy = None
if overall_moving:
 overall_moving = not self.droppacers(0, 0)
 # 移動(dòng)一次可能可以拼出多個(gè)3連塊
 if not overall_moving:
  res_match = self.isMatch()
  add_score = self.removeMatched(res_match)
  if add_score > 0:overall_moving = True
if individual_moving:
 pacer1 = self.getpacerByPos(*pacer_selected_xy)
 pacer2 = self.getpacerByPos(*pacer_selected_xy2)
 pacer1.move()
 pacer2.move()
 if pacer1.fixed and pacer2.fixed:
  res_match = self.isMatch()
  if res_match[0] == 0 and not swap_again:swap_again = Trueself.swappacer(pacer_selected_xy, pacer_selected_xy2)self.sounds['mismatch'].play()
  else:add_score = self.removeMatched(res_match)overall_moving = Trueindividual_moving = Falsepacer_selected_xy = Nonepacer_selected_xy2 = None
self.screen.fill((135, 206, 235))
self.drawGrids()
self.pacers_group.draw(self.screen)
if pacer_selected_xy:
 self.drawBlock(self.getpacerByPos(*pacer_selected_xy).rect)
if add_score:
 if add_score_showtimes == 10:
  random.choice(self.sounds['match']).play()
 self.drawAddScore(add_score)
 add_score_showtimes -= 1
 if add_score_showtimes < 1:
  add_score_showtimes = 10
  add_score = 0
self.remaining_time -= (int(time.time()) - time_pre)
time_pre = int(time.time())
self.showRemainingTime()
self.drawScore()
if self.remaining_time <= 0:
 return self.score
pygame.display.update()
clock.tick(self.cfg.FPS)

5、隨機(jī)初始化消消樂的主圖內(nèi)容

game.py 第三部分

詳細(xì)注釋,都寫在代碼里了。大家一定要看一遍,不要跑起來(lái),就不管了哦

'''初始化'''
 def reset(self):
  # 隨機(jī)生成各個(gè)塊(即初始化游戲地圖各個(gè)元素)
  while True:
self.all_pacers = []
self.pacers_group = pygame.sprite.Group()
for x in range(self.cfg.NUMGRID):
 self.all_pacers.append([])
 for y in range(self.cfg.NUMGRID):
  pacer = pacerSprite(img_path=random.choice(self.pacer_imgs), size=(self.cfg.GRIDSIZE, self.cfg.GRIDSIZE), position=[self.cfg.XMARGIN+x*self.cfg.GRIDSIZE, self.cfg.YMARGIN+y*self.cfg.GRIDSIZE-self.cfg.NUMGRID*self.cfg.GRIDSIZE], downlen=self.cfg.NUMGRID*self.cfg.GRIDSIZE)
  self.all_pacers[x].append(pacer)
  self.pacers_group.add(pacer)
if self.isMatch()[0] == 0:
 break
  # 得分
  self.score = 0
  # 拼出一個(gè)的獎(jiǎng)勵(lì)
  self.reward = 10
  # 時(shí)間
  self.remaining_time = 300
 '''顯示剩余時(shí)間'''
 def showRemainingTime(self):
  remaining_time_render = self.font.render('CountDown: %ss' % str(self.remaining_time), 1, (85, 65, 0))
  rect = remaining_time_render.get_rect()
  rect.left, rect.top = (self.cfg.SCREENSIZE[0]-201, 6)
  self.screen.blit(remaining_time_render, rect)
 '''顯示得分'''
 def drawScore(self):
  score_render = self.font.render('SCORE:'+str(self.score), 1, (85, 65, 0))
  rect = score_render.get_rect()
  rect.left, rect.top = (10, 6)
  self.screen.blit(score_render, rect)
 '''顯示加分'''
 def drawAddScore(self, add_score):
  score_render = self.font.render('+'+str(add_score), 1, (255, 100, 100))
  rect = score_render.get_rect()
  rect.left, rect.top = (250, 250)
  self.screen.blit(score_render, rect)
 '''生成新的拼圖塊'''
 def generateNewpacers(self, res_match):
  if res_match[0] == 1:
start = res_match[2]
while start > -2:
 for each in [res_match[1], res_match[1]+1, res_match[1]+2]:
  pacer = self.getpacerByPos(*[each, start])
  if start == res_match[2]:self.pacers_group.remove(pacer)self.all_pacers[each][start] = None
  elif start >= 0:pacer.target_y += self.cfg.GRIDSIZEpacer.fixed = Falsepacer.direction = 'down'self.all_pacers[each][start+1] = pacer
  else:pacer = pacerSprite(img_path=random.choice(self.pacer_imgs), size=(self.cfg.GRIDSIZE, self.cfg.GRIDSIZE), position=[self.cfg.XMARGIN+each*self.cfg.GRIDSIZE, self.cfg.YMARGIN-self.cfg.GRIDSIZE], downlen=self.cfg.GRIDSIZE)self.pacers_group.add(pacer)self.all_pacers[each][start+1] = pacer
 start -= 1
  elif res_match[0] == 2:
start = res_match[2]
while start > -4:
 if start == res_match[2]:
  for each in range(0, 3):pacer = self.getpacerByPos(*[res_match[1], start+each])self.pacers_group.remove(pacer)self.all_pacers[res_match[1]][start+each] = None
 elif start >= 0:
  pacer = self.getpacerByPos(*[res_match[1], start])
  pacer.target_y += self.cfg.GRIDSIZE * 3
  pacer.fixed = False
  pacer.direction = 'down'
  self.all_pacers[res_match[1]][start+3] = pacer
 else:
  pacer = pacerSprite(img_path=random.choice(self.pacer_imgs), size=(self.cfg.GRIDSIZE, self.cfg.GRIDSIZE), position=[self.cfg.XMARGIN+res_match[1]*self.cfg.GRIDSIZE, self.cfg.YMARGIN+start*self.cfg.GRIDSIZE], downlen=self.cfg.GRIDSIZE*3)
  self.pacers_group.add(pacer)
  self.all_pacers[res_match[1]][start+3] = pacer
 start -= 1
 '''移除匹配的pacer'''
 def removeMatched(self, res_match):
  if res_match[0] > 0:
self.generateNewpacers(res_match)
self.score += self.reward
return self.reward
  return 0
 '''游戲界面的網(wǎng)格繪制'''
 def drawGrids(self):
  for x in range(self.cfg.NUMGRID):
for y in range(self.cfg.NUMGRID):
 rect = pygame.Rect((self.cfg.XMARGIN+x*self.cfg.GRIDSIZE, self.cfg.YMARGIN+y*self.cfg.GRIDSIZE, self.cfg.GRIDSIZE, self.cfg.GRIDSIZE))
 self.drawBlock(rect, color=(0, 0, 255), size=1)
 '''畫矩形block框'''
 def drawBlock(self, block, color=(255, 0, 255), size=4):
  pygame.draw.rect(self.screen, color, block, size)
 '''下落特效'''
 def droppacers(self, x, y):
  if not self.getpacerByPos(x, y).fixed:
self.getpacerByPos(x, y).move()
  if x < self.cfg.NUMGRID - 1:
x += 1
return self.droppacers(x, y)
  elif y < self.cfg.NUMGRID - 1:
x = 0
y += 1
return self.droppacers(x, y)
  else:
return self.isFull()
 '''是否每個(gè)位置都有拼圖塊了'''
 def isFull(self):
  for x in range(self.cfg.NUMGRID):
for y in range(self.cfg.NUMGRID):
 if not self.getpacerByPos(x, y).fixed:
  return False
  return True
 '''檢查有無(wú)拼圖塊被選中'''
 def checkSelected(self, position):
  for x in range(self.cfg.NUMGRID):
for y in range(self.cfg.NUMGRID):
 if self.getpacerByPos(x, y).rect.collidepoint(*position):
  return [x, y]
  return None
 '''是否有連續(xù)一樣的三個(gè)塊(無(wú)--返回0/水平--返回1/豎直--返回2)'''
 def isMatch(self):
  for x in range(self.cfg.NUMGRID):
for y in range(self.cfg.NUMGRID):
 if x + 2 < self.cfg.NUMGRID:
  if self.getpacerByPos(x, y).type == self.getpacerByPos(x+1, y).type == self.getpacerByPos(x+2, y).type:return [1, x, y]
 if y + 2 < self.cfg.NUMGRID:
  if self.getpacerByPos(x, y).type == self.getpacerByPos(x, y+1).type == self.getpacerByPos(x, y+2).type:return [2, x, y]
  return [0, x, y]
 '''根據(jù)坐標(biāo)獲取對(duì)應(yīng)位置的拼圖對(duì)象'''
 def getpacerByPos(self, x, y):
  return self.all_pacers[x][y]
 '''交換拼圖'''
 def swappacer(self, pacer1_pos, pacer2_pos):
  margin = pacer1_pos[0] - pacer2_pos[0] + pacer1_pos[1] - pacer2_pos[1]
  if abs(margin) != 1:
return False
  pacer1 = self.getpacerByPos(*pacer1_pos)
  pacer2 = self.getpacerByPos(*pacer2_pos)
  if pacer1_pos[0] - pacer2_pos[0] == 1:
pacer1.direction = 'left'
pacer2.direction = 'right'
  elif pacer1_pos[0] - pacer2_pos[0] == -1:
pacer2.direction = 'left'
pacer1.direction = 'right'
  elif pacer1_pos[1] - pacer2_pos[1] == 1:
pacer1.direction = 'up'
pacer2.direction = 'down'
  elif pacer1_pos[1] - pacer2_pos[1] == -1:
pacer2.direction = 'up'
pacer1.direction = 'down'
  pacer1.target_x = pacer2.rect.left
  pacer1.target_y = pacer2.rect.top
  pacer1.fixed = False
  pacer2.target_x = pacer1.rect.left
  pacer2.target_y = pacer1.rect.top
  pacer2.fixed = False
  self.all_pacers[pacer2_pos[0]][pacer2_pos[1]] = pacer1
  self.all_pacers[pacer1_pos[0]][pacer1_pos[1]] = pacer2
  return True
 '''信息顯示'''
 def __repr__(self):
  return self.info

5、資源相關(guān)

包括游戲背景音頻、圖片和字體設(shè)計(jì)

res主資源目錄

audios:加載游戲背景音樂

fonts:記分牌相關(guān)字體

imgs:這里存放的是我們的各種小星星的圖形,是關(guān)鍵了的哦。如果這個(gè)加載不了,

我們的消消樂 就沒有任何圖形了

6、啟動(dòng)主程序

xxls.py

在主程序中,通過(guò)讀取配置文件,引入項(xiàng)目資源:包括圖片、音頻等,并從我們的modules里引入所有我們的模塊。

'''
Function:
 消消樂
'''
import os
import sys
import cfg
import pygame
from modules import *
 
 
'''主程序'''
def main():
 pygame.init()
 screen = pygame.display.set_mode(cfg.SCREENSIZE)
 pygame.display.set_caption('hacklex')
 # 加載背景音樂
 pygame.mixer.init()
 pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "res/audios/bg.mp3"))
 pygame.mixer.music.set_volume(0.6)
 pygame.mixer.music.play(-1)
 # 加載音效
 sounds = {}
 sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'res/audios/badswap.wav'))
 sounds['match'] = []
 for i in range(6):
  sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'res/audios/match%s.wav' % i)))
 
 # 字體顯示
 font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'res/font/font.TTF'), 25)
 # 星星
 pacer_imgs = []
 for i in range(1, 8):
  pacer_imgs.append(os.path.join(cfg.ROOTDIR, 'res/imgs/pacer%s.png' % i))
 # 循環(huán)
 game = pacerGame(screen, sounds, font, pacer_imgs, cfg)
 while True:
  score = game.start()
  flag = False
  # 給出選擇,玩家選擇重玩或者退出
  while True:
for event in pygame.event.get():
 if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
  pygame.quit()
  sys.exit()
 elif event.type == pygame.KEYUP and event.key == pygame.K_r:
  flag = True
if flag:
 break
screen.fill((136, 207, 236))
text0 = 'Final score: %s' % score
text1 = 'Press <R> to restart the game.'
text2 = 'Press <Esc> to quit the game.'
y = 150
for idx, text in enumerate([text0, text1, text2]):
 text_render = font.render(text, 1, (85, 65, 0))
 rect = text_render.get_rect()
 if idx == 0:
  rect.left, rect.top = (223, y)
 elif idx == 1:
  rect.left, rect.top = (133.5, y)
 else:
  rect.left, rect.top = (126.5, y)
 y += 99
 screen.blit(text_render, rect)
pygame.display.update()
  game.reset()
 
 
'''游戲運(yùn)行'''
if __name__ == '__main__':
 main()

四、如何啟動(dòng)游戲呢?

1、使用開發(fā)工具IDE啟動(dòng)

如果的開發(fā)工具IDE的環(huán)境

例如:VScode、sublimeText、notepad+

pycharm什么的配置了Python環(huán)境

可以直接在工具中,運(yùn)行該游戲。

2、命令行啟動(dòng)

如下圖所示

以上就是使用python開發(fā)消消樂游戲流程分析 附完整源碼的詳細(xì)內(nèi)容,更多關(guān)于python消消樂游戲的資料請(qǐng)關(guān)注本站其它相關(guān)文章!

香港服務(wù)器租用

版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部