class Battlefield: def __init__(self): self.field = new_battlefield() self.amount_ships = 0 self.ships = [] self.fourdeck = [] self.tripledecks = [] self.doubledecks = [] self.singledecks = [] def change_value(self, point, value): if 'n' in self.field[point]: self.field[point] = ' {}n'.format(value) else: self.field[point] = ' {}'.format(value) def make_move(self): pass def __str__(self): return ' a b c d e f g h i jnn' + ''.join(self.field.values())
Battlefield.field is dictionary with keys:
1 1a 1b 1c 1d 1e 1f 1g 1h 1i 1j 2 2a 2b 2c 2d 3 .. 4 .. 5 .. 6 .. 7 .. 8 .. 9 .. 10 10a 10b 10c 10d 10e 10f 10g 10h 10j
I know that this is far from the best solution, but to work with this, I decided to write a cursor class:
class Cursor: def __init__(self, start_point=None): self.battlefield = Battlefield() self.field_keys = list(self.battlefield.field.keys()) if start_point is not None: self.point = start_point else: self.point = '1a' self.battlefield.change_value(self.point, 'X') self.point_key_idx = self.field_keys.index(self.point) def up(self): if self.point_key_idx not in range(1, 11): new_point_key = self.point_key_idx - 11 self.point = self.field_keys[new_point_key] return self.point def down(self): pass def left(self): pass def right(self): pass def move(self, move): if move in ('up', 'down', 'left', 'right'): self.battlefield.change_value(self.point, '~') new_point = self.__getattribute__(move)() self.battlefield.change_value(new_point, 'X') else: raise ValueError('Move must be in: up, down, left, right.') return new_point
My problem: When I try to move a cursor multiple times by using the “up” function and others, the self.point value changes only once.
cur = Cursor('4d') print(cur.point) # 4d cur.up() print(cur.point) # 3d cur.up() print(cur.point) # 3d cur.up() print(cur.point) # 3d
The last use a function should return “1d”. I dont know what to do..
Advertisement
Answer
You’re only updating self.point
, not self.point_key_idx
.
def up(self): if self.point_key_idx not in range(1, 11): self.point_key_idx -= 11 self.point = self.field_keys[self.point_key_idx] return self.point