pygame写一个俄罗斯方块
时间: 2023-12-23 22:03:59 浏览: 87
以下是一个使用pygame编写的俄罗斯方块小游戏的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口的宽度和高度
window_width = 800
window_height = 600
# 设置方块的大小
block_size = 30
# 设置游戏窗口的背景颜色
background_color = (255, 255, 255)
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("俄罗斯方块")
# 定义方块的形状
shapes = [
[[1, 1, 1, 1]],
[[1, 1], [1, 1]],
[[1, 1, 0], [0, 1, 1]],
[[0, 1, 1], [1, 1, 0]],
[[1, 1, 1], [0, 1, 0]],
[[1, 1, 1], [1, 0, 0]],
[[1, 1, 1], [0, 0, 1]]
]
# 定义方块的颜色
colors = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255),
(128, 128, 128)
]
# 定义方块类
class Block:
def __init__(self, shape, color):
self.shape = shape
self.color = color
self.x = window_width // 2 - block_size
self.y = 0
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 = list(zip(*self.shape[::-1]))
def draw(self):
for i in range(len(self.shape)):
for j in range(len(self.shape[i])):
if self.shape[i][j] == 1:
pygame.draw.rect(window, self.color, (self.x + j * block_size, self.y + i * block_size, block_size, block_size))
# 定义游戏面板类
class Panel:
def __init__(self):
self.blocks = []
def create_move_block(self):
shape = random.choice(shapes)
color = random.choice(colors)
block = Block(shape, color)
self.blocks.append(block)
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):
for block in self.blocks:
block.rotate()
def draw(self):
for block in self.blocks:
block.draw()
# 创建游戏面板对象
main_panel = Panel()
# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
main_panel.move_down()
elif event.key == pygame.K_LEFT:
main_panel.move_left()
elif event.key == pygame.K_RIGHT:
main_panel.move_right()
elif event.key == pygame.K_UP:
main_panel.rotate()
# 更新游戏窗口
window.fill(background_color)
main_panel.create_move_block()
main_panel.draw()
pygame.display.flip()
# 控制游戏帧率
clock.tick(10)
# 退出游戏
pygame.quit()
```
阅读全文