python俄罗斯方块完整代码
时间: 2024-02-01 15:11:30 浏览: 78
俄罗斯方块python代码
5星 · 资源好评率100%
当然可以!以下是一个简单的Python俄罗斯方块的完整代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小
screen_width = 800
screen_height = 600
play_width = 300
play_height = 600
block_size = 30
top_left_x = (screen_width - play_width) // 2
top_left_y = screen_height - play_height
# 定义形状的类
class Shape(object):
rows = 20
columns = 10
def __init__(self, column, row, shape):
self.x = column
self.y = row
self.shape = shape
self.color = colors[shapes.index(shape)]
self.rotation = 0
# 定义形状的列表
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 = [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 165, 0), (0, 255, 255)]
# 初始化游戏区域
def create_grid(locked_positions={}):
grid = [[(0, 0, 0) for _ in range(Shape.columns)] for _ in range(Shape.rows)]
for row in range(len(grid)):
for col in range(len(grid[row])):
if (col, row) in locked_positions:
color = locked_positions[(col, row)]
grid[row][col] = color
return grid
# 检查是否可以移动形状
def valid_space(shape, grid):
accepted_positions = [[(j, i) for j in range(Shape.columns) if grid[i][j] == (0, 0, 0)] for i in range(Shape.rows)]
accepted_positions = [j for sub in accepted_positions for j in sub]
formatted_shape = convert_shape_format(shape)
for pos in formatted_shape:
if pos not in accepted_positions:
if pos[1] > -1:
return False
return True
# 检查游戏是否结束
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
# 将形状转换为坐标
def convert_shape_format(shape):
positions = []
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '1':
positions.append((shape.x + j, shape.y + i))
for i, pos in enumerate(positions):
positions[i] = (pos[0] - 2, pos[1] - 4)
return positions
# 绘制游戏区域
def draw_grid(surface, grid):
for row in range(len(grid)):
for col in range(len(grid[row])):
pygame.draw.rect(surface, grid[row][col], (top_left_x + col * block_size, top_left_y + row * block_size, block_size, block_size))
pygame.draw.rect(surface, (255, 255, 255), (top_left_x + col * block_size, top_left_y + row * block_size, block_size, block_size), 1)
# 绘制形状
def draw_shape(surface, shape):
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '1':
pygame.draw.rect(surface, shape.color, (top_left_x + (shape.x + j) * block_size, top_left_y + (shape.y + i) * block_size, block_size, block_size))
pygame.draw.rect(surface, (255, 255, 255), (top_left_x + (shape.x + j) * block_size, top_left_y + (shape.y + i) * block_size, block_size, block_size), 1)
# 清除行
def clear_rows(grid, locked_positions):
full_rows = []
for row in range(len(grid)):
if (0, 0, 0) not in grid[row]:
full_rows.append(row)
for row in full_rows:
del grid[row]
grid.insert(0, [(0, 0, 0) for _ in range(Shape.columns)])
for row in full_rows:
for pos in locked_positions.keys():
x, y = pos
if y < row:
new_pos = (x, y + 1)
locked_positions[new_pos] = locked_positions.pop(pos)
return len(full_rows)
# 绘制游戏界面
def draw_window(surface, grid, score=0):
surface.fill((0, 0, 0))
pygame.font.init()
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', 1, (255, 255, 255))
surface.blit(label, (top_left_x + play_width / 2 - (label.get_width() / 2), 30))
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Score: ' + str(score), 1, (255, 255, 255))
surface.blit(label, (top_left_x + play_width + 50, top_left_y + play_height / 2 - 30))
for row in range(len(grid)):
for col in range(len(grid[row])):
pygame.draw.rect(surface, grid[row][col], (top_left_x + col * block_size, top_left_y + row * block_size, block_size, block_size))
pygame.draw.rect(surface, (255, 255, 255), (top_left_x + col * block_size, top_left_y + row * block_size, block_size, block_size), 1)
pygame.draw.rect(surface, (255, 0, 0), (top_left_x, top_left_y, play_width, play_height), 5)
# 主函数
def main():
locked_positions = {}
grid = create_grid(locked_positions)
change_piece = False
run = True
current_piece = Shape(Shape.columns // 2 - 2, 0, random.choice(shapes))
next_piece = Shape(Shape.columns // 2 - 2, 0, random.choice(shapes))
clock = pygame.time.Clock()
fall_time = 0
fall_speed = 0.27
score = 0
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
if fall_time / 1000 >= fall_speed:
fall_time = 0
current_piece.y += 1
if not (valid_space(current_piece, grid)) and current_piece.y > 0:
current_piece.y -= 1
change_piece = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
elif event.key == pygame.K_DOWN:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
elif event.key == pygame.K_UP:
current_piece.rotation += 1
if not valid_space(current_piece, grid):
current_piece.rotation -= 1
shape_pos = convert_shape_format(current_piece)
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
if change_piece:
for pos in shape_pos:
p = (pos[0], pos[1])
locked_positions[p] = current_piece.color
current_piece = next_piece
next_piece = Shape(Shape.columns // 2 - 2, 0, random.choice(shapes))
change_piece = False
score += clear_rows(grid, locked_positions)
draw_window(win, grid, score)
draw_shape(win, current_piece)
pygame.display.update()
if check_lost(locked_positions):
run = False
print('Game Over')
# 游戏结束后的操作
# 运行游戏
win = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Tetris')
main()
```
希望这个代码能帮到你!如果你有任何其他问题,请随时提问。
阅读全文