我是 Pygame 的新手,我正在尝试为我的第一个 Pygame 项目创建一个 flappy Bird 克隆。我有一个不错的起点,但当我尝试向矩形添加纹理时遇到了问题。我有两个矩形代表顶部和底部管道。当我将它们保留为矩形时,矩形的大小就按照我想要的方式正确安装了。但是,当我尝试将管道纹理添加到矩形时,它们的纹理无法正确映射到矩形。我的代码是:
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((250,500))
clock = pygame.time.Clock()
run = True
background = pygame.image.load('graphics/background-day.png')
ground = pygame.image.load('graphics/base.png')
birdRec = pygame.Rect(0, 0, 30, 24)
birdRec.center = (100,300)
bottomPipeHeight = random.randrange(50, 350)
pipeRecBottom = pygame.Rect(0,0, 50, bottomPipeHeight)
pipeRecBottom.midbottom = (150, 450)
pipeRecTop = pygame.Rect(0,0,50,500)
pipeRecTop.midbottom = pipeRecBottom.midtop
pipeRecTop.y -= 100
gravity = 0
pipeBottomTexture = pygame.image.load("graphics/pipe-green.png").convert_alpha()
while run:
#poll for events
#pygame.QUIT event means the user clicked x
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
gravity += .1
birdRec.y += gravity
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
birdRec.y -= 7
gravity = 0
if keys[pygame.K_s]:
birdRec.y += 2
if keys[pygame.K_d]:
birdRec.x += 2
if keys[pygame.K_a]:
birdRec.x -= 2
pipeRecBottom.x -= 1
pipeRecTop.x -= 1
if(birdRec.colliderect(pipeRecTop) or birdRec.colliderect(pipeRecBottom)):
print("Collision")
# RENDER GAME
screen.blit(background,(0,0))
screen.blit(ground,(0,450))
#PROBLOMATIC AREA BEGIN
pygame.draw.rect(screen, "Black", pipeRecBottom)
#screen.blit(pipeBottomTexture, pipeRecBottom)
#PROBLOMATIC AREA END
pygame.draw.rect(screen, "Green", pipeRecTop)
pygame.draw.rect(screen, "Red", birdRec)
if pipeRecBottom.right < -30:
pipeRecBottom.height = random.randrange(50,350)
pipeRecBottom.bottomleft = (280,450)
if pipeRecTop.right < -30:
pipeRecTop.midbottom = pipeRecBottom.midtop
pipeRecTop.y -= 100
pygame.display.flip()
clock.tick(60)
pygame.quit()
我尝试最初注释掉有问题的区域中的第一行,然后简单地编写第二行。我的思考过程是,我计算了矩形位置,所以我只想将纹理拍在它上面。
但相反,纹理偏离了矩形,通常会导致管道底部进入地板下方。我认为底部管道的顶部已映射到正确的点,我只是希望能够阻止纹理进入地板。
两者之间的高度差异是因为高度是随机生成的。如果我修复高度值,裁剪问题仍然存在。
blit
有第三个参数来定义原始图像的显示区域
screen.blit(pipeBottomTexture, pipeRecBottom, (0, 0, 50, pipeRecBottom.height))