如何在运行时更改类中的变量?

时间:2016-10-20 16:46:31

标签: python

关于我之前的问题的后续问题。

在让圆圈正确显示之后,我希望能够通过键盘输入移动该圆圈。

因为它是一个我想要改变的类,所以我必须有一个实例,这样我就可以一直更改同一个类的实例,而且我确实有一个。

import pygame
pygame.init()

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

#Display
display_width, display_height = 800, 600
screen_center = int(display_width * 0.5), int(display_height * 0.5)
screen = pygame.display.set_mode((display_width, display_height))

#Clock
clock = pygame.time.Clock()

class Player():
    def __init__(self):
        self.xPos = int(display_width * 0.5)
        self.yPos = int(display_height * 0.5)
        self.color = blue
        self.radius = 15
        self.width = 0

        pygame.draw.circle(screen, self.color, (self.xPos, self.yPos), self.radius, self.width)

def game_loop():
    player = Player() #PLAYER CLASS INSTANCE

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

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.color = blue # THESE COLORS ARE MAINLY HERE FOR DEBUGGING
                if event.key == pygame.K_RIGHT:
                    player.color = red # THESE COLORS ARE MAINLY HERE FOR DEBUGGING

                if event.key == pygame.K_UP:
                    pass
                if event.key == pygame.K_DOWN:
                    pass

        #Background
        screen.fill(white)

        #Draw everything in order, each drawn object will be drawn beneath the next drawn object.
        player

        #Update
        pygame.display.update()
        clock.tick(60)

game_loop()

因此,每当我按下左键时,类中的xPos必须改变,以便我的圆圈移动。

1 个答案:

答案 0 :(得分:0)

您可以尝试更改您的播放器类,使其具有自行绘制的分离方法:

class Player():
    def __init__(self):
        self.xPos = int(display_width * 0.5)
        self.yPos = int(display_height * 0.5)
        self.color = blue
        self.radius = 15
        self.width = 0

    def draw(self):
        pygame.draw.circle(screen, self.color, (self.xPos, self.yPos), self.radius, self.width)

然后在你的主循环中,在你完成屏幕填充后调用player.draw():

#Background
screen.fill(white)

#Draw everything in order, each drawn object will be drawn beneath the next drawn object.
player.draw()

现在玩家对象在创建时不会自行绘制,而是在主循环的每次迭代中绘制它。