pygame的/ Python的精灵不动? 我做了什么错? (没有错误)(pygame/pyt

2019-10-23 19:39发布

好了,所以这里是我的代码,我没有得到任何错误,但我的精灵(播放器)不动

import pygame,sys
import random
import time

#Colors
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

class Block(pygame.sprite.Sprite):
    def __init__(self, color = blue, width = 50, height = 50):

    super(Block, self).__init__()

    self.image = pygame.Surface((width, height))

    self.image.fill(color)

    self.rect = self.image.get_rect()

def set_position(self, x , y):
    self.rect.x = x
    self.rect.y = y

def set_image(self, filename = None):
    if(filename != None):
        self.image = pygame.image.load(filename)

        self.rect = self.image.get_rect()

if (__name__ == "__main__"):
    pygame.init()

    window_size = window_width, window_height = 640,480
    window = pygame.display.set_mode(window_size)
    pygame.display.set_caption('Test')

    window.fill(white)
    clock = pygame.time.Clock()

    #important variables
    pos_x = 300
    pos_y = 200
    pos_x_change = 0
    pos_y_change = 0

    block_group = pygame.sprite.Group()
    player = Block()
    player.set_image('player.png')
    player.set_position(pos_x,pos_y)  #Player variable for pos

    another_block = Block(red)
    another_block.set_position(100,100)

    block_group.add(player, another_block)
    block_group.draw(window)

    pygame.display.update()



    running = True

    while(running):
        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                pos_x_change = -10
            if event.key == pygame.K_RIGHT:
                pos_x_change = 10
            if event.key == pygame.K_UP:
                pos_y_change -10
            if event.key == pygame.K_DOWN:
                pos_y_change = 10
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                pos_x_change = 0
            if event.key == pygame.K_RIGHT:
                pos_x_change = 0
            if event.key == pygame.K_UP:
                pos_y_change == 0
            if event.key == pygame.K_DOWN:
                pos_y_change == 0


    pos_x += pos_x_change
    pos_y += pos_y_change
    clock.tick(60)

pygame.quit 
quit()

正如你所看到的,我清楚地添加了POS_X和POS_Y并将其设置为POS_X + = pos_x_change和POS_Y + = pos_y_change但精灵依然不动。 我猜这是一个代码错位,因为蟒蛇在很大程度上依赖于缩进? 请给我解释什么,我做错了,这将不胜感激。

Answer 1:

它看起来像您要更新包含玩家X和Y坐标的变量,但你不更新显示。 这就是为什么它看起来像的位置没有改变。 我相信调用player.set_position(pos_x,pos_y)略高于clock.tick(60)语句将解决这个问题。



文章来源: pygame/python sprite not moving? What have i done wrong? (no errors)