【发布时间】:2021-03-16 18:30:53
【问题描述】:
我正在为 5x5 井字游戏编写代码。它似乎工作正常,但现在在运行程序的过程中,输入数字后没有任何反应,python shell 在顶部显示“正在执行命令。请等待结果”,但没有任何反应。我不确定问题是什么,因为在此之前它似乎工作正常。任何建议都会有很大帮助。
from random import randint
def displayBoard(board): #printing board with each list on new line
for i in board:
print(*i,sep=' ')
def checkIfLegal(number,board):
if number<=0 or number>25: #if number in correct range
print("That cell does not exist")
return False
number=number-1 #to match indices
row=int(number/5)
col=number
if col>4:
col=int(col%5)
if board[row][col]=="X" or board[row][col]=="O": #checking if cell is occupied
print("That cell is occupied")
return False
return True
def updateBoard(number,board,symbol):
number=number-1
row=int(number/5)
col=number
if col>4:
col=int(col%5)
board[row][col]=symbol #change cell to player symbol
def computerMove(board):
number=randint(0,24)
row=int(number/5)
col=number
if col>4:
col=int(col%5)
while board[row][col]=="X" or board[row][col]=="O": #computer chooses a random integer between 0 and 24 until the cell is not taken
number=randint(0,24)
board[row][col]="O" #change cell to computer symbol ("O")
def checkWinner(board):
#check rows
for row in board:
if len(set(row))==1: #if there is only one symbol in the board
return True
#check columns
for col in range(5):
completecol=True
for row in range(5):
if board[row][col]!=board[row-1][col]:
completecol=False
break
if completecol:
return True
#check diagonal
if len(set(board[row][row] for row in range(5)))==1:
return True
if len(set(board[row][5-row-1] for row in range(5)))==1:
return True
return False
def main():
board=[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]] #initialize board
turns=0 #turn counter
print("The board is numbered from 1 to 25 as per the following:")
displayBoard(board)
print("Player starts first. Simply input the number of the cell you want to occupy. Player's move is marked with X. Computer's move is marked with O.")
play=input("Start? y/n: ") #if the player chooses y, start game loop
while play=="y":
number=int(input("Which cell would you like to occupy? "))
while checkIfLegal(number,board)==False: #player chooses a number until it is legal
number=int(input("Please enter a new cell: "))
checkIfLegal(number,board)
if checkIfLegal(number,board)==True: #once number is legal, update board
updateBoard(number,board,"X")
number=number-1
row=int(number/5)
col=number
if col>4:
col=int(col%5)
if checkWinner(board)==True:
displayBoard(board)
print("Congratulations! You won!")
break
turns+=1
if turns==25: #if 25 turns are taken with no winner, board is full and it is a tie.
print("Tie game!")
break
computerMove(board)
if checkWinner(board)==True:
displayBoard(board)
print("Too bad. Computer won!")
break
turns+=1
displayBoard(board)
main()
[1]:https://i.stack.imgur.com/U4QwX.png[python 外壳]
【问题讨论】:
标签: python python-3.x loops tic-tac-toe