WIDTH = 600
HEIGHT = 600
NUMGRID = 8
GRIDSIZE = 64
XMARGIN = (WIDTH - GRIDSIZE * NUMGRID) // 2
YMARGIN = (HEIGHT - GRIDSIZE * NUMGRID) // 2
ROOTDIR = os.getcwd()
FPS = 30
1) 导入库:time计时,random生成随机数,pygame跨平台Python模块主要用于游戏图形化界面生成以及音频播放,config自己定义的相关变量
import time
import random
import pygame
from config import *
2) 定义拼图类
class gemSprite(pygame.sprite.Sprite):
主要有函数:
def __init__(self, img_path, size, position, downlen, **kwargs):
def move(self):
def getPosition(self):
def setPosition(self, position):
3) 定义游戏类:
class gemGame():
主要函数有:
def __init__(self, screen, sounds, font, gem_imgs, **kwargs):
def start(self):
def reset(self):
def showRemainingTime(self):
def drawScore(self):
def drawAddScore(self, add_score):
def generateNewGems(self, res_match):
def removeMatched(self, res_match):
def drawGrids(self):
def drawBlock(self, block, color=(255, 0, 255), size=4):
def dropGems(self, x, y):
def checkSelected(self, position):
def isMatch(self):
def swapGem(self, gem1_pos, gem2_pos):
1) 导入库
import os
import pygame
from utils import *
from config import *
2) 游戏主程序定义:
def main():
主要功能:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('消消乐')
# 加载背景音乐
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(ROOTDIR, "resources/audios/bg.mp3"))
pygame.mixer.music.set_volume(0.6)
pygame.mixer.music.play(-1)
# 加载音效
sounds = {}
sounds['mismatch'] = pygame.mixer.Sound(os.path.join(ROOTDIR, 'resources/audios/badswap.wav'))
sounds['match'] = []
for i in range(6):
sounds['match'].append(pygame.mixer.Sound(os.path.join(ROOTDIR, 'resources/audios/match%s.wav' % i)))
font = pygame.font.Font(os.path.join(ROOTDIR, 'resources/font.TTF'), 25)
gem_imgs = []
for i in range(1, 8):
gem_imgs.append(os.path.join(ROOTDIR, 'resources/images/gem%s.png' % i))
game = gemGame(screen, sounds, font, gem_imgs)
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((135, 206, 235))
text0 = 'Final score: %s' % score
text1 = 'Press to restart the game.'
text2 = 'Press 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 = (212, y)
elif idx == 1:
rect.left, rect.top = (122.5, y)
else:
rect.left, rect.top = (126.5, y)
y += 100
screen.blit(text_render, rect)
pygame.display.update()
game.reset()
if __name__ == '__main__':
main()