[英]Python Connect 4 Game- Print X on Board
I am trying to create a connect four game but I cannot figure out how to print the checkers on the board. 我正在尝试创建一个四通游戏,但我不知道如何在棋盘上打印棋子。 I need it to print the X at the lowest available spot in the column that the user inputted. 我需要它在用户输入的列中的最低可用位置打印X。 Each time I run the program, I get the same blank 6 by 7 board. 每次运行程序时,我都会得到相同的空白乘以6乘7板。 Please help. 请帮忙。 thank you! 谢谢!
#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.")
Here's what I noticed: 这是我注意到的:
range(numRows - 1, -1, -1)
or reversed(range(numRows))
instead. 第30行:看起来像是一个错误的错误,您可能希望使用range(numRows - 1, -1, -1)
或reversed(range(numRows))
。 board[row][int(userCol)] = 'X'
instead 我想您可能要用board[row][int(userCol)] = 'X'
代替 row+1
should be row
. 第41行:看起来像是另一个错误, row+1
应该是row
。 Also, should userCol
just be col
? 另外, userCol
应该只是col
吗? Otherwise it'll only be printing one column instead of the entire final board. 否则,它将只打印一列,而不是整个最终版。 General remarks: 一般说明:
Generally you can achieve more concise and readable python code by avoiding the for i in range(x): do_something(mylist[i])
anti-pattern and instead using python-style iteration: for item in mylist: do_something(item)
. 通常,通过避免for i in range(x): do_something(mylist[i])
的for i in range(x): do_something(mylist[i])
反模式,而使用python样式的迭代: for item in mylist: do_something(item)
可以实现更简洁和可读的python代码。
I would re-write lines 29-35. 我将重新编写29-35行。 But before you do so, ask yourself exactly what those lines are supposed to do. 但是在您这样做之前,请先问问自己这些行应该做什么。 If I understand the task correctly, you should only need one for
loop there. 如果我对任务的理解正确,那么那里只需要一个for
循环即可。
Ninja edit: Also, once that's working, don't forget to handle the case that the player entered a valid column number, yet that column is completely filled, in which case you probably want to ask the same player to choose a new column. 忍者编辑:此外,一旦可行,别忘了处理玩家输入有效列号但该列已完全填满的情况,在这种情况下,您可能想请同一个玩家选择新列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.