I've been trying to create a chess program with pygame and am stuck trying to program rules that the pieces are supposed to follow. I am starting by only focusing on the King piece. Here is my code:
class Piece(object):
def __init__(self, x_init, y_init, color):
self.x_init = x_init
self.y_init = y_init
self.color = color
self.possible_positions = False
self.width = 60
self.height = 60
self.click = False
self.click_rect = sprites[0].get_rect(topleft=(self.x_init, self.y_init))
self.init1 = True
self.x_newinit = 0
self.y_newinit = 0
self.final_pos = False
def movement(self):
global x, y
for event in ev:
if self.init1:
self.x_newinit = self.x_init
self.y_newinit = self.y_init
if event.type == pygame.MOUSEBUTTONDOWN:
if self.click_rect.collidepoint(event.pos):
self.click = True
self.init1 = True
x, y = event.pos
elif event.type == pygame.MOUSEBUTTONUP:
self.click = False
self.x_init = (((round(self.x_init / 75)) * 75) + 7.5)
self.y_init = (((round(self.y_init / 75)) * 75) + 7.5)
if not self.possible_positions:
self.x_init = self.x_newinit
self.y_init = self.y_newinit
if event.type == pygame.MOUSEMOTION:
self.init1 = False
if self.click:
if 25 < x < 580:
self.x_init = x - 30
if 20 < y < 580:
self.y_init = y - 30
self.click_rect = sprites[0].get_rect(topleft=(self.x_init, self.y_init))
class King(Piece):
def __init__(self, x_init, y_init, color):
super().__init__(x_init, y_init, color)
self.x_init = x_init
self.y_init = y_init
self.color = color
self.final_pos = False
def draw(self, gameWindow):
if not self.final_pos:
gameWindow.blit(sprites[0], (self.x_init, self.y_init)) # draw white king
def draw2(self, gameWindow):
if not self.final_pos:
gameWindow.blit(sprites[6], (self.x_init, self.y_init)) # draw black king
def poss_positions(self):
if self.x_newinit - 37.5 >= self.x_init >= self.x_newinit - 112.5: # move left
self.possible_positions = True
elif self.x_newinit + 37.5 <= self.x_init <= self.x_newinit + 112.5: # move right
self.possible_positions = True
elif self.y_newinit - 37.5 >= self.y_init >= self.y_newinit - 112.5: # move up
self.possible_positions = True
elif self.y_init - 37.5 >= self.y_newinit >= self.y_init - 112.5: # move down
self.possible_positions = True
else:
self.possible_positions = False
The king pieces follow the self.poss_positions rules and are sent back to their starting position when I try to move them incorrectly, but then they are stuck there and I can't move them again. I've tried defining new variables and setting them equal to self.x_init and self.y_init under certain conditions so that I can reset the variables self.x_newinit and self.y_newinit to 0 and reset the whole process, but that didn't work. Whatever possible solution I throw at this doesn't seem to work. I need help.