import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小
window_width = 400
window_height = 600
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("俄罗斯方块")
# 定义方块大小和颜色
block_size = 30
block_color = (255, 255, 255)
# 定义方块形状
shapes = [
[[1, 1, 1], [0, 1, 0]],
[[0, 2, 2], [2, 2, 0]],
[[3, 3, 0], [0, 3, 3]],
[[4, 0, 0], [4, 4, 4]],
[[0, 0, 5], [5, 5, 5]],
[[6, 6], [6, 6]]
]
# 定义方块移动速度
speed = 0.5
# 定义游戏状态
game_over = False
# 定义方块类
class Block:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
def draw(self):
for i in range(len(self.shape)):
for j in range(len(self.shape[i])):
if self.shape[i][j] != 0:
pygame.draw.rect(game_window, block_color, (self.x+j*block_size, self.y+i*block_size, block_size, block_size))
def move_down(self):
self.y += block_size
def move_left(self):
self.x -= block_size
def move_right(self):
self.x += block_size
def rotate(self):
self.shape = [[self.shape[j][i] for j in range(len(self.shape))] for i in range(len(self.shape[0])-1, -1, -1)]
# 创建一个新方块
def new_block():
shape = random.choice(shapes)
block = Block(window_width/2-block_size, 0, shape)
return block
# 主循环
current_block = new_block()
clock = pygame.time.Clock()
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_block.move_left()
if event.key == pygame.K_RIGHT:
current_block.move_right()
if event.key == pygame.K_UP:
current_block.rotate()
game_window.fill((0, 0, 0))
# 绘制当前方块
current_block.draw()
# 移动当前方块
if pygame.time.get_ticks()/1000 > speed:
current_block.move_down()
pygame.time.set_timer(pygame.USEREVENT, 0)
pygame.time.set_timer(pygame.USEREVENT, int(speed*1000))
# 检查是否碰撞到边界或其他方块
if current_block.y >= window_height-block_size*2:
current_block = new_block()
pygame.display.update()
clock.tick(60)
# 结束游戏
pygame.quit()