- 运行结果显示
- 代码如下
import pygame
import random
# 初始化pygame
pygame. init()
# 定义一些常量
WIDTH = 600
HEIGHT = 600
NUM_GRID=8
GRID_SIZE = WIDTH // NUM_GRID
FPS= 30
# 定义颜色
WHITE =(255, 255,255)
BLACK=(0,0,0)
COLORS = [(255, 0, 0),(0, 255,0),
(0,0,255),(255,255,0),(0,255,255),(255,0,255)]
# 创建游戏窗口
screen
pygame.display.set_mode((WIDTH HEIGHT))
pygame.display.set_caption('开心消消乐')
# 游戏元素类
class Gem:
def init__(self, x, y, color): self.x=x
self.y=y
self.color= color
def draw(self):
pygame.draw.rect(screen,
self.color (self.x * GRID SIZE self y * GRID_SIZE, GRID_SIZE,GRID_SIZE))
# 生成游戏元素
def generate_gems():
gems =[]
for i in range(NUM_GRID):
row=[]
for j in range(NUM_GRID):
color=[]
random.choice(COLORS)
gem = Gem(i, j, color)
row.append(gem)
gems.append(row)
return gems
# 绘制游戏界面
def draw_game(gems):
screen. fill(WHITE)
for row in gems:
for gem in row:
gem draw()
pygame.display.flip()
# 判断两个元素是否相邻
def is_adjacent(gem1, gem2):
return abs(gem1.x - gem2.x) +abs(gem1.y - gem2.y) ==1
#判断是否有连续三个及以上相同颜色的元素def check matches(gems):
matches =[]
#检查水平方向的匹配
for i in range(NUM_GRID): for j in range(NUM_GRID -2):
gem1 = gems[i][j]
gem2 = gems[i][j j + 1]
gem3 = gems[i][j+ 2]
if gem1.color ==
gem2.color == gem3.color:
match = [(i, j),(i,j + 1),(i,j + 2)]
matches. append(match)
#检查垂直方向的匹配
for i in range(NUM_GRID - 2):for j in range(NUM_GRID):gem1 = gems[i][j]
gem2 = gems[i +1][j]
gem3 = gems[i + 2][j]
if gem1.color ==
gem2.color ==gem3.color:
match = [(i, j),(i+ 1, j),(i + 2, i)]
matches.append(mach)
return matches# 消除匹配的元素
def remove_matches(gems, matches):
for match in matches:
for pos in match:
i, j = pos
gems[i][j] = None
# 下落剩余的元素
for j in range(NUM_GRID):
empty_spaces = 0
for i in range(NUM_GRID - 1, -1,-1):
if gems[i][j] is None:
empty_spaces += 1
else:
gems [i +empty_spaces][j] = gems[i][j] if empty_spaces > 0:
gems[i][j] =None
# 游戏主循环
def game_loop( ):
clock = pygame. time.Clock( )gems = generate_gems()
running = True
while running:
for event in
pygame.event.get():
if event.type ==
pygame QUIT:
running = False
matches =
check_matches(gems)
if matches:
remove_matches(gems
matches)
gems generate_gems
draw_game(gems)
clock.tick(FPS)
pygame.quit()
if__name___ == "__main___" :
game_loop()
- 知识点总结
1. 首先初始化 pygame ,定义了游戏窗口的大小、网格数量、网格大小等常量以及颜色列表。
2. 创建了 Gem 类来表示游戏中的元素,包含元素的位置和颜色信息,以及绘制方法。
3. generate_gems 函数用于随机生成游戏元素。
4. draw_game 函数用于绘制游戏界面,将每个元素绘制到屏幕上。
5. is_adjacent 函数用于判断两个元素是否相邻,这在后续的元素交换逻辑中会用到。
6. check_matches 函数用于检查是否有连续三个及以上相同颜色的元素,如果有则返回匹配的位置列表。
7. remove_matches 函数用于消除匹配的元素,并使剩余的元素下落。
8. game_loop 函数是游戏的主循环,不断处理事件、检查匹配、绘制游戏界面,直到游戏退出。