import pygame
import random
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
ORANGE = (255, 165, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 128, 0)
PURPLE = (128, 0, 128)
# 定义方块的形状和颜色
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]],
[[7, 7, 7, 7]]
]
colors = [CYAN, BLUE, ORANGE, YELLOW, GREEN, PURPLE, WHITE]
# 定义游戏界面的尺寸
block_size = 30
screen_width = 10 * block_size
screen_height = 20 * block_size
# 创建游戏界面
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Tetris")
# 定义字体
font = pygame.font.SysFont(None, 48)
# 定义计分板
score = 0
class Block:
def __init__(self):
self.x = screen_width // 2 - block_size
self.y = 0
self.shape = random.choice(shapes)
self.color = random.choice(colors)
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), 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_clockwise(self):
self.shape = [[self.shape[j][i] for j in range(len(self.shape))] for i in range(len(self.shape[0]) - 1, -1, -1)]
def rotate_counterclockwise(self):
self.shape = [[self.shape[j][i] for j in range(len(self.shape) - 1, -1, -1)] for i in range(len(self.shape[0]))]
def check_collision(block, all_blocks):
if block.y < 0:
return True
for i in range(len(block.shape)):
for j in range(len(block.shape[i])):
if block.shape[i][j] > 0:
x, y = block.x + j * block_size, block.y + i * block_size
if (x, y) in [(b.x, b.y) for b in all_blocks]:
return True
if x < 0 or x >= screen_width or y >= screen_height:
return True
return False
def remove_complete_lines(all_blocks):
complete_lines = [r for r in range(0, screen_height, block_size)
if len([(b.x, b.y) for b in all_blocks if b.y == r]) == screen_width // block_size]
num_lines = len(complete_lines)
global score
score += num_lines ** 2
for r in complete_lines:
for b in all_blocks:
if b.y == r:
all_blocks.remove(b)
for b in all_blocks:
if b.y < r:
b.move_down()
# 主程序
clock = pygame.time.Clock()
falling_block = Block()
标签:示例,Python,self,len,shape,方块,screen,block,size
From: https://blog.51cto.com/u_16096394/6262782