python井字棋盤(python井字棋遊戲代碼)

本文目錄一覽:

python 井字棋 ALPHA-BETA剪枝演算法和暴力演算法 具體代碼

#!/usr/bin/env python

”’Tic tac toe in python, Minimax with alpha-beta pruning.”’

import sys

import random

import getopt

# Board: array of 9 int, positionally numbered like this:

# 0 1 2

# 3 4 5

# 6 7 8

# Well-known board positions

WINNING_TRIADS = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7),

(2, 5, 8), (0, 4, 8), (2, 4, 6))

PRINTING_TRIADS = ((0, 1, 2), (3, 4, 5), (6, 7, 8))

# The order in which slots get checked for absence of a player’s token:

SLOTS = (0, 1, 2, 3, 4, 5, 6, 7, 8)

# Internal-use values. Chosen so that the “winner” of a finished

# game has an appropriate value, as X minimizes and O maximizes

# the board’s value (function board_valuation() defines “value”)

# Internally, the computer always plays Os, even though the markers[]

# array can change based on -r command line flag.

X_token = -1

Open_token = 0

O_token = 1

# Strings for output: player’s markers, phrase for end-of-game

MARKERS = [‘_’, ‘O’, ‘X’]

END_PHRASE = (‘draw’, ‘win’, ‘loss’)

HUMAN = 1

COMPUTER = 0

def board_valuation(board, player, next_player, alpha, beta):

”’Dynamic and static evaluation of board position.”’

# Static evaluation – value for next_player

wnnr = winner(board)

if wnnr != Open_token:

# Not a draw or a move left: someone won

return wnnr

elif not legal_move_left(board):

# Draw – no moves left

return 0 # Cat

# If flow-of-control gets here, no winner yet, not a draw.

# Check all legal moves for “player”

for move in SLOTS:

if board[move] == Open_token:

board[move] = player

val = board_valuation(board, next_player, player, alpha, beta)

board[move] = Open_token

if player == O_token: # Maximizing player

if val alpha:

alpha = val

if alpha = beta:

return beta

else: # X_token player, minimizing

if val beta:

beta = val

if beta = alpha:

return alpha

if player == O_token:

retval = alpha

else:

retval = beta

return retval

def print_board(board):

”’Print the board in human-readable format.

Called with current board (array of 9 ints).

”’

for row in PRINTING_TRIADS:

for hole in row:

print MARKERS[board[hole]],

print

def legal_move_left(board):

”’ Returns True if a legal move remains, False if not. ”’

for slot in SLOTS:

if board[slot] == Open_token:

return True

return False

def winner(board):

”’ Returns -1 if X wins, 1 if O wins, 0 for a cat game,

0 for an unfinished game.

Returns the first “win” it finds, so check after each move.

Note that clever choices of X_token, O_token, Open_token

make this work better.

”’

for triad in WINNING_TRIADS:

triad_sum = board[triad[0]] + board[triad[1]] + board[triad[2]]

if triad_sum == 3 or triad_sum == -3:

return board[triad[0]] # Take advantage of “_token” values

return 0

def determine_move(board):

”’ Determine Os next move. Check that a legal move remains before calling.

Randomly picks a single move from any group of moves with the same value.

”’

best_val = -2 # 1 less than min of O_token, X_token

my_moves = []

for move in SLOTS:

if board[move] == Open_token:

board[move] = O_token

val = board_valuation(board, X_token, O_token, -2, 2)

board[move] = Open_token

print “My move”, move, “causes a”, END_PHRASE[val]

if val best_val:

best_val = val

my_moves = [move]

if val == best_val:

my_moves.append(move)

return random.choice(my_moves)

def recv_human_move(board):

”’ Encapsulate human’s input reception and validation.

Call with current board configuration. Returns

an int of value 0..8, the Human’s move.

”’

looping = True

while looping:

try:

inp = input(“Your move: “)

yrmv = int(inp)

if 0 = yrmv = 8:

if board[yrmv] == Open_token:

looping = False

else:

print “Spot already filled.”

else:

print “Bad move, no donut.”

except EOFError:

print

sys.exit(0)

except NameError:

print “Not 0-9, try again.”

except SyntaxError:

print “Not 0-9, try again.”

if looping:

print_board(board)

return yrmv

def usage(progname):

”’Call with name of program, to explain its usage.”’

print progname + “: Tic Tac Toe in python”

print “Usage:”, progname, “[-h] [-c] [-r] [-x] [-X]”

print “Flags:”

print “-x, -X: print this usage message, then exit.”

print “-h: human goes first (default)”

print “-c: computer goes first”

print “-r: computer is X, human is O”

print “The computer O and the human plays X by default.”

def main():

”’Call without arguments from __main__ context.”’

try:

opts, args = getopt.getopt(sys.argv[1:], “chrxX”,

[“human”, “computer”, “help”])

except getopt.GetoptError:

# print help information and exit:

usage(sys.argv[0])

sys.exit(2)

next_move = HUMAN # Human goes first by default

for opt, arg in opts:

if opt == “-h”:

next_move = HUMAN

if opt == “-c”:

next_move = COMPUTER

if opt == “-r”:

MARKERS[-1] = ‘O’

MARKERS[1] = ‘X’

if opt in (“-x”, “-X”, “–help”):

usage(sys.argv[0])

sys.exit(1)

# Initial state of board: all open spots.

board = [Open_token, Open_token, Open_token, Open_token, Open_token,

Open_token, Open_token, Open_token, Open_token]

# State machine to decide who goes next, and when the game ends.

# This allows letting computer or human go first.

while legal_move_left(board) and winner(board) == Open_token:

print

print_board(board)

if next_move == HUMAN and legal_move_left(board):

humanmv = recv_human_move(board)

board[humanmv] = X_token

next_move = COMPUTER

if next_move == COMPUTER and legal_move_left(board):

mymv = determine_move(board)

print “I choose”, mymv

board[mymv] = O_token

next_move = HUMAN

print_board(board)

# Final board state/winner and congratulatory output.

try:

# “You won” should never appear on output: the program

# should always at least draw.

print [“Cat got the game”, “I won”, “You won”][winner(board)]

except IndexError:

print “Really bad error, winner is”, winner(board)

sys.exit(0)

#——-

if __name__ == ‘__main__’:

try:

main()

except KeyboardInterrupt:

print

sys.exit(1)

求python井字遊戲程序的map用途詳解

map本身是python中的關鍵字–一個內置函數,對第二個參數的每一個元素執行第一個參數指定的函數。

但上面的表達式明顯不是這個概念,它應該是在print_board函數的外面將map定義成一個二維數組(這樣的做法不好哦)

用python寫小程序

我覺得用3個列表,選中的時候,變成1,然後每輪計算橫豎斜是不是相加=3就行。

[0,0,0]

[0,0,0]

[0,0,0]

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/245543.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 13:09
下一篇 2024-12-12 13:09

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29

發表回復

登錄後才能評論