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/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

发表回复

登录后才能评论