python - 如何使用 python 和 pygame 在游戏中使用平铺?

标签 python python-3.x pygame tiling

我正在使用 python 和 pygame 创建一个 2D 平台游戏类型的射击游戏,并且我正在尝试添加平铺机制,因此如果我创建一个 100 像素长的平台并且平铺图像只有 70 像素长,它会绘制一个图 block 和另一个图 block 的一半,所以我创建了一个简单的原型(prototype),但我无法让它绘制 Sprite 。这是我的代码:

import pygame

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

class Rec(pygame.sprite.Sprite):

    def __init__(self, x, y, w, height):

        super().__init__()

        self.b = 0
        self.image = pygame.image.load("grass.png").convert()
        if w <= 70:
            self.image = pygame.transform.scale(self.image, (w, height))
        elif w > 70:
            self.image = pygame.Surface([w, height])
            while self.b < w:
                self.image.blit(pygame.image.load("grass.png").convert(), (x + self.b, y))
                self.b += 70

        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

pygame.init()

size = (700, 500)

screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

all_sprites_list = pygame.sprite.Group()

rec = Rec(100, 200, 140, 70)
all_sprites_list.add(rec)

done = False

clock = pygame.time.Clock()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    screen.fill(WHITE)
    all_sprites_list.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

最佳答案

线路

self.image.blit(pygame.image.load("grass.png").convert(), (x + self.b, y))

应该是

self.image.blit(pygame.image.load("grass.png").convert(), (self.b, 0))

因为您传递给 blit 函数的位置是相对于您 blit 的 Surface 而言的;但 xy 是屏幕坐标。

因此,在您的示例中,您在 Surface 上使用 x + self.b = 100y = 200 位置位 block 传输草 map 像> 的大小为 (140, 70),而您应该将其位 block 传送到 (0, 0)

关于python - 如何使用 python 和 pygame 在游戏中使用平铺?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35333669/

相关文章:

python -lxml : enforcing a specific order for attributes

python-3.x - 将文本文件的每一行写入单独的文本文件并使用不同的名称保存

来自装饰器的 Python3 边界方法

python - 如何让箭头朝鼠标方向射出?

python - 进入全屏时屏幕尺寸不更新

python - 似乎无法在 Windows 上为 python 2.7 安装 pandas

python - 计算文件中某个三联体的数量(DNA 密码子分析)

python - 对列表进行排序,其中某些值保持在固定位置

python - PyGame 无法在使用 Python3.4 的 Eclipse 中工作

Python - 数组的坐标