鼠标单击后更改屏幕区域的颜色,并在释放Pygame后保持更改

时间:2019-06-07 16:50:11

标签: python pygame

所以我有游戏背景。如果发生事件(单击),则背景区域会改变颜色。当我释放鼠标单击时,屏幕将更新并返回到我不想发生的原始颜色。

问题显然是游戏循环每次迭代后背景都会更新,使其恢复到原始状态,但是,我相信我需要背景不断更新,而且还需要点击更改才能永久生效?因此,我需要找到一种方法,以便在鼠标单击后 单击的区域更改颜色,而游戏继续循环。

class Game(object):
    def __init__(self):
        self.squares = []
        self.occupied = []
    for x in range(0,8,1):
        for y in range(0,8,1):
            if (x + y) % 2 !=0:
                pygame.draw.rect(screen, white, [x*100, y*100, 100, 100])
            elif(x + y) % 2 ==0:
                pygame.draw.rect(screen, aqua, [x*100, y*100, 100, 100])
            self.squares.append([x,y])
    if event.type == pygame.MOUSEBUTTONDOWN:
        mx, my = pygame.mouse.get_pos()
        mx = mx//100
        my = my//100
        pygame.draw.rect(screen, green, [mx*100, my*100, 100, 100])

while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        game = Game()
    pygame.display.update()
    clock.tick(30)

pygame.quit() quit()

1 个答案:

答案 0 :(得分:1)

请勿在每次迭代中创建Game()的新实例。仅在主循环之前创建一个实例,然后向Game类添加方法以更新正方形的颜色。

更好地捕获主循环中而不是类中的所有事件。捕获事件时,请调用相关的类方法以执行预期的操作。

下面的工作代码:

import pygame

white = (255, 255, 255)
aqua = (0, 0, 100) #or whatever it really is, it's just a constant
green = (0, 255, 0)

class Game(object):
    def __init__(self):
        self.squares = []
        self.occupied = []
        for x in range(0,8,1):
            for y in range(0,8,1):
                if (x + y) % 2 !=0:
                    pygame.draw.rect(screen, white, [x*100, y*100, 100, 100])
                elif(x + y) % 2 ==0:
                    pygame.draw.rect(screen, aqua, [x*100, y*100, 100, 100])
                self.squares.append([x,y])

    def colorsquare(self):
        mx, my = pygame.mouse.get_pos()
        mx = mx//100
        my = my//100
        pygame.draw.rect(screen, green, [mx*100, my*100, 100, 100])

game_over = False
pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
game = Game()
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        elif event.type == pygame.MOUSEBUTTONDOWN:
            game.colorsquare()

    pygame.display.update()
    clock.tick(30)
相关问题