使用pygame制作消消乐游戏
时间: 2023-12-25 18:04:17 浏览: 128
好的,下面是一个使用Pygame制作消消乐游戏的示例代码。这个示例代码包括了游戏的基本逻辑和界面设计,你可以在此基础上进行修改和扩展。
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
WINDOW_SIZE = (400, 500)
window = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("消消乐游戏")
# 定义游戏区域的大小和位置
BOARD_SIZE = (300, 300)
BOARD_LEFT = (WINDOW_SIZE[0] - BOARD_SIZE[0]) // 2
BOARD_TOP = 100
# 定义方块的大小和间隔
BLOCK_SIZE = 40
BLOCK_GAP = 5
# 定义方块的颜色
COLORS = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255),
]
# 定义游戏区域的矩形
board_rect = pygame.Rect(BOARD_LEFT, BOARD_TOP, BOARD_SIZE[0], BOARD_SIZE[1])
# 定义一个二维数组来存储方块的颜色
board = [[random.choice(COLORS) for j in range(BOARD_SIZE[0] // (BLOCK_SIZE + BLOCK_GAP))] for i in range(BOARD_SIZE[1] // (BLOCK_SIZE + BLOCK_GAP))]
# 定义一个函数来绘制方块
def draw_block(x, y, color):
block_rect = pygame.Rect(BOARD_LEFT + x * (BLOCK_SIZE + BLOCK_GAP), BOARD_TOP + y * (BLOCK_SIZE + BLOCK_GAP), BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(window, color, block_rect)
# 定义一个函数来检查是否有可以消除的方块
def check_matches():
matches = []
for i in range(len(board)):
for j in range(len(board[i])):
color = board[i][j]
if color != None:
if i < len(board) - 2 and board[i+1][j] == color and board[i+2][j] == color:
matches.append((j, i, 0))
if j < len(board[i]) - 2 and board[i][j+1] == color and board[i][j+2] == color:
matches.append((j, i, 1))
return matches
# 定义一个函数来消除方块
def remove_blocks(matches):
for match in matches:
x, y, direction = match
if direction == 0:
board[y][x] = None
board[y+1][x] = None
board[y+2][x] = None
elif direction == 1:
board[y][x] = None
board[y][x+1] = None
board[y][x+2] = None
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# 获取鼠标点击的位置
x, y = event.pos
# 如果鼠标点击在游戏区域内
if board_rect.collidepoint(x, y):
# 计算方块的索引
block_x = (x - BOARD_LEFT) // (BLOCK_SIZE + BLOCK_GAP)
block_y = (y - BOARD_TOP) // (BLOCK_SIZE + BLOCK_GAP)
# 如果方块存在
if board[block_y][block_x] != None:
# 将方块标记为None
board[block_y][block_x] = None
# 检查是否有可以消除的方块
matches = check_matches()
while len(matches) > 0:
# 消除方块
remove_blocks(matches)
# 将上方的方块掉落下来
for i in range(len(board)-1, 0, -1):
for j in range(len(board[i])):
if board[i][j] == None:
board[i][j], board[i-1][j] = board[i-1][j], None
# 在上方生成新的方块
for j in range(len(board[0])):
if board[0][j] == None:
board[0][j] = random.choice(COLORS)
# 再次检查是否有可以消除的方块
matches = check_matches()
# 绘制背景
window.fill((255, 255, 255))
# 绘制游戏区域的背景
pygame.draw.rect(window, (200, 200, 200), board_rect)
# 绘制方块
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] != None:
draw_block(j, i, board[i][j])
# 更新屏幕
pygame.display.flip()
# 退出Pygame
pygame.quit()
```
在这个示例代码中,我们使用Pygame创建了一个名为"消消乐游戏"的窗口,并在窗口中绘制了一个游戏区域和方块。玩家可以通过点击方块来消除它们,如果有三个或以上颜色相同的方块相连,则它们将被消除。在消除方块后,上方的方块将掉落下来,同时在上方生成新的方块。我们还使用了随机函数来生成方块的颜色。
阅读全文