为什么我的python pygame代码不起作用?

时间:2013-04-06 03:03:30

标签: python python-3.x pygame

我正在看新星波士顿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()

1 个答案:

答案 0 :(得分: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()