Python 俄罗斯方块游戏代码:入门教程
以下是一个简单的俄罗斯方块游戏的 Python 代码:
import pygame
import random
# 游戏界面的宽度和高度
WIDTH, HEIGHT = 800, 600
# 方块的大小
BLOCK_SIZE = 30
# 方块的形状
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, 0], [0, 1, 1]],
[[0, 1, 1], [1, 1, 0]]
]
# 方块的颜色
COLORS = [
(0, 0, 0),
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255)
]
# 初始化pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置窗口标题
pygame.display.set_caption('俄罗斯方块')
# 获取一个随机的方块形状和颜色
def get_random_shape():
shape = random.choice(SHAPES)
color = random.choice(COLORS)
return shape, color
# 绘制方块
def draw_block(x, y, color):
pygame.draw.rect(screen, color, (x, y, BLOCK_SIZE, BLOCK_SIZE))
# 绘制方块矩阵
def draw_shape(x, y, shape, color):
for i in range(len(shape)):
for j in range(len(shape[i])):
if shape[i][j] == 1:
draw_block(x + j * BLOCK_SIZE, y + i * BLOCK_SIZE, color)
# 主游戏循环
def main():
# 初始方块的位置
x, y = WIDTH // 2, 0
# 获取一个随机的方块形状和颜色
shape, color = get_random_shape()
clock = pygame.time.Clock()
running = True
while running:
# 设置帧率
clock.tick(5)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 按下方向键向下移动方块
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
y += BLOCK_SIZE
# 绘制游戏界面
screen.fill((255, 255, 255))
draw_shape(x, y, shape, color)
pygame.display.flip()
# 判断方块是否到达底部
if y + len(shape) * BLOCK_SIZE >= HEIGHT:
# 获取一个新的随机方块
shape, color = get_random_shape()
# 重置方块的位置
x, y = WIDTH // 2, 0
# 更新方块的位置
y += BLOCK_SIZE
# 退出游戏
pygame.quit()
# 运行游戏
if __name__ == '__main__':
main()
这个代码使用了 pygame 库来创建游戏窗口和处理游戏事件。游戏界面的宽度和高度分别为 800 和 600,方块的大小为 30。方块的形状和颜色通过 SHAPES 和 COLORS 列表来定义。游戏界面使用白色填充,方块使用颜色来绘制。游戏循环中,根据用户的输入和方块的位置来更新方块的位置,并判断方块是否到达底部。当方块到达底部时,获取一个新的随机方块并重置方块的位置。
原文地址: https://www.cveoy.top/t/topic/o6DO 著作权归作者所有。请勿转载和采集!