Why do I get a NameError
exception in this program?
I am programming a Python plane fight game using pygame
. I have just finished added the plane PNG to the background. However, when I want to test the movement of the plane, the error is raised and I couldn't find why it occurred.
Error traceback:
Traceback (most recent call last):
File "C:\Users\Desktop\Plane Fight\Plane Fight.py", line 34, in <module>
main()
File "C:\Users\Desktop\Plane Fight\Plane Fight.py", line 29, in main
draw_window()
File "C:\Users\Desktop\Plane Fight\Plane Fight.py", line 12, in draw_window
win.blit(leftjet, (left.x, left.y))
NameError: name 'left' is not defined
Code:
import pygame
import os
win = pygame.display.set_mode((900, 500)) #生成一个900*500分辨率的游戏界面
pygame.display.set_caption("Plane Fight Game")
leftjet = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(os.path.join('fighterjet.jpg')), (55 ,40)), 270)
rightjet = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(os.path.join('fighterjet.jpg')), (55 ,40)), 90)
def draw_window():
win.fill((0, 0, 0)) #设置背景为黑色
win.blit(leftjet, (left.x, left.y))
win.blit(rightjet, (right.x, right.y))
pygame.display.update()
def main():
left = pygame.Rect(100, 100, 55, 40)
right = pygame.Rect(800, 100, 55, 40)
run = True
while run:
pygame.time.Clock().tick(60) #设置游戏帧率为60帧
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
right.x += 1
draw_window()
pygame.quit()
if __name__ == "__main__":
main()