分享丨pygame
109
2025.03.01
2025.03.01
发布于 中国

import pygame

import random

# 初始化pygame

pygame.init()

# 设置屏幕大小

screen_width = 400

screen_height = 500

screen = pygame.display.set_mode((screen_width, screen_height))

# 定义颜色

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

GREEN = (0, 255, 0)

RED = (255, 0, 0)

# 方块大小

block_size = 20

# 游戏区域大小

game_width = 10

game_height = 20

# 初始化游戏区域

game_area = [[0] * game_width for _ in range(game_height)]

# 方块形状

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

]

# 当前方块

current_shape = random.choice(shapes)

current_x = game_width // 2 - len(current_shape[0]) // 2

current_y = 0

# 游戏主循环

running = True

clock = pygame.time.Clock()

def draw_game_area():

screen.fill(BLACK)

for y in range(game_height):

for x in range(game_width):

if game_area[y][x] == 1:

pygame.draw.rect(screen, GREEN, (x * block_size, y * block_size, block_size, block_size), 0)

else:

pygame.draw.rect(screen, WHITE, (x * block_size, y * block_size, block_size, block_size), 1)

def draw_current_shape():

for y in range(len(current_shape)):

for x in range(len(current_shape[y])):

if current_shape[y][x] != 0:

pygame.draw.rect(screen, RED, ((current_x + x) * block_size, (current_y + y) * block_size, block_size, block_size), 0)

def check_collision():

for y in range(len(current_shape)):

for x in range(len(current_shape[y])):

if current_shape[y][x] != 0:

if (current_y + y >= game_height or

current_x + x < 0 or

current_x + x >= game_width or

game_area[current_y + y][current_x + x] == 1):

return True

return False

def lock_shape():

for y in range(len(current_shape)):

for x in range(len(current_shape[y])):

if current_shape[y][x] != 0:

game_area[current_y + y][current_x + x] = 1

while running:

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_x -= 1

if check_collision():

current_x += 1

elif event.key == pygame.K_RIGHT:

current_x += 1

if check_collision():

current_x -= 1

elif event.key == pygame.K_DOWN:

current_y += 1

if check_collision():

current_y -= 1

lock_shape()

current_shape = random.choice(shapes)

current_x = game_width // 2 - len(current_shape[0]) // 2

current_y = 0

draw_game_area()

draw_current_shape()

pygame.display.flip()

clock.tick(5)

pygame.quit()

评论 (0)