你是一个python工程师我是一个python新手请你给我一个用python写的井字游戏并仔细讲解让我能够理解
时间: 2024-03-13 15:47:38 浏览: 91
好的,我可以为您提供一个简单的井字游戏的Python代码,并进行详细的讲解。
代码如下:
```python
board = [' ' for x in range(10)]
def insertLetter(letter, pos):
board[pos] = letter
def spaceIsFree(pos):
return board[pos] == ' '
def printBoard(board):
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
def isWinner(bo, le):
return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or (bo[1] == le and bo[2] == le and bo[3] == le) or (bo[1] == le and bo[4] == le and bo[7] == le) or (bo[2] == le and bo[5] == le and bo[8] == le) or (bo[3] == le and bo[6] == le and bo[9] == le) or (bo[1] == le and bo[5] == le and bo[9] == le) or (bo[3] == le and bo[5] == le and bo[7] == le)
def playerMove():
run = True
while run:
move = input('Please select a position to place an \'X\' (1-9): ')
try:
move = int(move)
if move > 0 and move < 10:
if spaceIsFree(move):
run = False
insertLetter('X', move)
else:
print('Sorry, this space is occupied!')
else:
print('Please type a number within the range!')
except:
print('Please type a number!')
def computerMove():
possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
move = 0
for let in ['O', 'X']:
for i in possibleMoves:
boardCopy = board[:]
boardCopy[i] = let
if isWinner(boardCopy, let):
move = i
return move
cornersOpen = []
for i in possibleMoves:
if i in [1,3,7,9]:
cornersOpen.append(i)
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
if 5 in possibleMoves:
move = 5
return move
edgesOpen = []
for i in possibleMoves:
if i in [2,4,6,8]:
edgesOpen.append(i)
if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
def selectRandom(li):
import random
ln = len(li)
r = random.randrange(0,ln)
return li[r]
def isBoardFull(board):
if board.count(' ') > 1:
return False
else:
return True
def main():
print('Welcome to Tic Tac Toe!')
printBoard(board)
while not(isBoardFull(board)):
if not(isWinner(board, 'O')):
playerMove()
printBoard(board)
else:
print('Sorry, O\'s won this time!')
break
if not(isWinner(board, 'X')):
move = computerMove()
if move == 0:
print('Tie Game!')
else:
insertLetter('O', move)
print('Computer placed an \'O\' in position', move , ':')
printBoard(board)
else:
print('X\'s won this time! Good Job!')
break
if isBoardFull(board):
print('Tie Game!')
main()
```
这段代码实现了一个简单的井字游戏,其中 X 代表玩家,O 代表电脑。现在我们逐行来解释这段代码的功能。
首先,我们创建一个包含10个空格的列表,表示游戏板的状态。
```python
board = [' ' for x in range(10)]
```
接着,我们定义了三个函数:insertLetter,spaceIsFree和printBoard。
```python
def insertLetter(letter, pos):
board[pos] = letter
def spaceIsFree(pos):
return board[pos] == ' '
def printBoard(board):
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
```
insertLetter函数用于将X或O插入到给定位置,spaceIsFree函数用于检查给定位置是否为空,printBoard函数用于显示游戏板的当前状态。
接着,我们定义了两个函数isWinner和playerMove。
```python
def isWinner(bo, le):
return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or (bo[1] == le and bo[2] == le and bo[3] == le) or (bo[1] == le and bo[4] == le and bo[7] == le) or (bo[2] == le and bo[5] == le and bo[8] == le) or (bo[3] == le and bo[6] == le and bo[9] == le) or (bo[1] == le and bo[5] == le and bo[9] == le) or (bo[3] == le and bo[5] == le and bo[7] == le)
def playerMove():
run = True
while run:
move = input('Please select a position to place an \'X\' (1-9): ')
try:
move = int(move)
if move > 0 and move < 10:
if spaceIsFree(move):
run = False
insertLetter('X', move)
else:
print('Sorry, this space is occupied!')
else:
print('Please type a number within the range!')
except:
print('Please type a number!')
```
isWinner函数用于检查给定的玩家是否是胜者,playerMove函数用于获取玩家的输入并将X插入到给定位置。
接着,我们定义了一个名为computerMove的函数,该函数模拟电脑的移动。该函数首先找到所有空格位置,然后按照优先级查找可以获胜的位置、角落位置、中心位置和边缘位置。
```python
def computerMove():
possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
move = 0
for let in ['O', 'X']:
for i in possibleMoves:
boardCopy = board[:]
boardCopy[i] = let
if isWinner(boardCopy, let):
move = i
return move
cornersOpen = []
for i in possibleMoves:
if i in [1,3,7,9]:
cornersOpen.append(i)
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
if 5 in possibleMoves:
move = 5
return move
edgesOpen = []
for i in possibleMoves:
if i in [2,4,6,8]:
edgesOpen.append(i)
if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
```
我们还定义了一个名为selectRandom的辅助函数,该函数从给定列表中随机选择一个元素。
```python
def selectRandom(li):
import random
ln = len(li)
r = random.randrange(0,ln)
return li[r]
```
接着,我们定义了isBoardFull函数用于检查游戏板是否已满。
```python
def isBoardFull(board):
if board.count(' ') > 1:
return False
else:
return True
```
最后,我们定义了一个名为main的函数,用于执行游戏的主要逻辑。该函数首先显示欢迎信息和初始游戏板状态,然后重复执行以下操作,直到游戏板已满:
- 如果电脑没有获胜,则玩家进行移动,并显示更新后的游戏板。
- 如果玩家没有获胜,则电脑进行移动,并显示更新后的游戏板。
- 如果玩家或电脑获胜,则停止游戏并显示获胜者。
如果游戏板已满并且没有获胜者,则停止游戏并显示平局。
```python
def main():
print('Welcome to Tic Tac Toe!')
printBoard(board)
while not(isBoardFull(board)):
if not(isWinner(board, 'O')):
playerMove()
printBoard(board)
else:
print('Sorry, O\'s won this time!')
break
if not(isWinner(board, 'X')):
move = computerMove()
if move == 0:
print('Tie Game!')
else:
insertLetter('O', move)
print('Computer placed an \'O\' in position', move , ':')
printBoard(board)
else:
print('X\'s won this time! Good Job!')
break
if isBoardFull(board):
print('Tie Game!')
main()
```
这就是这个井字游戏的Python代码及其详细解释。希望这能帮助您更好地理解Python编程。
阅读全文