目标:
想要写一个人人对弈的五子棋游戏,要是GUI界面的,能够判断输赢、提示游戏结束,能重新开局。
思路:
- 分析:我需要棋盘、棋子、输赢的显示区、落棋方的提示区以及一个重新开局按钮。使用Python库
tkinter
。 - 棋盘绘制:
- 窗口左半部分放置一块画布
canvas
用于棋盘绘制;右半部分放置四个标签label
,分别用来落棋方提示的图片放置、文字放置,结果显示和状态显示;此外右下角放置一个按钮button
用于重置。 - 画布上设置背景,绘制线条、点、坐标的字母和数字
- 将标签和按钮放到指定位置
- 窗口左半部分放置一块画布
实现:
1import tkinter as tk #补充:如果你用的是Python2,那么很可能库名是Tkinter
2
3"""窗口主体"""
4root = tk.Tk()
5
6root.title("Gobang")
7root.geometry("760x560")
8
9"""棋子提示"""
10side_canvas = tk.Canvas(root, width = 220, height = 50)
11side_canvas.grid(row = 0, column = 1)
12side_canvas.create_oval(110 - PIECE_SIZE, 25 - PIECE_SIZE,
13 110 + PIECE_SIZE, 25 + PIECE_SIZE,
14 fill = piece_color, tags = ("show_piece") )
15"""棋子提示标签"""
16var = tk.StringVar()
17var.set("执黑棋")
18person_label = tk.Label(root, textvariable = var, width = 12, anchor = tk.CENTER,
19 font = ("Arial", 20) )
20person_label.grid(row = 1, column = 1)
21
22"""输赢提示标签"""
23var1 = tk.StringVar()
24var1.set("")
25result_label = tk.Label(root, textvariable = var1, width = 12, height = 4,
26 anchor = tk.CENTER, fg = "red", font = ("Arial", 25) )
27result_label.grid(row = 2, column = 1, rowspan = 2)
28
29"""游戏结束提示标签"""
30var2 = tk.StringVar()
31var2.set("")
32game_label = tk.Label(root, textvariable = var2, width = 12, height = 4,
33 anchor = tk.CENTER, font = ("Arial", 18) )
34game_label.grid(row = 4, column = 1)
35
36"""重置按钮"""
37reset_button = tk.Button(root, text = "重新开始", font = 20,
38 width = 8, command = gameReset)
39reset_button.grid(row = 5, column = 1)
40
41"""棋盘绘制"""
42#背景
43canvas = tk.Canvas(root, bg = "saddlebrown", width = 540, height = 540)
44canvas.bind("<Button-1>", coorBack) #对鼠标进行事件绑定,方便获取点击位置的坐标,下篇会用到
45canvas.grid(row = 0, column = 0, rowspan = 6)
46#线条
47for i in range(15):
48 canvas.create_line(32, (35 * i + 38), 522, (35 * i + 38))
49 canvas.create_line((35 * i + 32), 38, (35 * i + 32), 528)
50#点
51point_x = [3, 3, 11, 11, 7]
52point_y = [3, 11, 3, 11, 7]
53for i in range(5):
54 canvas.create_oval(35 * point_x[i] + 28, 35 * point_y[i] + 33,
55 35 * point_x[i] + 36, 35 * point_y[i] + 41, fill = "black")
56#数字坐标
57for i in range(15):
58 label = tk.Label(canvas, text = str(i + 1), fg = "black", bg = "saddlebrown",
59 width = 2, anchor = tk.E)
60 label.place(x = 2, y = 35 * i + 28)
61#字母坐标
62count = 0
63for i in range(65, 81):
64 label = tk.Label(canvas, text = chr(i), fg = "black", bg = "saddlebrown")
65 label.place(x = 35 * count + 25, y = 2)
66 count += 1
67
68"""窗口循环"""
69root.mainloop()
效果图:
下篇将分享内部逻辑的写法。(如何落子以及判断输赢)
此为旧文,图片水印为我的CSDN账号,无妨