Hi, @ulfen69 and @florian! Thank you guys so much! With your helps, I managed to make a first version of the code:
class Engine(object):
def __init__(self, map_num):
self.map_num = map_num
def play(self):
current_num = self.map_num.opening_num()
last_num = self.map_num.last_num(3, 2)
# I set ending coordinate to be (3, 2)
while current_num != last_num:
print(current_num)
action = input("> ")
current_num = self.map_num.next_num(action)
# be sure to print out the last number
print(current_num)
class Map(object):
map_num = [
[ 00, 1, 2, 3],
[ 10, 11, 12, 13],
[ 20, 21, 22, 23],
[ 30, 31, 32, 33]
]
def __init__(self, a, b):
self.a = a
self.b = b
self.start_num = self.map_num[self.a][self.b]
def next_num(self, action):
ori_a = self.a
ori_b = self.b
# If user input is not recognized or user goes outbound,
# use ori_a and ori_b to go back to current num again.
if action == 'North':
self.a -= 1
elif action == 'South':
self.a += 1
elif action == 'West':
self.b -= 1
elif action == 'East':
self.b += 1
else:
print("NA")
return self.map_num[ori_a][ori_b]
if self.a < 0 or self.a > 3 or self.b < 0 or self.b > 3:
print:("Out of Bound")
return self.map_num[ori_a][ori_b]
val = self.map_num[self.a][self.b]
return val
def opening_num(self):
val = self.start_num
return val
def last_num(self, a, b):
val = self.map_num[a][b]
return val
a_map = Map(2, 1)
a_game = Engine(a_map)
a_game.play()
The good news is it works perfectly if we let our adventurer stays within the grid.
However, if we accidentally/purposely moves the adventurer out of the grid, some weird behavior will show up:
21 (# starting coordinate)
> North
11
>North
1
> North
1
> North
31
> North
21
> North
11
> North
1
> North
Traceback (most recent call last):
File “test.py”, line 72, in
a_game.play()
File “test.py”, line 19, in play
current_num = self.map_num.next_num(action)
File “test.py”, line 56, in next_num
return self.map_num[new_a][new_b]
IndexError: list index out of range
It loops the column two times then comes to an IndexError, it doesn’t go through the code:
if self.a < 0 or self.a > 3 or self.b < 0 or self.b > 3:
print:("Out of Bound")
return self.map_num[new_a][new_b]
And if I type in words (i.e “big”) other than North/South/West/East:
> big
Traceback (most recent call last):
File “test.py”, line 72, in
a_game.play()
File “test.py”, line 19, in play
current_num = self.map_num.next_num(action)
File “test.py”, line 52, in next_num
print(“NA”)
UnboundLocalError: local variable ‘print’ referenced before assignment
It does’t go through code:
else:
print("NA")
return self.map_num[new_a][new_b]
These two are the major problems I’m encountering right now.
Again, thanks for the helps from @florian and @ulfen69 !