Issue
I’m making a game similar to tic-tac-toe, called strikes and circles. The most noticeable difference is that the board is 4 by 4, rather than 3 by 3. (I am a beginner with coding in Python so please bear with me.) I took a chunk of code from an online post that lets you make a tic-tac-toe board, and altered it to make the board the way I needed it. I am now getting an error that states “TypeError: can only concatenate str(not "list") to str.”
theBoard = {'a1': ' ' , 'a2': ' ' , 'a3': ' ' , 'a4': ' ' ,
'b1': ' ' , 'b2': ' ' , 'b3': ' ' , 'b4': ' ' ,
'c1': ' ' , 'c2': ' ' , 'c3': ' ' , 'c4': ' ' ,
'd1': ' ' , 'd2': ' ' , 'd3': ' ' , 'd4': ' ' }
def printboard(board):
print(board['a1']+['|']+['a2']+['|']+['a3']+['|']+['a4'])
print('-+-+-+-')
print(board['b1']+['|']+['b2']+['|']+['b3']+['|']+['b4'])
print('-+-+-+-')
print(board['c1']+['|']+['c2']+['|']+['c3']+['|']+['c4'])
print('-+-+-+-')
print(board['d1']+['|']+['d2']+['|']+['d3']+['|']+['d4'])
I tried changing every + other than the ones in
print('-+-+-+-')
To “, “ as well as removing the word board from everything below line 10 and changing line ten from
def printboard(board):
To
def printboard(self):
And neither attempts worked the way I had hoped.
I just want a 4 by 4 tic-tac-toe board that works.
Solution
What you are doing is wrong. You are trying to do ['a2']
and so on which returns nothing but a list. What you expect is the value of the a2
key from the board
variable. Therefore, it needs to be changed to board['a2']
Try this:
def printboard(board):
print(board['a1']+'|'+board['a2']+'|'+board['a3']+'|'+board['a4'])
print('-+-+-+-')
print(board['b1']+'|'+board['b2']+'|'+board['b3']+'|'+board['b4'])
print('-+-+-+-')
print(board['c1']+'|'+board['c2']+'|'+board['c3']+'|'+board['c4'])
print('-+-+-+-')
print(board['d1']+'|'+board['d2']+'|'+board['d3']+'|'+board['d4'])
You could also optimize your function by using a for loop:
def printboard(board):
for v in ['a','b','c','d']:
print('|'.join([board[f'{v}{i}'] for i in range(1,5)]))
if v != 'd': print('-+-+-+-') # since you don't want this at last line
Edit: thanks to @Swifty
Answered By - The Myth Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.