初始化Pygame:使用pygame.init()来初始化Pygame库。
定义屏幕尺寸和颜色:设置了屏幕的宽度、高度和方块的大小,并定义了使用的颜色。
形状定义:定义了所有的俄罗斯方块形状以及对应的颜色。
方块类:定义了一个Block类,负责处理方块的绘制、移动和旋转。
主游戏循环:在main函数中实现了主游戏循环,处理事件、更新方块位置、绘制屏幕内容并控制游戏速度。
import pygame
import random
# 初始化Pygame
pygame.init()
# 屏幕尺寸
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# 颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
ORANGE = (255, 165, 0)
# 形状定义
SHAPES = [
[[1, 1, 1, 1]], # I
[[1, 1, 1], [0, 1, 0]], # T
[[1, 1, 1], [1, 0, 0]], # L
[[1, 1, 1], [0, 0, 1]], # J
[[1, 1], [1, 1]], # O
[[0, 1, 1], [1, 1, 0]], # S
[[1, 1, 0], [0, 1, 1]] # Z
]
# 形状颜色
SHAPE_COLORS = [CYAN, BLUE, ORANGE, YELLOW, GREEN, RED, MAGENTA]
# 初始化屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 定义方块类
class Block:
def __init__(self, shape):
self.shape = shape
self.color = random.choice(SHAPE_COLORS)
self.x = SCREEN_WIDTH // 2 // BLOCK_SIZE
self.y = 0
def draw(self, surface):
for i, row in enumerate(self.shape):
for j, val in enumerate(row):
if val == 1:
pygame.draw.rect(surface, self.color,
pygame.Rect((self.x + j) * BLOCK_SIZE, (self.y + i) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
def move(self, dx, dy):
self.x += dx
self.y += dy
def rotate(self):
self.shape = [list(row) for row in zip(*self.shape[::-1])]
# 主游戏循环
def main():
clock = pygame.time.Clock()
grid = [[BLACK for _ in range(SCREEN_WIDTH // BLOCK_SIZE)] for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)]
current_block = Block(random.choice(SHAPES))
running = True
while running:
screen.fill(BLACK)
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_block.move(-1, 0)
if event.key == pygame.K_RIGHT:
current_block.move(1, 0)
if event.key == pygame.K_DOWN:
current_block.move(0, 1)
if event.key == pygame.K_UP:
current_block.rotate()
current_block.move(0, 1)
# 绘制当前方块
current_block.draw(screen)
# 更新显示
pygame.display.flip()
# 控制游戏速度
clock.tick(10)
pygame.quit()
if __name__ == "__main__":
main()
运行效果: