错误:
Traceback (most recent call last):
File "/home/hayden/Desktop/Platformer/platformer.py", line 65, in <module>
game_loop()
File "/home/hayden/Desktop/Platformer/platformer.py", line 58, in game_loop
char(char_x,char_y)
File "/home/hayden/Desktop/Platformer/platformer.py", line 23, in char
pygame.game_display.blit(size,(x,y))
AttributeError: 'module' object has no attribute 'game_display'
>>>
法典:
import pygame
pygame.init()
display_width = 800
display_height = 600
char_width = 128
char_height = 99
char_sprite = pygame.image.load("man.png")
framerate = 30
gravity = 5
game_display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Platformer")
clock = pygame.time.Clock()
def char(x,y):
size = pygame.transform.scale(char_sprite,(128,99))
pygame.game_display.blit(size,(x,y))
def close():
pygame.quit()
quit()
def game_loop():
char_x = display_width/2
char_y = display_height/2
char_x_change = 0
char_y_change = 0
char_speed = 5
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
close()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_W:
char_y_change -= char_speed
if event.type == pygame.K_S:
char_y_change += char_speed
if event.type == pygame.K_A:
char_x_change -= char_speed
if event.type == pygame.K_D:
char_x_change += char_speed
game_display.fill((0,0,255))
char_x += char_x_change
char_y += char_y_change
char_y -= gravity
char(char_x,char_y)
char_y -= gravity
pygame.display.update()
clock.tick(framerate)
game_loop()
我不知道为什么我会收到此错误和黑屏。为了帮助您更好地理解代码,我正在尝试创建一个 2d 平台成型器。我是编程和pygame的新手,所以请尽量不要给出高级解释。对于像这样的其他错误,似乎您必须导入某些内容,但导入了pygame。
这是修改后的代码。还有更多的错误,但你必须尝试自己解决,只有在你不能独自完成时才问。:)当你调用一个函数时,你必须将值和参数发送到它。函数不会自动执行此操作。查看我所做的更改。
import pygame
from pygame import *
pygame.init()
display_width = 800
display_height = 600
char_width = 128
char_height = 99
char_sprite = pygame.image.load("test.png")
framerate = 30
gravity = 5
screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Platformer")
clock = pygame.time.Clock()
def char(x,y, screen):
size = pygame.transform.scale(char_sprite,(128,99))
screen.blit(size,(x,y))
def close():
pygame.quit()
quit()
def game_loop(screen, display_width, display_height):
char_x = display_width/2
char_y = display_height/2
char_x_change = 0
char_y_change = 0
char_speed = 5
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
close()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_W:
char_y_change -= char_speed
if event.type == pygame.K_S:
char_y_change += char_speed
if event.type == pygame.K_A:
char_x_change -= char_speed
if event.type == pygame.K_D:
char_x_change += char_speed
screen.fill((0,0,255))
char_x += char_x_change
char_y += char_y_change
char_y -= gravity
char(char_x,char_y, screen)
char_y -= gravity
pygame.display.update()
clock.tick(framerate)
game_loop(screen, display_width, display_height)
希望这有帮助。