俄罗斯方块这块游戏堪称经典,相信很多朋友小时候都玩过了。
今天,我们就用Python来写一个俄罗斯方块游戏。
# 导入必要的库
import pygame
import random
# 定义俄罗斯方块的形状
SHAPES = [
[[1, 1, 1, 1]],
[[1, 1], [1, 1]],
[[1, 1, 1], [0, 1, 0]],
[[1, 1, 1], [1, 0, 0]],
[[1, 1, 1], [0, 0, 1]],
[[1, 1, 1], [0, 1, 0]],
[[1, 1, 1], [1, 1, 0]]
]
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
# 颜色列表,对应不同形状
COLORS = [BLACK, RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA]
# 初始化pygame
pygame.init()
# 设置窗口尺寸
WIDTH, HEIGHT = 800, 600
GRID_SIZE = 30
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 创建时钟对象,用于控制游戏速度
clock = pygame.time.Clock()
# 生成随机形状
def generate_shape():
shape = random.choice(SHAPES)
color = random.randint(1, len(COLORS) - 1)
return shape, color
# 绘制网格
def draw_grid():
for x in range(0, WIDTH, GRID_SIZE):
pygame.draw.line(screen, GRAY, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, GRID_SIZE):
pygame.draw.line(screen, GRAY, (0, y), (WIDTH, y))
# 绘制形状
def draw_shape(shape, x, y, color):
for i in range(len(shape)):
for j in range(len(shape[i])):
if shape[i][j]:
pygame.draw.rect(screen, COLORS[color],
(x + j * GRID_SIZE, y + i * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# 检查形状是否可以移动到指定位置
def can_move(shape, x, y, grid):
for i in range(len(shape)):
for j in range(len(shape[i])):
if shape[i][j]:
if (x + j < 0 or x + j >= GRID_WIDTH or y + i >= GRID_HEIGHT or
(y + i >= 0 and grid[y + i][x + j])):
return False
return True
# 旋转形状
def rotate_shape(shape):
return list(map(list, zip(*reversed(shape))))
# 检查是否可以旋转到指定位置
def can_rotate(shape, x, y, grid):
rotated_shape = rotate_shape(shape)
return can_move(rotated_shape, x, y, grid)
# 清除满行
def clear_full_lines(grid):
full_lines = []
for i in range(len(grid)):
if all(grid[i]):
full_lines.append(i)
for line in full_lines:
del grid[line]
grid = [[0] * GRID_WIDTH] + grid
return grid
# 游戏主循环
def main():
running = True
grid = [[0] * GRID_WIDTH for _ in range(GRID_HEIGHT)]
current_shape, current_color = generate_shape()
current_x = GRID_WIDTH // 2 - len(current_shape[0]) // 2
current_y = 0
while running:
for
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。