用python写一个俄罗斯方块代码,并附上简单注释
时间: 2024-01-08 18:47:36 浏览: 77
python编写俄罗斯方块
以下是一个简单的俄罗斯方块游戏代码,注释在代码中:
```python
import pygame
import random
# 初始化 pygame 模块
pygame.init()
# 定义窗口大小
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500
# 定义方块大小
BLOCK_SIZE = 20
# 定义游戏区域大小
GAME_WIDTH = 10 * BLOCK_SIZE
GAME_HEIGHT = 20 * BLOCK_SIZE
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 创建窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 创建字体对象
font = pygame.font.Font(None, 36)
# 定义方块形状
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]],
[[7, 7, 7, 7]]
]
# 定义方块颜色
COLORS = [
BLUE,
YELLOW,
GREEN,
RED,
WHITE,
YELLOW,
BLUE
]
# 定义方块类型数量
SHAPE_COUNT = len(SHAPES)
# 定义方块初始位置
INITIAL_POSITION = (GAME_WIDTH // 2 - BLOCK_SIZE * 2, 0)
# 定义方块下落速度
FALL_SPEED = 500
# 定义方块移动速度
MOVE_SPEED = 100
# 定义方块旋转速度
ROTATE_SPEED = 100
# 定义游戏结束状态
GAME_OVER = False
# 定义得分
score = 0
# 创建方块类
class Block:
def __init__(self, shape, color, position):
self.shape = shape
self.color = color
self.position = list(position)
self.rotation = 0
# 绘制方块
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(window, self.color, (self.position[0] + j * BLOCK_SIZE, self.position[1] + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
# 移动方块
def move(self, direction):
if direction == "left":
self.position[0] -= BLOCK_SIZE
elif direction == "right":
self.position[0] += BLOCK_SIZE
elif direction == "down":
self.position[1] += BLOCK_SIZE
# 旋转方块
def rotate(self):
self.rotation = (self.rotation + 1) % len(self.shape)
self.shape = list(zip(*self.shape[::-1]))
# 判断方块是否超出边界
def is_out_of_bounds(self, direction):
if direction == "left":
return self.position[0] < 0
elif direction == "right":
return self.position[0] + len(self.shape[0]) * BLOCK_SIZE > GAME_WIDTH
elif direction == "down":
return self.position[1] + len(self.shape) * BLOCK_SIZE > GAME_HEIGHT
# 判断方块是否与其他方块重叠
def is_colliding(self, blocks):
for block in blocks:
for i in range(len(self.shape)):
for j in range(len(self.shape[i])):
if self.shape[i][j] != 0 and block.shape[i + self.position[1] // BLOCK_SIZE][j + self.position[0] // BLOCK_SIZE] != 0:
return True
return False
# 创建方块工厂类
class BlockFactory:
def __init__(self):
self.blocks = []
# 创建新方块
def create_block(self):
shape = SHAPES[random.randint(0, SHAPE_COUNT - 1)]
color = COLORS[random.randint(0, SHAPE_COUNT - 1)]
position = INITIAL_POSITION
block = Block(shape, color, position)
if block.is_colliding(self.blocks):
global GAME_OVER
GAME_OVER = True
else:
self.blocks.append(block)
return block
# 绘制所有方块
def draw_blocks(self):
for block in self.blocks:
block.draw()
# 移动当前方块
def move_current_block(self, direction):
current_block = self.blocks[-1]
if not current_block.is_out_of_bounds(direction) and not current_block.is_colliding(self.blocks[:-1]):
current_block.move(direction)
# 旋转当前方块
def rotate_current_block(self):
current_block = self.blocks[-1]
if not current_block.is_colliding(self.blocks[:-1]):
current_block.rotate()
# 下落当前方块
def fall_current_block(self):
current_block = self.blocks[-1]
if not current_block.is_out_of_bounds("down") and not current_block.is_colliding(self.blocks[:-1]):
current_block.move("down")
else:
self.create_block()
# 判断是否有一行已经被填满
def check_full_rows(self):
full_rows = []
for i in range(GAME_HEIGHT // BLOCK_SIZE):
row_blocks = [block for block in self.blocks if block.position[1] == i * BLOCK_SIZE]
if len(row_blocks) == GAME_WIDTH // BLOCK_SIZE:
full_rows.append(i)
return full_rows
# 移除已经被填满的行
def remove_full_rows(self):
full_rows = self.check_full_rows()
if len(full_rows) > 0:
for block in self.blocks[:]:
if block.position[1] // BLOCK_SIZE in full_rows:
self.blocks.remove(block)
global score
score += 10
elif block.position[1] // BLOCK_SIZE < min(full_rows):
block.move("down")
# 创建方块工厂对象
block_factory = BlockFactory()
# 创建时钟对象
clock = pygame.time.Clock()
# 游戏循环
while not GAME_OVER:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
GAME_OVER = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
block_factory.move_current_block("left")
elif event.key == pygame.K_RIGHT:
block_factory.move_current_block("right")
elif event.key == pygame.K_DOWN:
block_factory.fall_current_block()
elif event.key == pygame.K_SPACE:
block_factory.rotate_current_block()
# 绘制背景
window.fill(BLACK)
# 绘制游戏区域
pygame.draw.rect(window, WHITE, (0, 0, GAME_WIDTH, GAME_HEIGHT), 5)
# 绘制所有方块
block_factory.draw_blocks()
# 移除已经被填满的行
block_factory.remove_full_rows()
# 绘制得分
score_text = font.render("Score: {}".format(score), True, WHITE)
window.blit(score_text, (10, GAME_HEIGHT + 10))
# 更新屏幕
pygame.display.update()
# 控制方块下落速度
if pygame.time.get_ticks() % FALL_SPEED == 0:
block_factory.fall_current_block()
# 控制方块移动速度
if pygame.time.get_ticks() % MOVE_SPEED == 0:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
block_factory.move_current_block("left")
elif keys[pygame.K_RIGHT]:
block_factory.move_current_block("right")
# 控制方块旋转速度
if pygame.time.get_ticks() % ROTATE_SPEED == 0:
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
block_factory.rotate_current_block()
# 控制帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
阅读全文