❶ 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版本五子棋
机器博弈是人工智能领域的重要分支,它的研究对象多以复杂的棋牌类智力游戏为主,已经得到解决的棋类游戏,几乎全部都应归功于机器博弈近半个世纪的发展。计算机解决问题的优势在于能把不易解析的问题,借助于现代计算机的运算速度优势枚举出所有的合理情形而得解;然而,博弈问题的复杂程度决定了它不能过度依赖机器的计算能力。许多待解决的或已经解决的棋类,其状态空间复杂度或博弈树复杂度量级都太过庞大,所以我们需要添加约束,并且采用合理的算法进行优化。
五子棋问题是人工智能中的一个经典问题。当今世界,AlphaGo已经执围棋之牛耳,五子棋领域却鲜少有人问津。本文根据课堂所学知识结合文献、博客,基于两种开发语言实现了一个智能对战的AI五子棋游戏平台。
本文所做工作如下:
(1) 五子棋界面实现;
(2) 智能判定棋盘走势;
(3) 改进了棋盘扫描方式;
(4) 改良了系统评分表评估方式;
(5) 实现了基于点评分表估值找出最佳落子方式。
五子棋AI问题的最大问题是如何实现智能对弈,即当人落子之后,算法如何解读当前的棋盘并且对其进行分析解读,得到电脑方的最佳落子点。其次还有一个问题是如何判断胜利,这可以作为前面棋盘局势判定的一个子问题,也可以看做是一个单独的问题,不过这个问题总体来说较为简单,所以不做详细说明。
五子棋的整体知识构建包含以下部分:
(1) 棋盘局面表示法
(2) 棋局胜利判定
(3) 棋型知识库
(4) 智能博弈流程
对于问题(1),采用数组表示法。棋盘中的各交叉点有三种状态,不妨令 0表示空(未放置棋子) ,-1 表示有黑子 ,1 表示有白子,数组表示法的基本思想是:以交叉点对应的数组索引值来表达物理位置 ,以交叉点对应的元素值表达状态(空、 黑子、 白子)。令 V = {0 ,1 ,-1} ,棋盘 的第 i 个交叉点的状态 Si ∈V ,任何棋局都可以表示成一个 n ×n 的二元组。
对于问题(2), 采用数组表示法时,想知道任意两个元素 Si 和Sj 是否共线,要通过 i 和 j 之间的数值规律来判断。从这方面看,数组表示法是一种原始、低效的表示方法,但是对于评分表算法来说其性能损失是可以接受的。要判断是否有一方已经胜利,只需要对整个棋盘判定当前落子点的纵、横、正斜、反斜四个方向的最长延伸出四个位置看是否能连成一条同色直线即可。具体的操作可以视为:从落子点出发,向两个方向延伸,如果遇到同色,那么计数器加一,遇到非同色(空白或者异色)则停止在该方向的延伸,一个计数器记下该方向上的两头的连续同色棋子数。等到四个方向都探索完毕,如果四个计数器中有一个计数器达到了5,那么即可判断出已经有五子连珠了,此局结束。
问题(3)棋型知识库主要包括各种既定的棋盘形式,有如下几种:
² 活四 :有两个连五点(即有两个点可以形成五),图中白点即为连五点。当活四出现的时候,整个局势已经无法阻止连五了,活四的归属方一定能取得胜利;
² 冲四 :有一个连五点,如下面三图,均为冲四棋型。图中白点为连五点。 相对比活四来说,冲四的威胁性就小了很多,因为这个时候,只要跟着防守在那个唯一的连五点上,冲四就没法形成连五。
² 活三 :可以形成活四的三,如下图,代表两种最基本的活三棋型。图中白点为活四点。活三棋型是进攻中最常见的一种,因为活三之后,如果对方不以理会,将可以下一手将活三变成活四,而活四是无法防守的。所以,面对活三的时候,需要非常谨慎对待。在没有更好的进攻手段的情况下,必须对其进行防守,以防止其形成可怕的活四棋型。
² 眠三: 只能够形成冲四的三,如下各图,分别代表最基础的六种眠三形状。图中白点代表冲四点。眠三的棋型与活三的棋型相比,危险系数下降不少,因为眠三棋型即使不去防守,下一手它也只能形成冲四,而对于单纯的冲四棋型,是可以很简单的防守住的。
² 活二 :能够形成活三的二,如下图,是三种基本的活二棋型。图中白点为活三点。
² 眠二 :能够形成眠三的二。图中四个为最基本的眠二棋型,细心且喜欢思考的同学会根据眠三介绍中的图2-13找到与下列四个基本眠二棋型都不一样的眠二。图中白点为眠三点。
对于上述的棋型,我们主要考虑的是活四、冲四、活三、眠三这几种主要的进攻棋型的防守与构成,整体棋型遵从以下原则:优先考虑数目,同等数目的情况下考虑是活是眠。评分表算法的设计整体偏向于防守。
对于问题(4),当下棋型的评估分析,算法严格遵从以下流程:
当人类方落下一子,算法启动,扫描全局,得到人类棋子的集合和电脑棋子的集合。全局扫描之后,对当前局势进行排序、计算。对每个集合的每个空白点位置打分,打分依据是根据这个点周围四个方向上的同色连续棋子的数量。按照这些最后得到的评分,得出最大值。得到人类方和电脑方的两个最大值之后,进行比较,如果人类方局势较好(分数较高),则算法将下一次落子位置设置为人类方得分最高的点,尽力降低人类方的下一步得分;如果电脑方的分数较高,那么则直接在使得分数最高的点落子即可。
本次课程设计,一共设计了两个版本,一个Java版本,为19X19的棋盘,配备简单的消息提示,基于AWT实现GUI,开发工具IntelliJ IDEA 2018.1
另一个版本是使用Python设计,核心算法相同,但是受限于图片源文件,为15X15棋盘,基于pygame实现GUI,开发工具是:JetBrains PyCharm 2018.2.4 x64
因为近期时间较为紧迫,所以《人工智能》这门课我选择了较为简单的五子棋问题进行课程设计。在本次课程设计中,我的编码能力、调试能力、算法解读实现能力、函数优化能力等各方面有了长足的进步。在本次的设计过程中也出现了几个问题,下面对这些问题进行一个简单的描述:
(1) 对棋盘局势的判断力不够,因为只是简单的对当前的棋盘局势进行判断,基本等同于一个粗通规则而且天赋不高的五子棋选手。如果对手很细心,而且熟练经营各种布局策略,那么基本这个算法就会被钻研出习惯,从而被轻易针对,而且针对方案百试不爽;
(2) 判断棋局形式的时候对边界的评分算法跟中心区域的评分算法一致,无法有效提前识别边界,降低边界空白点的权重;
(3) 用户图形界面需要改进,另外可以增设PK模式以及选色、选择棋盘大小功能等;
后续可以尝试用博弈树算法尝试与当前算法进行比较。评分表算法牺牲了更高的精度,以求迅速的得出最佳落子点;而博弈树可以通过提前落子进行全局预判进行更全方位的对人类方的围追堵截。
另外,可以通过在课堂上学到的知识,比如BFS、DFS、A*算法、决策树算法 等应用于五子棋的智能决策中。
《人工智能》这门课让我对于图、知识表示、智能决策等各个方面有了更好地认识与体验,课堂设计内容充实有趣,让我受益匪浅,希望今后可以更加深入这个方面,并且将课堂上学到的知识应用于实践之中。
❸ 请用PYTHON编一个小游戏,如五子棋,连连看,贪吃蛇,扫雷,计算器等等
#!/usr/bin/python
from Tkinter import *
import random
class snake(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.body = [(0,0)]
self.bodyid = []
self.food = [ -1, -1 ]
self.foodid = -1
self.gridcount = 10
self.size = 500
self.di = 3
self.speed = 500
self.top = self.winfo_toplevel()
self.top.resizable(False, False)
self.grid()
self.canvas = Canvas(self)
self.canvas.grid()
self.canvas.config(width=self.size, height=self.size,relief=RIDGE)
self.drawgrid()
s = self.size/self.gridcount
id = self.canvas.create_rectangle(self.body[0][0]*s,self.body[0][1]*s,
(self.body[0][0]+1)*s, (self.body[0][1]+1)*s, fill="yellow")
self.bodyid.insert(0, id)
self.bind_all("<KeyRelease>", self.keyrelease)
self.drawfood()
self.after(self.speed, self.drawsnake)
def drawgrid(self):
s = self.size/self.gridcount
for i in range(0, self.gridcount+1):
self.canvas.create_line(i*s, 0, i*s, self.size)
self.canvas.create_line(0, i*s, self.size, i*s)
def drawsnake(self):
s = self.size/self.gridcount
head = self.body[0]
new = [head[0], head[1]]
if self.di == 1:
new[1] = (head[1]-1) % self.gridcount
elif self.di == 2:
new[0] = (head[0]+1) % self.gridcount
elif self.di == 3:
new[1] = (head[1]+1) % self.gridcount
else:
new[0] = (head[0]-1) % self.gridcount
next = ( new[0], new[1] )
if next in self.body:
exit()
elif next == (self.food[0], self.food[1]):
self.body.insert(0, next)
self.bodyid.insert(0, self.foodid)
self.drawfood()
else:
tail = self.body.pop()
id = self.bodyid.pop()
self.canvas.move(id, (next[0]-tail[0])*s, (next[1]-tail[1])*s)
self.body.insert(0, next)
self.bodyid.insert(0, id)
self.after(self.speed, self.drawsnake)
def drawfood(self):
s = self.size/self.gridcount
x = random.randrange(0, self.gridcount)
y = random.randrange(0, self.gridcount)
while (x, y) in self.body:
x = random.randrange(0, self.gridcount)
y = random.randrange(0, self.gridcount)
id = self.canvas.create_rectangle(x*s,y*s, (x+1)*s, (y+1)*s, fill="yellow")
self.food[0] = x
self.food[1] = y
self.foodid = id
def keyrelease(self, event):
if event.keysym == "Up" and self.di != 3:
self.di = 1
elif event.keysym == "Right" and self.di !=4:
self.di = 2
elif event.keysym == "Down" and self.di != 1:
self.di = 3
elif event.keysym == "Left" and self.di != 2:
self.di = 4
app = snake()
app.master.title("Greedy Snake")
app.mainloop()
贪食蛇
❹ 求助,写一个python代码,用于简单的复盘统计
下面是一个简单的 Python 代码,用于统计复盘:
运行代码后,它将持续询问用户输入比赛的结果,直到输入“q”。它将统计每个结果的数量,并最终打印结果。
❺ 在线等!求一个python 五子棋源代码,最好是有“人人对弈”和“人机对弈”功能的,不胜感谢!
试试这个吧。
import numpy as np
import pygame
import sys
import traceback
import
from pygame.locals import *
pygame.init()
pygame.mixer.init()
#颜色
background=(201,202,187)
checkerboard=(80,80,80)
button=(52,53,44)
#音乐
play_chess_sound = pygame.mixer.Sound("music/play_chess.wav")
play_chess_sound.set_volume(0.2)
button_sound = pygame.mixer.Sound("music/button.wav")
button_sound.set_volume(0.2)
victor_sound = pygame.mixer.Sound("music/victory.wav")
victor_sound.set_volume(0.2)
#绘制棋盘
def Draw_a_chessboard(screen):
#填充背景色
screen.fill(background)
Background=pygame.image.load("background.jpg").convert_alpha()
screen.blit(Background,(0,0))
#画棋盘
for i in range(21):
pygame.draw.line(screen, checkerboard, (40*i+3, 3), (40*i+3, 803))
pygame.draw.line(screen, checkerboard, (3, 40*i+3), (803, 40*i+3))
#画边线
pygame.draw.line(screen, checkerboard, (3, 3), (803, 3),5)
pygame.draw.line(screen, checkerboard, (3, 3), (3, 803),5)
pygame.draw.line(screen, checkerboard, (803, 3), (803, 803),5)
pygame.draw.line(screen, checkerboard, (3, 803), (803, 803),5)
#画定位点
pygame.draw.circle(screen, checkerboard, (163, 163), 6)
pygame.draw.circle(screen, checkerboard, (163, 643), 6)
pygame.draw.circle(screen, checkerboard, (643, 163), 6)
pygame.draw.circle(screen, checkerboard, (643, 643), 6)
pygame.draw.circle(screen, checkerboard, (403, 403), 6)
#画‘悔棋’‘重新开始’跟‘退出’按钮
pygame.draw.rect(screen,button,[900,350,120,100],5)
pygame.draw.rect(screen,button,[900,500,200,100],5)
pygame.draw.rect(screen,button,[900,650,200,100],5)
s_font=pygame.font.Font('font.ttf',40)
text1=s_font.render("悔棋",True,button)
text2=s_font.render("重新开始",True,button)
text3=s_font.render("退出游戏",True,button)
screen.blit(text1,(920,370))
screen.blit(text2,(920,520))
screen.blit(text3,(920,670))
#绘制棋子(横坐标,纵坐标,屏幕,棋子颜色(1代表黑,2代表白))
def Draw_a_chessman(x,y,screen,color):
if color==1:
Black_chess=pygame.image.load("Black_chess.png").convert_alpha()
screen.blit(Black_chess,(40*x+3-15,40*y+3-15))
if color==2:
White_chess=pygame.image.load("White_chess.png").convert_alpha()
screen.blit(White_chess,(40*x+3-15,40*y+3-15))
#绘制带有棋子的棋盘
def Draw_a_chessboard_with_chessman(map,screen):
screen.fill(background)
Draw_a_chessboard(screen)
for i in range(24):
for j in range(24):
Draw_a_chessman(i+1,j+1,screen,map[i][j])
#定义存储棋盘的列表,
#列表为24列24行是因为判断是否胜利函数里的索引会超出19
#列表大一点不会对游戏有什么影响
map=[]
for i in range(24):
map.append([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
#清零map列表
def clear():
global map
for i in range(24):
for j in range(24):
map[i][j]=0
#判断是否胜利
def win(i, j):
k = map[i][j]
p=[]
for a in range(20):
p.append(0)
for i3 in range(i-4,i+5):
for j3 in range(j-4,j+5):
if (map[i3][j3] == k and i3 - i == j3 - j and i3 <= i and j3 <= j):
p[0]+=1
if (map[i3][j3] == k and j3 == j and i3 <= i and j3 <= j):
p[1]+=1
if (map[i3][j3] == k and i3 == i and i3 <= i and j3 <= j):
p[2]+=1
if (map[i3][j3] == k and i3 - i == j3 - j and i3 >= i and j3 >= j):
p[3]+=1
if (map[i3][j3] == k and j3 == j and i3 >= i and j3 >= j):
p[4]+=1
if (map[i3][j3] == k and i3 == i and i3 >= i and j3 >= j):
p[5]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i and j3 >= j):
p[6]+=1
if (map[i3][j3] == k and i3 - i == j - j3 and i3 >= i and j3 <= j):
p[7]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[8]+=1
if (map[i3][j3] == k and j == j3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[9]+=1
if (map[i3][j3] == k and i == i3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[10]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[11]+=1
if (map[i3][j3] == k and j == j3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[12]+=1
if (map[i3][j3] == k and i == i3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[13]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i + 1 and i3 >= i - 3 and j3 >= j - 1 and j3 <= j + 3):
p[14]+=1
if (map[i3][j3] == k and i3 - i == j - j3 and i3 >= i - 1 and i3 <= i + 3 and j3 <= j + 1 and j3 >= j - 3):
p[15]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[16]+=1
if (map[i3][j3] == k and j == j3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[17]+=1
if (map[i3][j3] == k and i == i3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[18]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[19]+=1
for b in range(20):
if p[b]==5:
return True
return False
#绘制提示器(类容,屏幕,字大小)
def text(s,screen,x):
#先把上一次的类容用一个矩形覆盖
pygame.draw.rect(screen,background,[850,100,1200,100])
#定义字体跟大小
s_font=pygame.font.Font('font.ttf',x)
#定义类容,是否抗锯齿,颜色
s_text=s_font.render(s,True,button)
#将字放在窗口指定位置
screen.blit(s_text,(880,100))
pygame.display.flip()
#用于控制顺序
t=True
#用于结束游戏后阻止落子
running=True
#主函数
def main():
#将 t,map,running设置为可改的
global t,map,running,maps,r,h
#将map置零
clear()
#定义储存所有棋盘状态的列表(用于悔棋)
map2=.deep(map)
maps=[map2]
#定义窗口
screen = pygame.display.set_mode([1200,806])
#定义窗口名字
pygame.display.set_caption("五子棋")
#在窗口画出棋盘,提示器以及按钮
Draw_a_chessboard(screen)
pygame.display.flip()
clock=pygame.time.Clock()
while True:
#只有running为真才能落子,主要用于游戏结束后防止再次落子
if running:
if t:
color=1
text('黑棋落子',screen,54)
else:
color=2
text('白棋落子',screen,54)
for event in pygame.event.get():
#点击x则关闭窗口
if event.type ==pygame.QUIT:
pygame.quit()
sys.exit()
#点击窗口里面类容则完成相应指令
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
x,y=event.pos[0],event.pos[1]
for i in range(19):
for j in range(19):
#点击棋盘相应位置
if i*40+3+20<x<i*40+3+60 and j*40+3+20<y<j*40+3+60 and not map[i][j] and running:
#在棋盘相应位置落相应颜色棋子
Draw_a_chessman(i+1,j+1,screen,color)
#播放音效
play_chess_sound.play(0)
#在map里面记录落子位置
map[i][j]=color
#将map存入maps
map3=.deep(map)
maps.append(map3)
#判断落子后是否有五子一线
if win(i,j):
if t:
text('黑棋胜利,请重新游戏',screen,30)
else:
text('白棋胜利,请重新游戏',screen,30)
#播放音效
victor_sound.play(0)
#阻止再往棋盘落子
running=False
pygame.display.flip()
t=not t
#如果点击‘重新开始’
if 900<x<1100 and 500<y<600:
#取消阻止
running=True
#播放音效
button_sound.play(0)
#重新开始
main()
#点击‘退出游戏’,退出游戏
elif 900<x<1100 and 650<y<750:
#播放音效
button_sound.play(0)
pygame.quit()
sys.exit()
#点击‘悔棋’
elif 900<x<1020 and 350<y<450 and len(maps)!=1:
#播放音效
button_sound.play(0)
#删除maps里最后一个元素
del maps[len(maps)-1]
#再将最后一个元素给map
map=.deep(maps[len(maps)-1])
#切换顺序
t=not t
#将map显示出来
Draw_a_chessboard_with_chessman(map,screen)
#悔棋完成,阻止再次悔棋
x,y=0,0
clock.tick(60)
if __name__ == "__main__":
try:
main()
except SystemExit:
pass
except:
traceback.print_exc()
pygame.quit()
input()
❻ 求一个编写的五子棋小游戏python的代码,求借鉴啊!!急急急。。。
#五子棋importappuifw,e32,key_codes
fromgraphicsimport*defcn(x):returnx.decode('utf-8')
defquit():_quit=1
globalrunning
running=1
defredraw(rect):canvas.blit(img)defdefault():
globalcon,color,font
con={"l":15,"x":15,"y":33,"r":13,"n":15}
color={"bg":0x7777bb,"fg":0x333333,"p1":0x000000,"p2":0xffffff,"w":0xff0000}
font=u"SansMT936_S60"definitial():
globalimg,canvas,con,color,cur_x,cur_y,turn,pos1,pos2,pos
appuifw.app.screen='full'
appuifw.app.body=canvas=appuifw.Canvas()
img=Image.new((240,320))
img.clear(color["bg"])
cur_x=7
cur_y=7
turn=1
pos1=[]
pos2=[]
pos=[]
foriinrange(con["n"]*con["n"]):
pos.append(0)defpaint_back():
globalimg,color,font
#img.text((90,25),cn('欢乐五子棋'),color["fg"],font)
foriinrange(con["x"],con["x"]+con["l"]*con["n"]-1,con["l"]):
img.line((i,con["y"],i,con["y"]+con["l"]*(con["n"]-1)),color["fg"])
foriinrange(con["y"],con["y"]+con["l"]*con["n"]-1,con["l"]):
img.line((con["x"],i,con["x"]+con["l"]*(con["n"]-1),i),color["fg"])
img.text((40,270),cn('玩家1'),color["p1"],font)
img.text((160,270),cn('玩家2'),color["p2"],font)
img.point((90,263),color["p1"],width=con["r"],fill=color["p1"])
img.point((144,263),color["p2"],width=con["r"],fill=color["p2"])
defpaint_cur(x,y,sh):
globalimg,con,color,pos1,pos2,running
ifrunning<>1:return
ax=con["x"]+con["l"]*x
ay=con["y"]+con["l"]*y
b=con["l"]/2
ifsh<>0:
c=color["p"+str(sh)]
ifrp((x,y))<>0:
c=color["w"]
ifsh==0:
c=color["bg"]
img.line((ax-b,ay-2,ax-b,ay-b,ax-2,ay-b),c)
img.line((ax-b,ay+2,ax-b,ay+b,ax-2,ay+b),c)
img.line((ax+b,ay-2,ax+b,ay-b,ax+2,ay-b),c)
img.line((ax+b,ay+2,ax+b,ay+b,ax+2,ay+b),c)
redraw(())defpaint_q(x,y,z):
globalimg,con,color
ax=con["x"]+con["l"]*x
ay=con["y"]+con["l"]*y
b=con["l"]/2
ifz==0:
c=color["bg"]
else:
c=color["p"+str(z)]
img.point((ax,ay),c,width=con["r"],fill=c)
redraw(())
ifz==0:
img.line((ax-b,ay,ax+b,ay),c)
img.line((ax,ay-b,ax,ay+b),c)
defk_up():
globalcur_x,cur_y,con,turn
paint_cur(cur_x,cur_y,0)
cur_y=cur_y-1
ifcur_y==-1:
cur_y=con["n"]-1
paint_cur(cur_x,cur_y,turn)defk_down():
globalcur_x,cur_y,con,turn
paint_cur(cur_x,cur_y,0)
cur_y=cur_y+1
ifcur_y==con["n"]:
cur_y=0
paint_cur(cur_x,cur_y,turn)defk_left():
globalcur_x,cur_y,con,turn
paint_cur(cur_x,cur_y,0)
cur_x=cur_x-1
ifcur_x==-1:
cur_x=con["n"]-1
paint_cur(cur_x,cur_y,turn)defk_right():
globalcur_x,cur_y,con,turn
paint_cur(cur_x,cur_y,0)
cur_x=cur_x+1
ifcur_x==con["n"]:
cur_x=0
paint_cur(cur_x,cur_y,turn)defrp(x):
globalcon,pos
if(x[0]<0orx[0]>=con["n"]orx[1]<0orx[1]>=con["n"]):return0
#printx,pos[x[0]*con["n"]+x[1]]
returnpos[x[0]*con["n"]+x[1]]defwp(x,y):
globalcon,pos
pos[x[0]*con["n"]+x[1]]=y
defwin():
foriinpos1:
k=0
forjinrange(0,6):
ifrp((i[0]+j,i[1]))==1:
k=k+1
else:
break
ifk>=5:
return1
k=0
forjinrange(0,6):
ifrp((i[0],i[1]+j))==1:
k=k+1
else:
break
ifk>=5:
return1
k=0
forjinrange(0,6):
ifrp((i[0]+j,i[1]+j))==1:
k=k+1
else:
break
ifk>=5:
return1
k=0
forjinrange(0,6):
ifrp((i[0]+j,i[1]-j))==1:
k=k+1
else:
break
ifk>=5:
return1foriinpos2:
k=0
forjinrange(0,6):
ifrp((i[0]+j,i[1]))==2:
k=k+1
else:
break
ifk>=5:
return2
k=0
forjinrange(0,6):
ifrp((i[0],i[1]+j))==2:
k=k+1
else:
break
ifk>=5:
return2
k=0
forjinrange(0,6):
ifrp((i[0]+j,i[1]+j))==2:
k=k+1
else:
break
ifk>=5:
return2
k=0
forjinrange(0,6):
ifrp((i[0]+j,i[1]-j))==2:
k=k+1
else:
break
ifk>=5:
return2
return0
defk_enter():
globalcur_x,cur_y,turn,pos1,pos2,con,color,font,running
ifrunning<>1:return
ifrp((cur_x,cur_y))==0:
ifturn==1:
pos1.append((cur_x,cur_y))
img.rectangle((35,255,100,272),color["bg"])
img.rectangle((135,255,200,272),color["p2"])
ifturn==2:
pos2.append((cur_x,cur_y))
img.rectangle((35,255,100,272),color["p1"])
img.rectangle((135,255,200,272),color["bg"])
paint_q(cur_x,cur_y,turn)
wp((cur_x,cur_y),turn)
ifwin()<>0:
#img.text((80,300),cn('玩家')+str(turn)+cn("获胜!"),color["fg"],font)
img.rectangle((35,255,100,272),color["bg"])
img.rectangle((135,255,200,272),color["bg"])
paint_cur(cur_x,cur_y,0)
running=2
turn=3-turn
paint_cur(cur_x,cur_y,turn)defbindkey():
canvas.bind(key_codes.EKeyUpArrow,k_up)
canvas.bind(key_codes.EKeyDownArrow,k_down)
canvas.bind(key_codes.EKeyLeftArrow,k_left)
canvas.bind(key_codes.EKeyRightArrow,k_right)
canvas.bind(key_codes.EKeySelect,k_enter)default()
initial()
paint_back()
paint_cur(cur_x,cur_y,1)
img.rectangle((35,255,100,272),color["p1"])
bindkey()redraw(())
appuifw.app.exit_key_handler=quit()
_quit=0
while(1-_quit):
e32.ao_sleep(0.2)
redraw(())
❼ 求解用python 编写五子棋怎样编写判断输赢的函数,
你都做到这个程度了,当然就是高手了。 把棋子位置放在一个数据里。然后做一个路径搜索算法。只搜索8个方向,如果某个方向有5个子连在一起就赢了。 这是个笨方法,还有很多优化的地方,比如上一次搜索后,建立一个路径数组。下一次,只需要检验求解用python 编写五子棋怎样编写判断输赢的函数,