1

我正在观看 thenewboston http://www.youtube.com/watch?v=9YWzFcHMz78&feature=share&list=EC8E21BDD0981FDF66在 youtube 上的教程,我正在复制他的代码,但我的代码不起作用。每当我按下向下箭头键时,整个程序都会冻结,不会让我退出。我正在使用python 3.3。请帮忙。这是我的代码。

grey="grey.jpg"
circle="circle.png"

import pygame, sys
from pygame.locals import*

pygame.init()
screen=pygame.display.set_mode((1278,990),0,32)

background=pygame.image.load(grey).convert()
pic=pygame.image.load(circle).convert()

x,y=0,0
movex,movey=0,0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type==KEYDOWN:
            if event.key==K_LEFT:
                movex=-1
            elif event.key==K_RIGHT:
                movex=+1
            elif event.key==K_UP:
                movey=-1
            elif event.key==K_DOWN:
                movey=+1
        if event.type==KEYUP:
            if event.key==K_LEFT:
                movex=0
            elif event.key==K_RIGHT:
                movex=0
            elif event.key==K_UP:
                movey=0
            elif event.key==K_Down:
                movey=0
    x+=movex
    y+=movey

    screen.blit(background, (0,0))
    screen.blit(pic,(x,y))

    pygame.display.update()
4

1 回答 1

4

快速运行代码:

$ python test1.py 
Traceback (most recent call last):
  File "test1.py", line 37, in <module>
    elif event.key==K_Down:
NameError: name 'K_Down' is not defined

当程序在向下箭头按下时崩溃时会显示该错误。

崩溃是由于拼写错误,当它需要“K_DOWN”时你有“K_Down”。

更正的代码:

grey="grey.jpg"
circle="circle.png"

import pygame, sys
from pygame.locals import*

pygame.init()
screen=pygame.display.set_mode((1278,990),0,32)

background=pygame.image.load(grey).convert()
pic=pygame.image.load(circle).convert()

x,y=0,0
movex,movey=0,0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type==KEYDOWN:
            if event.key==K_LEFT:
                movex=-1
            elif event.key==K_RIGHT:
                movex=+1
            elif event.key==K_UP:
                movey=-1
            elif event.key==K_DOWN:
                movey=+1
        if event.type==KEYUP:
            if event.key==K_LEFT:
                movex=0
            elif event.key==K_RIGHT:
                movex=0
            elif event.key==K_UP:
                movey=0
            elif event.key==K_DOWN:
                movey=0
    x+=movex
    y+=movey

    screen.blit(background, (0,0))
    screen.blit(pic,(x,y))

    pygame.display.update()
于 2013-04-06T04:31:28.053 回答