As a project after learning about classes, I'm trying to create a type of board game where the program tells you where all of it's pieces are, and then you tell it where you've moved your pieces, and then the AI moves its pieces accordingly.
However I'm having a bit of trouble with a few aspects of the program, namely, how do I dynamically update a specific variable stored in a class (in this case, sold1.targx and sold1.targy)? I'm kind of at a loss since this is my first program to use a class.
# The enemy foot soldier class.
class foot:
def __init__(self,mov,posx,posy,targx,targy):
# self.mov is soldier's movement speed, currently not implemented
self.mov = mov
# self.x and self.y are soldier's position
self.x = posx
self.y = posy
# self.targx and self.targy are soldier's x and y target destinations
self.targx = targx
self.targy = targy
def advancex(self):
# advancex(self) adjusts soldier's x position to match the target x position
if self.x > self.targx:
self.x = self.x - 1
elif self.x < self.targx:
self.x = self.x + 1
else:
self.x = self.x
return self.x
def advancey(self):
# as advancex(self) except for the y-axis
if self.y > self.targy:
self.y = self.y - 1
elif self.y < self.targy:
self.y = self.y + 1
else:
self.y = self.y
return self.y
def getpos(self):
# checks the soldier's x and y coordinates and returns as list
pos = [self.x, self.y]
return pos
# Gets the player's move.
def getMove(item):
# Print's the soldier's position str(item)
print("The enemy is at " + str(item) + ".")
print("What is your troop's x coordinate?")
playposx = int(input())
print("What is your troop's y coordinate?")
playposy = int(input())
playpos = [playposx, playposy]
# Returns player's position as list
return playpos
#Creates instance of foot sold1
sold1 = foot(0, 4, 6, 4, 6)
sold1pos = sold1.getpos()
# Gets the player's move
move = getMove(sold1pos)
# Recreates the soldier now that the player's position has been given
sold1 = foot(0, 4, 6, move[0], move[1])
sold1pos = sold1.getpos()
# Prints the soldier's original position, advances him one space
# towards the target, and prints the new position
print(sold1pos)
sold1.advancex()
sold1.advancey()
print(sold1.getpos())
Thanks in advance!