gpt4 book ai didi

python - Sprite 没有显示在 pygame 窗口上

转载 作者:行者123 更新时间:2023-12-01 06:25:09 27 4
gpt4 key购买 nike

我刚刚开始使用 pygame,我很困惑为什么我的 Sprite 没有出现在窗口中......

这是我的游戏主要代码:

import pygame

from Classes.Car import Car

pygame.init()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
GREY = (167, 167, 167)

size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My First Game")

all_sprites_list = pygame.sprite.Group()
playerCar = Car(BLACK, 20, 30)

playerCar.rect.x = 200
playerCar.rect.y = 300
all_sprites_list.add(playerCar)

carryOn = True
clock = pygame.time.Clock()
while carryOn:
for event in pygame.event.get():
if event.type == pygame.QUIT:
carryOn = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
carryOn = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
playerCar.moveLeft(5)
if keys[pygame.K_RIGHT]:
playerCar.moveRight(5)
all_sprites_list.update()
all_sprites_list.draw(screen)
screen.fill(GREEN)
pygame.draw.rect(screen, GREY, [150, 0, 400, 500], 0)
pygame.draw.line(screen, WHITE, [150, 0], [150, 500], 3)
pygame.draw.line(screen, WHITE, [250, 0], [250, 500], 3)
pygame.draw.line(screen, WHITE, [350, 0], [350, 500], 3)
pygame.draw.line(screen, WHITE, [450, 0], [450, 500], 3)
pygame.draw.line(screen, WHITE, [550, 0], [550, 500], 3)
pygame.display.flip()
clock.tick(60)
pygame.quit()


这是我的类,它是在另一个名为 Car.py 的文件中创建的:

import pygame
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREY = (167, 167, 167)
GREEN = (0, 255, 0)


class Car(pygame.sprite.Sprite):

def __init__(self, color, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(GREY)
pygame.draw.rect(self.image, color, [0, 0, width, height])
self.rect = self.image.get_rect()

def moveRight(self, pixels):
self.rect.x += pixels

def moveLeft(self, pixels):
self.rect.x -= pixels

请告诉我如何进一步澄清我的问题。这是我第一次在这里真正问任何问题。

最佳答案

汽车没有出现,因为它被遮盖了。 screen.fill(GREEN) 不仅仅设置颜色,它还用 GREEN 颜色填充整个屏幕。
首先填满屏幕。然后画灰色的街道,最后在上面画 Sprite 。更新最后的显示:

while carryOn:

# [...]

screen.fill(GREEN)

pygame.draw.rect(screen, GREY, [150, 0, 400, 500], 0)
pygame.draw.line(screen, WHITE, [150, 0], [150, 500], 3)
pygame.draw.line(screen, WHITE, [250, 0], [250, 500], 3)
pygame.draw.line(screen, WHITE, [350, 0], [350, 500], 3)
pygame.draw.line(screen, WHITE, [450, 0], [450, 500], 3)
pygame.draw.line(screen, WHITE, [550, 0], [550, 500], 3)

all_sprites_list.draw(screen)

pygame.display.flip()

关于python - Sprite 没有显示在 pygame 窗口上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60193186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com