Jul-22-2021, 02:46 PM
(This post was last modified: Jul-23-2021, 08:41 PM by deanhystad.)
Instead of using a variable to store the color you could use a function that returns the color. As I said, somewhere you need code.
Your code is odd. I don't have any pygame experience at all, but I think you would want to some sort of collection object instead of having a named variable for each thing. Since the squares on the board are an important part of the game I might make a class to hold all the information for a square such as the location, the background color, and any chess piece landing on the square:
The board is just a collection of squares, so I make a class that represents that.
Your code is odd. I don't have any pygame experience at all, but I think you would want to some sort of collection object instead of having a named variable for each thing. Since the squares on the board are an important part of the game I might make a class to hold all the information for a square such as the location, the background color, and any chess piece landing on the square:
class Square(): '''A location on the board''' def __init__(self, rank, file): self.rank = rank self.file = file self.name = 'abcdefgh'[rank]+str(file+1) self.background = [0,0,120] if (rank+file)%2 else [0,0,0] x = (rank)*100 # Not sure of pygame coordinates so this could be wrong y = (file)*100 self.rectangle = [x, y, 100, 100] self.occupant = None def draw(self): '''Draw self on screen''' self.square = pygame.draw.rect(screen, self.color, self.rectangle) if self.occupant: '''Draw image for piece occupying square''' @property def piece(self): '''Return occupant''' return self.occupant @piece.setter def place(self, piece): '''Set the occupant. Redraw the square''' self.occupant = piece self.draw()In addition to storing information a class can also have actions. My Square class would have an action (method) to draw the square and another for adding or removing a chess piece. I might make the latter a property so I can use the same property to see or set what piece occupies a square.
The board is just a collection of squares, so I make a class that represents that.
class Board(): '''A grid of Squares''' def __init__(self): self.ranks = [] for rank in range(8): self.rank.append([Square(rank, file) for file in range(8)]) def square(self, rank, file): """Return square at rank/file""" return self.rank[rank][file] def move(self, r1, f1, r2, f2): '''Move piece from r1, f1 to r2, f2''' self.square(r2, f2).piece = self.square(r1, f1).piece self.square(r1, f1).piece = None def draw(self): '''Draw the board''' for rank in self.ranks: for square in rank: square.draw()Now I can make and draw a chess board in two lines:
board = Board() board.draw()And I can move a piece in one line
board.move(startRank, startFile, endRank, endFile)