I am making a little project for a Battleships game, but I am having a little trouble with getting the code to understand when I click on the object, I want it to change colour.
So far I have this class:
class Tile:
def __init__(self, xstart, ystart, game_display, colour):
self.tile = pygame.Rect(xstart, ystart, 50, 50)
pygame.draw.rect(game_display, colour, self.tile, 1)
print(self.tile)
def ChangeColour(self, game_display, colour):
pygame.draw.rect(game_display, colour, self.tile, 0)
I create the board using this function I made:
def new_board():
global board
xstart = 70
ystart = 50
#pygame.draw.rect(game_display, BLACK, (70, 50, 500, 500), 3)
for square in range(PLAYER_NUMBER_SQUARES):
board.append(Tile(xstart, ystart, game_display, BLACK))
xstart += 50
if xstart == 570:
ystart += 50
xstart = 70
return board
So far, I has added the square / rectangle objects to the list "board", when the player clicks, I get the pixel and use this method to get which square it is that has been clicked:
def get_x_number(x):
index = None
if x >= 70 and x < 120:
index = 70
if x >= 120 and x < 170:
index = 120
if x >= 170 and x < 220:
index = 170
if x >= 220 and x < 270:
index = 220
if x >= 270 and x < 320:
index = 270
if x >= 320 and x < 370:
index = 320
if x >= 370 and x < 420:
index = 370
if x >= 420 and x < 470:
index = 420
if x >= 470 and x < 520:
index = 470
return index
def get_y_number(y):
index = None
if y >= 50 and y < 100:
index = 70
if y >= 100 and y < 150:
index = 120
if y >= 150 and y < 200:
index = 170
if y >= 200 and y < 250:
index = 220
if y >= 250 and y < 300:
index = 270
if y >= 300 and y < 350:
index = 320
if y >= 350 and y < 400:
index = 370
if y >= 400 and y < 450:
index = 420
if y >= 450 and y < 500:
index = 470
return index
(I know this is a slightly more long winded way, but if there is a better way, let me know, tried loops, couldn't get it to work.)
Finally, I get to where it will get the clicked square, however it doesn't change the square, this is because when I index the square out of the list, it returns this: <__main__.Tile object at 0x068A5590>
How can I get it to return the pygame.Rect rather than this? I have had a look into classes, tried __repr__ and __str__ and had no joy, if someone can assist me, that would be great!
Thank you!