Python游戏开发帮助

时间:2014-03-02 12:49:04

标签: python

所以我想用python和pygame模块制作游戏。我从YouTube视频中获取了此代码,但它无效。当您按下箭头键时,代码应该让球移动,但每当我按箭头键时,球就会保持原位。如果你看错了,请你纠正我的代码。这是我的代码:

bif="hills.jpg"
mif="ball.png"

import pygame, sys
from pygame.locals import *

pygame.init()

screen=pygame.display.set_mode((604,367),0,32)

background=pygame.image.load(bif).convert()
mouse_c=pygame.image.load(mif).convert_alpha()

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(mouse_c,(x,y))

    pygame.display.update()

1 个答案:

答案 0 :(得分:0)

移动球的代码仅在event.type == QUIT:时执行。这是正确缩进的代码

bif="hills.jpg"
mif="ball.png"

import pygame, sys
from pygame.locals import *

pygame.init()

screen=pygame.display.set_mode((604,367),0,32)

background=pygame.image.load(bif).convert()
mouse_c=pygame.image.load(mif).convert_alpha()

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(mouse_c,(x,y))

    pygame.display.update()