python写一个可直接运行的俄罗斯方块
时间: 2023-03-02 13:24:55 浏览: 117
好的,以下是一个Python编写的可直接运行的俄罗斯方块游戏。
```python
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 600
# 游戏区域大小
PLAY_WIDTH = 300
PLAY_HEIGHT = 600
# 方块大小
BLOCK_SIZE = 30
# 游戏区域左上角坐标
PLAY_X = (WINDOW_WIDTH - PLAY_WIDTH) // 2
PLAY_Y = WINDOW_HEIGHT - PLAY_HEIGHT
# 方块形状
SHAPES = [
(0, 1, 2, 3), # I
(1, 2, 3, 4), # L
(0, 1, 2, 4), # J
(0, 1, 3, 4), # Z
(1, 2, 4, 5), # S
(0, 2, 3, 4), # T
(0, 1, 4, 5) # O
]
# 方块颜色
COLORS = [
(0, 255, 255), # I
(255, 165, 0), # L
(0, 0, 255), # J
(255, 0, 0), # Z
(0, 255, 0), # S
(128, 0, 128), # T
(255, 255, 0) # O
]
# 方块移动速度
SPEED = 5
# 初始化Pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 创建时钟对象
clock = pygame.time.Clock()
class Block:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
self.color = COLORS[SHAPES.index(shape)]
def draw(self):
for i in range(4):
pygame.draw.rect(screen, self.color, (PLAY_X + (self.x + i) * BLOCK_SIZE, PLAY_Y + self.y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
def move(self, dx, dy):
if self.x + dx < 0 or self.x + dx + 4 > PLAY_WIDTH // BLOCK_SIZE or self.y + dy + 1 > PLAY_HEIGHT // BLOCK_SIZE:
return False
for i in range(4):
if (self.y + dy) * PLAY_WIDTH // BLOCK_SIZE + self.x + dx + i in occupied:
return False
self.x += dx
self.y += dy
return True
def rotate(self):
new_shape = []
for i in range(16):
if i % 4 == 0:
row = []
for j in range(4):
row.append(self.shape[3 - j * 4 + i // 4])
new_shape += row
new_x = self.x
while new_x + 3 >= PLAY_WIDTH // BLOCK_SIZE:
new_x -= 1
if new_x < 0:
new_x = 0
if (self.y + 1) *
阅读全文