王剑编程网

分享专业编程知识与实战技巧

一个使用 Python 和 Pygame 库编写的简单俄罗斯方块游戏代码示例

```python

import pygame

import random


初始化 Pygame

pygame.init()


定义常量

WIDTH, HEIGHT = 300, 600

BLOCK_SIZE = 30

GRID_WIDTH = WIDTH // BLOCK_SIZE

GRID_HEIGHT = HEIGHT // BLOCK_SIZE


颜色定义

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

COLORS = [(0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 165, 0), (255, 0, 0), (128, 0, 128), (0, 255, 255)]


定义形状

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]]

]


创建游戏窗口

screen = pygame.display.set_mode((WIDTH, HEIGHT))


pygame.display.set_caption("俄罗斯方块")


初始化网格

grid = [[0] * GRID_WIDTH for _ in range(GRID_HEIGHT)]


class Tetromino:

def __init__(self):

self.shape = random.choice(SHAPES)

self.color = random.choice(COLORS)

self.x = GRID_WIDTH // 2 - len(self.shape[0]) // 2

self.y = 0


def move_down(self):

if self.can_move(0, 1):

self.y += 1

else:

self.lock()

return True

return False


def move_left(self):

if self.can_move(-1, 0):

self.x -= 1


def move_right(self):

if self.can_move(1, 0):

self.x += 1


def rotate(self):

rotated_shape = list(map(list, zip(*self.shape[::-1])))

if self.can_rotate(rotated_shape):

self.shape = rotated_shape


def can_move(self, dx, dy):

for y, row in enumerate(self.shape):

for x, cell in enumerate(row):

if cell:

new_x = self.x + x + dx

new_y = self.y + y + dy

if new_x < 0 or new_x>= GRID_WIDTH or new_y >= GRID_HEIGHT or (

new_y >= 0 and grid[new_y][new_x]):

return False

return True


def can_rotate(self, rotated_shape):

for y, row in enumerate(rotated_shape):

for x, cell in enumerate(row):

if cell:

new_x = self.x + x

new_y = self.y + y

if new_x < 0 or new_x>= GRID_WIDTH or new_y >= GRID_HEIGHT or (

new_y >= 0 and grid[new_y][new_x]):

return False

return True


def lock(self):

for y, row in enumerate(self.shape):

for x, cell in enumerate(row):

if cell:

grid[self.y + y][self.x + x] = self.color


def draw_grid():

for x in range(0, WIDTH, BLOCK_SIZE):

pygame.draw.line(screen, WHITE, (x, 0), (x, HEIGHT))

for y in range(0, HEIGHT, BLOCK_SIZE):

pygame.draw.line(screen, WHITE, (0, y), (WIDTH, y))


def draw_blocks():

for y, row in enumerate(grid):

for x, cell in enumerate(row):

if cell:

pygame.draw.rect(screen, cell, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))


def check_lines():

full_lines = []

for y, row in enumerate(grid):

if all(row):

full_lines.append(y)

for line in full_lines:

del grid[line]

grid.insert(0, [0] * GRID_WIDTH)


游戏主循环

clock = pygame.time.Clock()

fall_time = 0

fall_speed = 0.3

current_piece = Tetromino()


running = True

while running:

screen.fill(BLACK)

draw_grid()

draw_blocks()


# 绘制当前方块

for y, row in enumerate(current_piece.shape):

for x, cell in enumerate(row):

if cell:

pygame.draw.rect(screen, current_piece.color,

((current_piece.x + x) * BLOCK_SIZE, (current_piece.y + y) * BLOCK_SIZE, BLOCK_SIZE,

BLOCK_SIZE))


for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

elif event.type == pygame.KEYDOWN:

if event.key == pygame.K_LEFT:

current_piece.move_left()

elif event.key == pygame.K_RIGHT:

current_piece.move_right()

elif event.key == pygame.K_DOWN:

current_piece.move_down()

elif event.key == pygame.K_UP:

current_piece.rotate()


# 自动下落

fall_time += clock.get_rawtime()

clock.tick()


if fall_time / 1000 >= fall_speed:

if current_piece.move_down():

check_lines()

current_piece = Tetromino()

if not current_piece.can_move(0, 0):

running = False

fall_time = 0


pygame.display.flip()


pygame.quit()

```


代码说明:

1. 初始化部分:

- 使用 `pygame.init()` 初始化 Pygame 库。

- 定义游戏窗口的大小、方块大小、网格的宽度和高度等常量。

- 定义颜色和形状列表。


2. 网格和方块类:

- `grid` 是一个二维列表,表示游戏的网格。

- `Tetromino` 类表示一个俄罗斯方块,包含形状、颜色、位置等属性,以及移动、旋转、锁定等方法。


3. 绘制函数:

- `draw_grid()` 函数用于绘制网格线。

- `draw_blocks()` 函数用于绘制已经锁定在网格中的方块。


4. 检查行满函数:

- `check_lines()` 函数用于检查是否有满行,如果有则删除该行,并在顶部添加一行空行。


5. 游戏主循环:

- 处理用户输入,包括左右移动、下落和旋转。

- 控制方块的自动下落速度。

- 当方块无法再下落时,将其锁定在网格中,并检查是否有满行。

- 如果新生成的方块无法放置,则游戏结束。


运行代码:

确保你已经安装了 Pygame 库,可以使用以下命令安装:

```sh

pip install pygame

```

将上述代码保存为一个 Python 文件(例如 `tetris.py`),然后在命令行中运行:

```sh

python tetris.py

```

这样就可以开始玩俄罗斯方块游戏了。

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言