本帖最后由 Stubborn 于 2024-8-12 16:31 编辑
只要你不作弊,肯定赢不了的井字棋,你咸鱼好久了,开始冒泡啦?
# -*- coding: utf-8 -*-
# !/usr/bin/python3
"""
@ Version : ??
@ Author : Alex
@ Software : Pycharm
@ Time : 2020/3/21 下午8:30
"""
MARKERS = ['_', 'O', 'X']
PRINTING_TRIADS = ((0, 1, 2), (3, 4, 5), (6, 7, 8))
def view_bar():
import time, sys
for i in range(21):
sys.stdout.write('\r%s > %d%%' % ("#" * i, int((i / 20) * 100)))
sys.stdout.flush()
time.sleep(0.05)
def vacancy(board):
"""棋盘是还有空位"""
return 0 in board
def winner(board):
"""是否有获胜者
1,-1 有胜负
0 表示没有胜负,没有结束,或者平局
"""
lines = [board[0:3], board[3:6], board[6:9], board[0::3], board[1::3], board[2::3], board[0::4], board[2:7:2]]
return 1 if [1] * 3 in lines else -1 if [-1] * 3 in lines else 0
def score(board, player=-1, next_player=1, alpha=-2, beta=2):
win = winner(board)
if win != 0:
return win
if not vacancy(board):
return 0
for move in range(9):
if board[move] == 0:
board[move] = player
val = score(board, next_player, player)
board[move] = 0
if player == 1:
alpha = max(val, alpha)
beta = min(val, beta)
return alpha if player == 1 else beta
def moves(board):
scores = 0
mo = 0
for move in range(9):
'''找出空位,计算当前棋局得分'''
if board[move] == 0:
board[move] = 1
val = score(board)
board[move] = 0
'''记录最高分,和位置'''
mo = move if val >= scores else mo
return mo
def board_print(board):
"""打印当前棋盘"""
for row in PRINTING_TRIADS:
r = ' '
for hole in row:
r += MARKERS[board[hole]] + ' '
print(r)
def main():
"""
程序主入口
"""
# 决定先手
next_move = "PLAYER"
opt = input("输入'C'电脑先手,否则默认玩家先手,友情提示(如果下不赢,可以输入下面作弊代码!\nCopy代码:I love Fishc\n请输入:")
if opt in ['C', 'c']:
next_move = "COMPUTER"
# 初始化棋盘
board = [0 for _ in range(9)]
# Go 开始游戏,
while vacancy(board) and winner(board) == 0:
board_print(board)
if next_move == "PLAYER" and vacancy(board):
"""处理落子无效位置,超出范围,以及有子"""
try:
location = int(input("请输入你要落子的位置(1-9):")) - 1
assert board[location] == 0
assert -1 < location < 9
board[location] = -1
next_move = "COMPUTER"
except (ValueError, AssertionError, IndexError):
print("输入有误,重新落子")
if opt == 'I love Fishc':
print('鱼友最可爱了')
location = board.index(0)
print("\nComputer最终决定下在", location + 1)
board[location] = 1
next_move = "PLAYER"
elif next_move == "COMPUTER" and vacancy(board):
print('COMPUTER正在开启暴力搜索\t')
view_bar()
location = moves(board)
print("\nComputer最终决定下在", location + 1)
board[location] = 1
next_move = "PLAYER"
# 输出结果
board_print(board)
print('这次游戏是', ["平局", "Computer赢了", "你赢了"][winner(board)])
|