this is a past yr mid-term exam qns, around the topic of data abstraction. I'm limited to only using tuples and these are the functions I was guided to define.
make_state() creates empty state object for game
get_square(s,x,y) will return symbol in the game state object s at the grid location(x,y) where 0<_x,y<_2. If grid empty, function returns None
move(s,x,y,player) returns a new state object after player(where player either 'X' or 'O' makes a move at the grid location (x,y). If the move is invalid, False is returned instead.
check_rep(s) return True if s is a valid game state object, or False otherwise.
def make_state():
return ((0,0,0),(0,0,0),(0,0,0))
def get_square(s,x,y):
if s[x][y]==0:
return None
elif s[x][y]==1:
return 'X'
elif s[x][y]==2:
return 'O'
def check_rep(s):
if len(s)!=3:
return False
for row in s:
if len(row)!=3:
return False
for col in row:
if col not in (0,1,2):
return False
return True
The problem comes when I have to implement move(s,x,y,player)
def move(s,x,y,player):
if check_rep(s)==False:
return False
elif get_square(s,x,y):
return False
elif player not in ('X','O'):
return False
symbol=1
if player=='O':
symbol=2
a,b=0,0
for row in s:
for col in row:
if x==a and y==b:
new_row=row[:y]+(symbol,)+row[y+1:]
return s[:x]+(new_row,)+s[x+1:]
b+=1
a+=1
My test cases
s=make_state()
s1=move(s,0,0,'X')
s2=move(s1,1,1,'X')
s3=move(s2,2,2,'O')
Error messages from Python seem to show s2 is a NoneType object, can someone tell me why it will end up as None?