簡體   English   中英

在Pygame中,我無法移動子畫面? 是我的代碼嗎?

[英]In Pygame i cannot make my sprite move?? is it my code?

使用箭頭鍵時,我的精靈不會移動? 我已經查看了我的代碼,但我終生無法解決它的問題所在? 任何幫助將不勝感激在此先感謝!!:D

    bif="cloud.jpg"
    mif="reddwarf.png"

import pygame,sys
from pygame.locals import *

pygame.init()

DISPLAYSURF=screen=pygame.display.set_mode((813,555),32,0)
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==KEY_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==KEY_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()

檢查您的縮進。 看起來,用於檢查事件的for循環不在while循環內,並且您的代碼也不可移動您的精靈或更新屏幕。

首先提到您的標題:如果某事不起作用,則很有可能這確實是由於您的代碼所致;)

內在化在Python中極為重要。 這部分在這里:

x+=movex
y+=movey

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

pygame.display.update()

在while循環之外!

Python的工作方式如下:

while True:
    do_something()
    #this code will run while the condition remains true
do_something_else()
#code with this indendation level will run AFTER the while loop has finished.
#It's on the same indendation level like while.

您必須使用我上面發布的代碼的一部分,因此它與

if event.type == ...

塊。 現在它的排列方式是,x + = movex .....部分一直等到while循環結束時-這實際上永遠不會發生,因此沒有更新x / y值和閃爍。

看起來像是縮進錯誤。 你需要把你的

x+=movex
y+=movey

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

在while True循環中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM