python - 俄罗斯方 block 从 block 生成彩色形状

标签 python pygame tetris

我正在用 Pygame 制作俄罗斯方 block 。我已经单独设计了 block (每种颜色的 block ),因此我需要让游戏生成所有颜色的所有 block 形状。我的意思是我希望它生成例如由 4 个连续的红色 block 组成的形状或看起来像这些独立 block 中的字母 L 的蓝色形状...然后我将创建一个列表,在其中存储所有这些形状之后会随机生成。

这些是那些独立的 block :

red_block = pygame.image.load(r'C:\Users\Salem\Documents\MyGame1\red.png')
blue_block = pygame.image.load(r'C:\Users\Salem\Documents\MyGame1\blue.png')

因此,我想在 pygame 中制作俄罗斯方 block 形状,以便直接在游戏中使用它们,无需 Photoshop 或任何外部软件 blue block green blocks purple block red block yellow block

简历: enter image description here --->>> enter image description here (这只是一种可能的情况)

最佳答案

俄罗斯方 block 按网格排列。定义形状列表。每个形状都是一个列表。该列表包含指定组成形状的每个图 block 的列和行的元组:

shapes = [
    [(0, 0), (1, 0), (2, 0), (3, 0)],
    [(0, 0), (1, 0), (0, 1), (1, 1)],
    [(0, 0), (1, 0), (2, 0), (2, 1)],
    [(0, 0), (1, 0), (2, 0), (1, 1)],
    # [...] add more
]

创建一个可用于绘制列表的单个形状的函数:

def draw_shape(x, y, tile_index, surf):
    w, h = surf.get_size()
    for pos in shapes[tile_index]:
        screen.blit(surf, (x + pos[0]*w, y + pos[1]*h))

完整示例:

import pygame

pygame.init()
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

tile_size = 20
red_tile = pygame.Surface((tile_size, tile_size))
red_tile.fill("red")
blue_tile = pygame.Surface((tile_size, tile_size))
blue_tile.fill("blue")
green_tile = pygame.Surface((tile_size, tile_size))
green_tile.fill("green")
yellow_tile = pygame.Surface((tile_size, tile_size))
yellow_tile.fill("yellow")

shapes = [
    [(0, 0), (1, 0), (2, 0), (3, 0)],
    [(0, 0), (1, 0), (0, 1), (1, 1)],
    [(0, 0), (1, 0), (2, 0), (2, 1)],
    [(0, 0), (1, 0), (2, 0), (1, 1)],
    # [...] add more
]

def draw_shape(x, y, tile_index, surf):
    w, h = surf.get_size()
    for pos in shapes[tile_index]:
        screen.blit(surf, (x + pos[0]*w, y + pos[1]*h))

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          

    screen.fill(0)
    draw_shape(70, 70, 0, red_tile)
    draw_shape(170, 70, 1, blue_tile)
    draw_shape(70, 170, 2, green_tile)
    draw_shape(170, 170, 3, yellow_tile)
    pygame.display.flip()

pygame.quit()
exit()

关于python - 俄罗斯方 block 从 block 生成彩色形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66765536/

相关文章:

python - Pygame 中的动画故障

java - 在游戏上打印具有透明背景的 JLabel + 使用 Swing 添加声音

python - 为什么 for 循环和 np.random.shuffle 在 Python 中不能按预期工作?

python - 在缩小列宽后强制 Tkinter.ttk Treeview 小部件调整大小

python - 为什么我收到错误 : command 'llvm-gcc-4.2' failed with exit status 1

Python 2.7 : Faster/better way to extract all integer values from a string?

python - Pygame.movi​​e 丢失

python - 在 PyGame 中使用 GIF

javascript - p5.j​​s 俄罗斯方 block 的实现有一个错误,使碎片从底部掉落

python - 我的 pygame 俄罗斯方 block 游戏总是卡住