文章目录
- 游戏页面
- 实现代码
游戏页面
左右键移动方块位置,上键切换方块形态。
实现代码
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义颜色
colors = [
(0, 0, 0), # 黑色
(255, 0, 0), # 红色
(0, 255, 0), # 绿色
(0, 0, 255), # 蓝色
(255, 255, 0), # 黄色
(255, 0, 255), # 紫色
(0, 255, 255) # 青色
]
# 俄罗斯方块形状
shapes = [
[[1, 1, 1, 1]],
[[1, 1],
[1, 1]],
[[0, 1, 1],
[1, 1, 0]],
[[1, 1, 0],
[0, 1, 1]],
[[1, 1, 1],
[0, 1, 0]],
[[1, 1, 1],
[1, 0, 0]],
[[1, 1, 1],
[0, 0, 1]]
]
# 设置游戏屏幕
screen_width = 300
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('俄罗斯方块')
# 游戏网格
grid = [[0 for _ in range(10)] for _ in range(20)]
# 初始化时钟
clock = pygame.time.Clock()
# 定义方块类
class Shape:
def __init__(self):
self.shape = random.choice(shapes)
self.color = random.randint(1, len(colors) - 1)
self.x = 3
self.y = 0
def rotate(self):
self.shape = [list(row) for row in zip(*self.shape[::-1])]
def draw(self):
for i, row in enumerate(self.shape):
for j, val in enumerate(row):
if val:
pygame.draw.rect(screen, colors[self.color], (self.x * 30 + j * 30, self.y * 30 + i * 30, 30, 30))
def check_collision(shape):
for i, row in enumerate(shape.shape):
for j, val in enumerate(row):
if val:
if shape.x + j < 0 or shape.x + j >= 10 or shape.y + i >= 20 or grid[shape.y + i][shape.x + j]:
return True
return False
def merge_shape(shape):
for i, row in enumerate(shape.shape):
for j, val in enumerate(row):
if val:
grid[shape.y + i][shape.x + j] = shape.color
def remove_full_lines():
global grid
grid = [row for row in grid if not all(row)]
while len(grid) < 20:
grid.insert(0, [0 for _ in range(10)])
def draw_grid():
for y in range(20):
for x in range(10):
pygame.draw.rect(screen, colors[grid[y][x]], (x * 30, y * 30, 30, 30))
def main():
running = True
current_shape = Shape()
fall_time = 0
while running:
screen.fill((0, 0, 0))
draw_grid()
current_shape.draw()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_shape.x -= 1
if check_collision(current_shape):
current_shape.x += 1
if event.key == pygame.K_RIGHT:
current_shape.x += 1
if check_collision(current_shape):
current_shape.x -= 1
if event.key == pygame.K_DOWN:
current_shape.y += 1
if check_collision(current_shape):
current_shape.y -= 1
if event.key == pygame.K_UP:
current_shape.rotate()
if check_collision(current_shape):
current_shape.rotate()
current_shape.rotate()
current_shape.rotate()
fall_time += clock.get_rawtime()
clock.tick()
if fall_time / 1000 >= 0.5:
fall_time = 0
current_shape.y += 1
if check_collision(current_shape):
current_shape.y -= 1
merge_shape(current_shape)
remove_full_lines()
current_shape = Shape()
if check_collision(current_shape):
running = False
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()