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

问题描述 投票:1回答:1

我正在观看由newsboston 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()
python python-3.x pygame
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()
© www.soinside.com 2019 - 2024. All rights reserved.