给我一个俄罗斯方块的Python代码
时间: 2023-11-21 19:08:01 浏览: 60
以下是一个简单的俄罗斯方块的 Python 代码:
```python
import pygame
import random
pygame.init()
# 定义一些常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
GRID_WIDTH = 10
GRID_HEIGHT = 20
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 加载方块图片
block_image = pygame.Surface((BLOCK_SIZE, BLOCK_SIZE))
block_image.fill(WHITE)
# 定义方块类
class Block:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
def draw(self):
rect = pygame.Rect(self.x * BLOCK_SIZE, self.y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)
screen.blit(block_image, rect)
pygame.draw.rect(screen, self.color, rect, 1)
def move_down(self):
self.y += 1
def move_left(self):
self.x -= 1
def move_right(self):
self.x += 1
# 定义方块组合类
class BlockGroup:
def __init__(self, blocks):
self.blocks = blocks
def draw(self):
for block in self.blocks:
block.draw()
def move_down(self):
for block in self.blocks:
block.move_down()
def move_left(self):
for block in self.blocks:
block.move_left()
def move_right(self):
for block in self.blocks:
block.move_right()
def rotate(self):
center_x = self.blocks[0].x
center_y = self.blocks[0].y
for block in self.blocks[1:]:
x_diff = block.x - center_x
y_diff = block.y - center_y
block.x = center_x - y_diff
block.y = center_y + x_diff
# 定义方块工厂类
class BlockFactory:
def __init__(self):
self.colors = [RED, GREEN, BLUE]
def create_block(self):
x = random.randint(0, GRID_WIDTH - 1)
y = 0
color = random.choice(self.colors)
blocks = [
Block(x, y, color),
Block(x + 1, y, color),
Block(x, y + 1, color),
Block(x + 1, y + 1, color)
]
return BlockGroup(blocks)
# 初始化游戏
block_factory = BlockFactory()
current_block = block_factory.create_block()
# 游戏循环
clock = pygame.time.Clock()
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 移动方块
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
current_block.move_left()
elif keys[pygame.K_RIGHT]:
current_block.move_right()
elif keys[pygame.K_DOWN]:
current_block.move_down()
elif keys[pygame.K_SPACE]:
current_block.rotate()
# 绘制界面
screen.fill(BLACK)
current_block.draw()
pygame.display.flip()
# 延迟一定时间
clock.tick(30)
```
该代码使用了 Pygame 库来实现游戏界面和事件处理。游戏中的方块和方块组合都是使用 Block 类和 BlockGroup 类来表示的。BlockFactory 类用于生成随机的方块组合。游戏循环中处理了方块的移动和旋转,以及界面的绘制。
阅读全文