❶ 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 編寫五子棋怎樣編寫判斷輸贏的函數,