本課程設計是本專業的一門重要實踐性教學環節.在學習了專業基礎課和《Python程序設計》課程的基礎上,本課程設計旨在加深對PythonThe understanding of the program design,對PythonLanguage and language ecology has a further grasp and application of,學會運用PythonThe standard library and external related library to basic ability to solve practical problems,培養和提高學生分析問題、解決問題的能力,尤其是提高學生使用Python為開發語言來進行問題描述、The ability to exchange and thinking,為畢業設計和以後的工程實踐打下良好的基礎.
After a group discussion analysis,我們最終選擇了“五子棋”As this class set the theme.
Gobang originated in China ancient times one of the traditional black white kind of.Mainly in Chinese and Chinese culture as well as Europe and the United States in some areas,Chess is the oldest in the world.Ancient renju boards and go board is common,直到1931年,Only the so-called special renju board,For 15 road(15×15)棋盤.Now people increasing pressure,Need to distribute work to achieve higher work efficiency,Of the job of entertainment for each and every one of essential.Gobang the entertainment easier,老少皆宜,而且趣味橫生,引人入勝;Can not only enhance thinking ability,提高智力,而且富含哲理,有助於修身養性.
The main task of the curriculum design is based onPythonFor the development of language to complete a100~300Line about the size of the application project development.
Curriculum design is the basic requirement of:At the different stages of the course design of strict、To complete the relevant specification document,For example, in early finish the design purpose、設計要求、總體設計,In the later to complete the detailed design、調試與測試、Design summary, etc.Required to complete the topic purpose main function,The program runs robust、正確,The code should have detailed comments,可讀性好;Written document structure reasonable、內容完整、敘述清晰.Higher requirements are:有創意、系統界面美觀.
Because the course design project has a certain comprehensive,Encourage students with different expertise and ability to team up with each other.The project team himself recommends a leader,實行“The group leader responsibility system”.Project leader group crew on the topic、任務分配、方案確定、方案設計、System debugging test,Team collaboration.Team members to carry out the project to discuss,互相支持,Form a collaboration consciousness.
有圖形界面,Can use the mouse to operate.
Ability of basic operation gobang game,The players take turns to move later.
To properly determine the result of the game.
To implement additional features such as back and throw in the towel.
Application functions of display and straightforward.
Output the necessary message for players to play better.
基於Python的標准GUI庫tkinter快速創建GUI應用程序.
To run the program prompt to start the game.人人對戰,Two people take turns to move later.Interface display message when point which side turn move later.There are five before“—”或“|”或“/”或“\”Line up the players to win.If the board piece is full,Players are completed to abital connected is judged to be a draw.When win black or white win or a draw in time to make decision,並彈出提示框,Inform current player game over.
組員:Jia-li wu yu Ye Yu Liu Luyao
任務分配:
:Responsible for the players operating module design,Including move later、Back and throw in the towel.
:Visual design is responsible for the game,Including the game interface design and the board design.
Board design part includes begin the game to run the program and to start the initialization board.
:Responsible for the decision results that players win or a draw game decision
Start the program to run the game,彈出提示框,Prompt players began to,Black to move later.Players click on the board without pieces for move later.或點擊“開局”、“悔棋”、“認輸”Button to start or back or throw in the towel.當點擊“開局/重新開局”按鈕時,In the empty board pieces,Show about the same as the initiator of the game interface.界面中間“黑方”與“落子”2 place text message in game,Said current turn black pieces placed.Turn white when they move later“黑方”將自動更改為“白方”,“白方”The word displayed in white.如圖4-1所示.
如圖4-2所示,If there is one player“—”或“|”或“/”或“\”五子相連,The players to win the agency game.In an effort to shown in case——黑方“/”Five is linked together, for example,That player to win the result.Through the yellow lines will be black connected together as a line of five pieces,The interface between message to“黑方獲勝”,“獲勝”The word displayed in red.And a pop-up message prompt box,Prompt players game over black finish abital connected,取得勝利.If you click the back button at this time,You will be prompted to players at this point cannot be back.如圖4-3所示;Click button to throw in the towel,You will be prompted to click on start to start game,如圖4-4所示.
When both players didn't finish the five wire,And all move on the chessboard, has placed pieces that have placed pieces when,Judged to be a draw.
Show more convenient,Change the board to5*5大小.如圖4-5所示,Intermediate hint text changes for the green words“平局??!”,At the same time, a pop-up message prompt box,Tip current player game over,The two sides reached a draw.此時游戲結束,Players not to take back or throw in the towel,If the player click button back or throw in the towel,To the same effect with one player win.The game interface do not change,彈出消息提示框,The message prompt dialog box in figure4-3、圖4-4In the message box is the same,不再重復展示.
In the process of game,If the player first click button to throw in the towel.Board do not change,Among the game interface text“落子”變為“認輸”如圖4-6所示.此時游戲結束,Players not to take back or throw in the towel,If the player click button back or throw in the towel,To the same effect with one player win.The game interface do not change,彈出消息提示框,The message prompt dialog box in figure4-3、圖4-4In the message box is the same,不再重復展示.
游戲過程中,If that player for the first time in a round back,To collect the player just placed to pieces on a board,And will be in the middle of the message“We have a move later”Back to the players.In the case of black back,Back before and after back part game interface, respectively, as shown in figure4-7、圖4-8所示.If the player in a round back operations were carried out in,Click the back button again,Do not change the game interface and board,But the springback prompt box can't back at this time,The message prompt box and prompt information and win when click the back button,即圖4-4In the prompt dialog box the same.
Form the interface intuitive and clear,Game with appropriate hint information can help in the process of players to play the game better.At the same time, the form of color form the size set right.Players won't because the game interface color impact or board、Text messages, such as greater than the little get tired.Program can properly determine the result of the game,Back and give up the two additional features also can realize.Course design of set of the original function and the request can realize.在此基礎上,When connected to abital players finish with a yellow line,For players to have a better experience.Plus a round in allowing the player to the back only once,增加挑戰,讓游戲更加有趣.
Group exceeded original function and the request want to achieve,So we give our evaluation for good!
Of course this small program also many shortcomings.For example, no marked the last place the pieces,Doesn't mark after the players back in front of the back pieces etc.We also should study hard back,做的更好.
Responsible for the part can be roughly divided into three modules.首先,Judge the game the outcome of the four,即橫、豎、Diagonal direction abital line;其次,Determine whether the board can continue playing chess,Whether a draw;最後,判斷玩家輸贏,並彈出提示框.
from tkinter import*
from tkinter import messagebox
Tkinter庫:
Tkinter是Python 的標准 GUI 庫.Python 使用 Tkinter 可以快速的創建 GUI 應用程序.由於 Tkinter 是內置到 python 的安裝包中、只要安裝好 Python 之後就能 import Tkinter 庫、而且 IDLE 也是用 Tkinter 編寫而成、Simple graphical interface can beTkinter 庫完成.
Messagebox 函數分析:
函數定義:<整型> MessageBox(<字符串> Text, <字符串> Title, <整型> nType);
函數功能: 彈出一個消息框.
參數:
Text <字符串>,消息框的正文;
Title <字符串>,消息框的標題;
nType <整型>,消息框的類型.
返回值:<整型>,用戶在消息框上點擊關閉時的選擇的按鈕.
說明:
nTypeThe corresponding dialog box shown in the following table:
0: 確定
1: 確定,取消
2: 終止,重試,忽略
3: 是,否,取消
4: 是,否
5: 重試,取消
6: 取消,再試一次,繼續
Returns the value of value corresponding to the following:
1: 確定
2: 取消
3: 終止
4: 重試
5: 忽略
6: 是
7: 否
:再試一次
自定義panduan()Function and usefor語句循環,To determine whether a piece for cross、豎、Inclined to abital attachment,列表QP[a][b]Must meet 0 <= a,b <= 17,i、j必須嚴格控制.If there are five cords to happen,Add a yellow tag line on the pieces through five,Are more likely to see.
代碼如下:
def panduan():
iswin = 0 #Tag is one complete abital connected,0代表否
for i in range (num-4):
for j in range (num): #Determine whether any one"—"五子相連
If QP[i][j]==QP[i+1][j]==QP[i+2][j]==QP[i+3][j]==QP[i+4][j] != -1:
iswin=1 canvas.create_line(mesh*(i+1)-Qr/2,mesh*(j+1),mesh*(i+5)+Qr/2,mesh*(j+1),fill="yellow")
win()
for i in range (num):
for j in range (num-4): #Determine whether any one"|"五子相連
if QP[i][j]==QP[i][j+1]==QP[i][j+2]==QP[i][j+3]==QP[i][j+4] != -1:
iswin=1 canvas.create_line(mesh*(i+1),mesh*(j+1)-Qr/2,mesh*(i+1),mesh*(j+5)+Qr/2,fill="yellow")
win()
for i in range (num-4):
for j in range (num-4): #Determine whether any one"\"五子相連 if QP[i][j]==QP[i+1][j+1]==QP[i+2][j+2]==QP[i+3][j+3]==QP[i+4][j+4] != -1:
iswin = 1
canvas.create_line(mesh*(i+1)-Qr/2,mesh*(j+1)-Qr/2,mesh*(i+5)+Qr/2,mesh*(j+5)+Qr/2,fill="yellow")
win()
for i in range (num-4):
for j in range (4,num): #Determine whether any one"/"五子相連
if QP[i][j]==QP[i+1][j-1]==QP[i+2][j-2]==QP[i+3][j-3]==QP[i+4][j-4] != -1:
iswin=1 canvas.create_line(mesh*(i+1)-Qr/2,mesh*(j+1)+Qr/2,mesh*(i+5)+Qr/2,mesh*(j-3)-Qr/2,fill="yellow")
win()
Function and statement analysis:
for循環:
作用:for循環語句是pythonIn a loop control statements,Any order of elements within a sequence object can traverse the,比如字符串、列表、Tuples can be iterative to like.
一般格式:第一行是要先定義一個賦值目標(迭代變量),和要遍歷(迭代)的對像;首行後面是要執行的語句塊.
for 目標 in 對像:
print賦值目標
循環過程: i相當於目標,range(num)Is traversal of like.當運行for循環語句時,每一次迭代時,iFrom traversal of likerange(num)Receiving a new value in the output.結束循環後,目標iWill retain the last value
Canvas組件:
Python Tkinter 畫布(Canvas)組件和 html5 中的畫布一樣,都是用來繪圖的.可以將圖形、文本、小部件或框架放置在畫布上.canvas.create_line()The main implementation is to draw a straight line,後面()
Parameter is given in the line of two coordinates,兩點確定一條直線.
Canvas 組件支持以下標准選項:
arc 創建一個扇形
coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=0, extent=150, fill="blue")
image 創建圖像
filename = PhotoImage(file = "sunshine.gif")
image = canvas.create_image(50, 50, anchor=NE, image=filename)
line 創建線條
line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, options)
oval 創建一個圓
oval = canvas.create_oval(x0, y0, x1, y1, options)
polygon 創建一個至少有三個頂點的多邊形
oval = canvas.create_polygon(x0, y0, x1, y1,…xn, yn, options)
分析:定義一個列表boringRecord each chess lattice state,Whether includes chess pieces,If a piece is for black or white.ForWhile loop traverse board(列表QP[a][b]Must meet 0 <= a,b <= 17,i、j必須嚴格控制),When the board does not exist in no unfinished piece of chess, and both parties abital attachment,Judged to be a draw and popup tooltip.
代碼如下:
boring=[] #遍歷棋盤,Record each chess lattice state
for i in range(num):
for j in range(num):
boring.append(QP[i][j])
if -1 not in boring and iswin != 1:
print(messagebox.askokcancel('游戲結束','旗鼓相當!平局!'))
append()函數
描述:append() 方法用於在列表末尾添加新的對象.
用法: list.append(obj) objTo add to the list at the end of the object
返回值:該方法無返回值,但是會修改原來的列表.
本例應用:
boring.append(QP[i][j])
Role is to traverse the latest state of chess, added to theboring列表最後.
輸出分析
Output prompt box,顯示游戲結束,旗鼓相當!平局!
print(messagebox.askokcancel('游戲結束','旗鼓相當!平局!')
函數分析:
messagebox.askokcancel()是tkinter庫中的一個組件,Used to set a message box.
askokcancel()設置對話框的主要文本內容,可以用’\n’來實現換行
返回值為Boolean類型.
分析:Sunspots or an albino win,彈出提示框,顯示“游戲結束,Black abital connected!獲勝!”或“游戲結束,White's abital connected!獲勝!”.
變量設置:global設置全局變量stop,hq.其中tag為之前定義的,tagMarkers of chess,0代表黑方,1代表白方 ;stopMark the game state,0代表游戲進行中,1代表游戲結束;hqTags can back,0代表不可以,1代表可以.
代碼如下:
def win():
global stop,hq
a.config(text=key[(tag+1)%2],fg=color[(tag+1)%2])
b.config(text = "獲勝",fg='red')
stop,hq = 1,0 #Decided after the end of the game,Do not back
if tag == 0:
r=messagebox.askokcancel('游戲結束','White's abital connected!獲勝!')
else:
r=messagebox.askokcancel('游戲結束','Black abital connected!獲勝!')
print(r)
前要:
a = Label(tk,text=key[tag],fg=color[tag],bg = "pink",font = ("楷體", "18", "bold"))
b = Label(tk,text= "落子" ,fg=color[tag],bg = "pink",font = ("楷體", "18", "bold"))
函數分析:
a.config(text=key[(tag+1)%2],fg=color[(tag+1)%2])
b.config(text = "獲勝",fg='red')
通過tagDetermine the color of the pieces,A pop-up message box that wins the font to red.
把print()替換為logging,logging不會拋出錯誤,而且可以輸出到文件.
它允許你指定記錄信息的級別,有debug,info,warning,error等幾個級別,當我們指定level=INFO時,logging.debug就不起作用了.同理,level=WARNING後,debug和info就不起作用了.這樣一來,You can rest assured to output different levels of information,也不用刪除,最後統一控制輸出哪個級別的信息.logging的另一個好處是通過簡單的配置,一條語句可以同時輸出到不同的地方.
使用pdb進行調試,pdb是python自帶的一個包,為python程序提供了一種交互的源代碼調試功能,主要特性包括設置斷點、單步調試、進入函數調試、查看當前代碼、查看棧片段、動態改變變量的值等.
pdb常用命令如下:
圖6-1 pdb常用命令表
步驟如下:
[1]讓程序以單步方式運行,可以隨時查看運行狀態.
[2]以參數-mpdb啟動後,pdb定位到下一步要執行的代碼->s=‘0’.輸入命令l來查看代碼
[3]輸入命令n可以單步執行代碼
[4]任何時候都可以輸入命令p變量名來查看變量
[5]輸入命令q結束調試,退出程序
Sunspots right abital attachment,黑方獲勝
Black abital vertical wire,黑方獲勝
Spots left oblique abital attachment,黑方獲勝
An albino abital transverse connection,白方獲勝