Reputation: 29
so I have a background to my game. If an event (click) occurs, an area of the background changes colour. When I release the mouseclick, the screen updates and returns to the original colour which I don't want to happen.
The issue is clearly that the background updates after every iteration of the game loop, returning it to its original state, however, I believe I need the background to keep updating, but also for the clicks change to stay in permanent effect? So I need to find a way so that after a mouseclick, the clicked area changes color, while the game continues to loop.
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()
Upvotes: 0
Views: 120
Reputation: 7361
Do not create a new instance of Game()
each iteration. Create one instance only before the main loop, and add a method to Game
class to update the color of the square.
Better to catch all the events in the main loop and not in the classes. When you catch an event, call the correlated class method to perform the intended action.
Below a working code:
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)
Upvotes: 1