开心消消乐代码编写
时间: 2023-07-02 20:07:23 浏览: 108
以下是一个简单的开心消消乐游戏代码,使用 Python 和 Pygame 库:
```python
import pygame
import random
# 游戏区域的大小和方块的大小
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 640
BLOCK_SIZE = 40
# 游戏区域的位置
SCREEN_POS_X = 50
SCREEN_POS_Y = 50
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 初始化 Pygame 库
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH + SCREEN_POS_X * 2, SCREEN_HEIGHT + SCREEN_POS_Y * 2))
pygame.display.set_caption("Happy Elimination Game")
# 加载方块图片
block_images = []
for i in range(1, 7):
image = pygame.image.load(f"block_{i}.png").convert_alpha()
image = pygame.transform.scale(image, (BLOCK_SIZE, BLOCK_SIZE))
block_images.append(image)
# 定义方块类
class Block:
def __init__(self, x, y, color_index):
self.x = x
self.y = y
self.color_index = color_index
def draw(self):
screen.blit(block_images[self.color_index], (self.x, self.y))
# 生成初始方块矩阵
block_matrix = []
for i in range(10):
row = []
for j in range(10):
color_index = random.randint(0, 5)
block = Block(SCREEN_POS_X + j * BLOCK_SIZE, SCREEN_POS_Y + i * BLOCK_SIZE, color_index)
row.append(block)
block_matrix.append(row)
# 定义消除函数
def eliminate(blocks):
colors = set()
for block in blocks:
colors.add(block.color_index)
if len(colors) != 3:
return False
for block in blocks:
block.color_index = 6
return True
# 循环处理游戏事件
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
i = (y - SCREEN_POS_Y) // BLOCK_SIZE
j = (x - SCREEN_POS_X) // BLOCK_SIZE
if i < 0 or i >= 10 or j < 0 or j >= 10:
continue
blocks = []
if i > 0:
blocks.append(block_matrix[i-1][j])
if i < 9:
blocks.append(block_matrix[i+1][j])
if j > 0:
blocks.append(block_matrix[i][j-1])
if j < 9:
blocks.append(block_matrix[i][j+1])
blocks.append(block_matrix[i][j])
if eliminate(blocks):
for i in range(10):
for j in range(10):
if block_matrix[i][j].color_index == 6:
color_index = random.randint(0, 5)
block_matrix[i][j].color_index = color_index
# 绘制游戏界面
screen.fill(WHITE)
for i in range(10):
for j in range(10):
block_matrix[i][j].draw()
pygame.display.update()
```
游戏规则:玩家点击一个方块,如果它和上下左右四个方块中恰好有三个颜色相同,则这四个方块会被消除,同时它们上面的方块会下落填补空缺,最上面一行则会生成新的随机方块。游戏结束条件为无法再消除方块。