我正在尝试创建一个连接四游戏,但我无法弄清楚如何在棋盘上打印棋子。我需要它在用户输入的列中的最低可用点处打印X.每次运行程序时,我都会得到相同的空白6乘7。请帮忙。谢谢!
#ConnectFour
numRows=6
numCols=7
numPlayers=2
board=[]
checkers=['X','O']
turn=0
win = False
for row in range(numRows):
tempList=[]
for col in range(numCols):
tempList.append('.')
board.append(tempList)
while not win:
turn = (turn+1)%numPlayers
userCol = input ("Player"+str(turn+1)+"please enter your col: ")
while not userCol.isdigit() or not int(userCol) in range(numCols):
userCol = input ("Player"+str(turn+1)+"please enter your col: ")
for row in range(numRows):
for col in range(numCols):
print(board[row][col], end='')
print()
for repeat in range(numRows-2):
for row in range(numRows,-1,-1):
for col in range(numCols):
if board[row][int(userCol)]==".":
board[row+1][int(userCol)]="X"
print
break
#print board
for row in range(numRows):
for col in range(numCols):
print(board[row+1][userCol],end=' ')
print()
print ("Player", checkers[turn],"has won the game.")
答案 0 :(得分:0)
这是我注意到的:
range(numRows - 1, -1, -1)
或reversed(range(numRows))
。board[row][int(userCol)] = 'X'
而不是row+1
应该是row
。另外,userCol
应该col
吗?否则它只会打印一列而不是整个最终板。一般评论:
通常,您可以通过避免for i in range(x): do_something(mylist[i])
反模式而不是使用python样式的迭代来实现更简洁和可读的python代码:for item in mylist: do_something(item)
。
我会重写第29-35行。但在你这样做之前,要问问自己这些线应该做什么。如果我正确理解了该任务,那么您应该只需要一个for
循环。