JavaScript
x
23
23
1
class Battlefield:
2
def __init__(self):
3
self.field = new_battlefield()
4
self.amount_ships = 0
5
self.ships = []
6
self.fourdeck = []
7
self.tripledecks = []
8
self.doubledecks = []
9
self.singledecks = []
10
11
def change_value(self, point, value):
12
if 'n' in self.field[point]:
13
self.field[point] = ' {}n'.format(value)
14
else:
15
self.field[point] = ' {}'.format(value)
16
17
def make_move(self):
18
pass
19
20
def __str__(self):
21
return ' a b c d e f g h i jnn' +
22
''.join(self.field.values())
23
Battlefield.field is dictionary with keys:
JavaScript
1
11
11
1
1 1a 1b 1c 1d 1e 1f 1g 1h 1i 1j
2
2 2a 2b 2c 2d
3
3 ..
4
4 ..
5
5 ..
6
6 ..
7
7 ..
8
8 ..
9
9 ..
10
10 10a 10b 10c 10d 10e 10f 10g 10h 10j
11
I know that this is far from the best solution, but to work with this, I decided to write a cursor class:
JavaScript
1
37
37
1
class Cursor:
2
def __init__(self, start_point=None):
3
self.battlefield = Battlefield()
4
self.field_keys = list(self.battlefield.field.keys())
5
if start_point is not None:
6
self.point = start_point
7
else:
8
self.point = '1a'
9
self.battlefield.change_value(self.point, 'X')
10
self.point_key_idx = self.field_keys.index(self.point)
11
12
13
def up(self):
14
if self.point_key_idx not in range(1, 11):
15
new_point_key = self.point_key_idx - 11
16
self.point = self.field_keys[new_point_key]
17
return self.point
18
19
def down(self):
20
pass
21
22
def left(self):
23
pass
24
25
def right(self):
26
pass
27
28
def move(self, move):
29
if move in ('up', 'down', 'left', 'right'):
30
self.battlefield.change_value(self.point, '~')
31
new_point = self.__getattribute__(move)()
32
self.battlefield.change_value(new_point, 'X')
33
else:
34
raise ValueError('Move must be in: up, down, left, right.')
35
36
return new_point
37
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.
JavaScript
1
12
12
1
cur = Cursor('4d')
2
print(cur.point) # 4d
3
4
cur.up()
5
print(cur.point) # 3d
6
7
cur.up()
8
print(cur.point) # 3d
9
10
cur.up()
11
print(cur.point) # 3d
12
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
.
JavaScript
1
7
1
def up(self):
2
if self.point_key_idx not in range(1, 11):
3
self.point_key_idx -= 11
4
self.point = self.field_keys[self.point_key_idx]
5
return self.point
6
7