python俄罗斯方块源程序
时间: 2023-10-26 12:08:39 浏览: 175
我可以为您提供一个基于 Python 的俄罗斯方块源程序,您可以在此基础上进行修改和优化。以下是代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏区域大小
WIDTH = 300
HEIGHT = 600
# 方块大小
BLOCK_SIZE = 30
# 方块种类及其形状
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]]
]
# 方块颜色
COLORS = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255)
]
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 创建字体对象
font = pygame.font.SysFont(None, 30)
# 创建时钟对象
clock = pygame.time.Clock()
# 定义方块类
class Block:
def __init__(self):
self.shape = random.choice(SHAPES)
self.color = random.choice(COLORS)
self.x = WIDTH // 2 - BLOCK_SIZE
self.y = 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(screen, self.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]))]
# 翻转后如果超出边界,则向左或向右移动
if self.x < 0:
self.x = 0
elif self.x + len(self.shape[0]) * BLOCK_SIZE > WIDTH:
self.x = WIDTH - len(self.shape[0]) * BLOCK_SIZE
# 定义游戏类
class Game:
def __init__(self):
self.score = 0
self.block = Block()
self.blocks = []
def draw(self):
screen.fill((255, 255, 255))
for block in self.blocks:
block.draw()
self.block.draw()
# 绘制分数
score_text = font.render("Score: " + str(self.score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
def update(self):
# 方块下落
if not self.check_collision(self.block, 0, BLOCK_SIZE):
self.block.move_down()
else:
self.blocks.append(self.block)
self.block = Block()
# 消除满行
for y in range(HEIGHT - BLOCK_SIZE, 0, -BLOCK_SIZE):
if all([(x, y) in [(block.x, block.y) for block in self.blocks] for x in range(0, WIDTH, BLOCK_SIZE)]):
self.blocks = [block for block in self.blocks if block.y != y]
self.score += 10
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and not self.check_collision(self.block, -BLOCK_SIZE, 0):
self.block.move_left()
elif event.key == pygame.K_RIGHT and not self.check_collision(self.block, BLOCK_SIZE, 0):
self.block.move_right()
elif event.key == pygame.K_UP:
self.block.rotate()
def check_collision(self, block, dx, dy):
for i in range(len(block.shape)):
for j in range(len(block.shape[i])):
if block.shape[i][j] != 0:
x = block.x + j * BLOCK_SIZE + dx
y = block.y + i * BLOCK_SIZE + dy
if x < 0 or x >= WIDTH or y >= HEIGHT or (x, y) in [(b.x, b.y) for b in self.blocks]:
return True
return False
# 创建游戏对象
game = Game()
# 游戏循环
while True:
game.update()
game.draw()
pygame.display.update()
clock.tick(30)
# 相关问题:
阅读全文