赞
踩
文章下面有井字棋全部代码和如何与上一篇登入界面进行连接
我们先设置两个函数,一个函数里面储存九宫格,另一个函数储存主程序,之后我们调用主程序进行实现。
import tkinter as tk
def main():
root = tk.Tk()
root.title("九宫格")
root.geometry("500x600")
if __name__ == "__main__":
main()
canvas:可以在窗口中创建各种图形。
create:create 是 tkinter 中 Canvas 组件的方法之一,用于在画布上创建不同类型的图形。通过 create 方法,可以创建并添加各种图形对象到画布上,如矩形、椭圆、文本、线条等。
def draw_grid(canvas):
# 画外边框线
canvas.create_line(2, 2, 300, 2, width=2) # 上
canvas.create_line(2, 2, 2, 300, width=2) # 左
canvas.create_line(2, 300, 300, 300, width=2) # 下
canvas.create_line(300, 2, 300, 300, width=2) # 右
# 画横线
canvas.create_line(100, 0, 100, 300)
canvas.create_line(200, 0, 200, 300)
# 画竖线
canvas.create_line(0, 100, 300, 100)
canvas.create_line(0, 200, 300, 200)
global canvas
canvas = tk.Canvas(root, width=350, height=350,)
canvas.pack()
draw_grid(canvas)
root.mainloop()
我们使用for循环在格子里面输入数字。
#初始化变量 num 为1,用于存储将要显示的数字。
num = 1
# 外层循环,变量 i 从0到2循环,共执行3次。
for i in range(3):
#内层循环,变量 j 从0到2循环,共执行3次。
for j in range(3):
#计算每个格子中心点的 y 坐标。当 i 为0时,y 为50;当 i 为1时,y 为150;当 i 为2时,y 为250。
y = i * 100 + 50
#计算每个格子中心点的 x 坐标。当 j 为0时,x 为50;当 j 为1时,x 为150;当 j 为2时,x 为250。
x = j * 100 + 50
#在坐标 (x, y) 处创建一个文本对象,显示的内容为 num 的字符串形式,即当前数字。设置文本的字体为 Arial,大小为24。
canvas.create_text(x, y, text=str(num), font=("Arial", 24))
#每次内循环结束后,将 num 的值加1,以便显示下一个数字。
num += 1
运行结果如下:
lb1 = tk.Label(root, text='请要输入落子的位置(1~9):')
lb1.place(x=150, y=350)
global e1
e1 = tk.Entry(root, bd=5, width=20)
e1.place(x=150, y=380)
button1 = tk.Button(root, text="按下落子", width=10, height=2, fg='black')
button1.place(x=180, y=420)
button2 = tk.Button(root, text="重新开始", width=10, height=2, fg='black')
button2.place(x=180, y=480)
定义一个函数,使得在输入框输入对应的九宫格数字,点击按下落子按钮,实现在格子里面画叉,如果重复一个数字输入,则会弹出警告框。
我们先在最上方导入一个包:from tkinter import messagebox
然后在主程序中写着:board = [’ '] * 9,这个代码表示创建了一个包含9个元素的列表 board,并将每个元素初始化为一个空格 ’ '。
再在主程序中定义初始步数为0:step = 0
isdigit() 是 Python 字符串对象的一个方法,用于判断字符串是否只包含数字字符。具体来说,isdigit() 方法会遍历字符串中的每个字符,如果所有字符都是数字字符(0-9),则返回 True;否则返回 False。
def on_click(): global board global step position = e1.get() if position.isdigit() and 1 <= int(position) <= 9: number = int(position) index = number - 1 if board[index] == ' ': board[index] = 'x' x = ((int(position) - 1) % 3) * 100 + 50 y = ((int(position) - 1) // 3) * 100 + 50 canvas.create_line(x - 20, y - 20, x + 20, y + 20, fill='black', width=2) canvas.create_line(x + 20, y - 20, x - 20, y + 20, fill='black', width=2) else: messagebox.showerror("错误", "该位置已经落子,请选择其他位置")
设置一个函数,使得输入1~9以外的数字会弹出弹窗警告,如果输入其他也会弹出弹出警告。
def problem():
try:
input_value = int(e1.get())
if input_value < 1 or input_value > 9:
messagebox.showerror("错误", "请输入1到9之间的数字")
else:
print("输入正确")
except ValueError:
messagebox.showerror("错误", "请输入一个有效的数字")
on_click()
如果要想实现此功能,我们还需要把bullon1里面调用的函数改为problem
如下:
button1 = tk.Button(root, text="按下落子", width=10, height=2, fg='black', command=problem)
button1.place(x=180, y=420)
设置一个函数,里面设置一个二维数组,把所有赢的可能设置在里面,然后判断是否赢,超过5步则平局。
def iswins():
global gameover,step
wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
for w in wins:
if (board[w[0]]!=" " and board[w[0]]==board[w[1]]==board[w[2]]):
gameover = True
messagebox.showinfo(title="shuchu",message="我赢了")
return
if step>5:
gameover = True
messagebox.showinfo(title="shuchu",message="都没有赢了")
return
要想实现此代码,还需要在on_click函数的步数后面加上此函数,这样每下完一步都会进行判断。
定义一个函数,链接重新开始按钮,使点击主窗口的重新开始按钮,九宫格内所有叉消失,重新开始游戏。
我们要在主循环中设置gameover=False
def again():
global board, step, gameover
board = [' '] * 9
step = 0
gameover = False
#删除画布上的所有元素。
canvas.delete('all')
#再一次绘制九宫格棋盘
draw_grid(canvas)
定义一个函数,代表AI下棋,在里面随机生成0~8的整数,用于表示AI在棋盘上的位置,然后让AI落子时不落在已经落子的地方,然后画圈。
在写代码前,我们先要在最上方导入import random
还要在主循环中写如AI的步数foot=0
写完AI落子,我们还需要在on_click函数中添加AI落子,实现玩家与AI交替落子。
def ai_move():
global board, foot
index = random.randint(0, 8)
while board[index] != ' ':
index = random.randint(0, 8)
x = ((index) % 3) * 100 + 50
y = ((index) // 3) * 100 + 50
canvas.create_oval(x - 20, y - 20, x + 20, y + 20, fill='red')
board[index] = 'AI'
foot += 1
iswins()
到这里我们的代码基本就结束啦,但是还有最后一步,就是把登入界面和井字棋游戏界面进行链接起来。
登入界面在上一篇文章
首先确保我们的登入界面和井字棋界面在一个文件下,我们需要先在登入界面最上方添加一个包:import subprocess
再在usr_login函数里面加入:
window.destroy()
subprocess.Popen(["python", "demo3.py"])
上面的"demo3.py"
是我井字棋游戏的文件名
import random import tkinter as tk from tkinter import messagebox def draw_grid(canvas): # 画外边框线 canvas.create_line(2, 2, 300, 2, width=2) # 上 canvas.create_line(2, 2, 2, 300, width=2) # 左 canvas.create_line(2, 300, 300, 300, width=2) # 下 canvas.create_line(300, 2, 300, 300, width=2) # 右 # 画横线 canvas.create_line(100, 0, 100, 300) canvas.create_line(200, 0, 200, 300) # 画竖线 canvas.create_line(0, 100, 300, 100) canvas.create_line(0, 200, 300, 200) num = 1 for i in range(3): for j in range(3): y = i * 100 + 50 x = j * 100 + 50 canvas.create_text(x, y, text=str(num), font=("Arial", 24)) num += 1 def on_click(): global board global step position = e1.get() if position.isdigit() and 1 <= int(position) <= 9: number = int(position) index = number - 1 if board[index] == ' ': board[index] = 'x' x = ((int(position) - 1) % 3) * 100 + 50 y = ((int(position) - 1) // 3) * 100 + 50 canvas.create_line(x - 20, y - 20, x + 20, y + 20, fill='black', width=2) canvas.create_line(x + 20, y - 20, x - 20, y + 20, fill='black', width=2) step += 1 iswins() if not gameover: ai_move() else: messagebox.showerror("错误", "该位置已经落子,请选择其他位置") def ai_move(): global board, foot index = random.randint(0, 8) while board[index] != ' ': index = random.randint(0, 8) x = ((index) % 3) * 100 + 50 y = ((index) // 3) * 100 + 50 canvas.create_oval(x - 20, y - 20, x + 20, y + 20, fill='red') board[index] = 'AI' foot += 1 iswins() def problem(): try: input_value = int(e1.get()) if input_value < 1 or input_value > 9: messagebox.showerror("错误", "请输入1到9之间的数字") else: print("输入正确") except ValueError: messagebox.showerror("错误", "请输入一个有效的数字") on_click() def iswins(): global gameover,step wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]] for w in wins: if (board[w[0]]!=" " and board[w[0]]==board[w[1]]==board[w[2]]): gameover = True messagebox.showinfo(title="shuchu",message="赢家是"+board[w[0]]) return if step>5: gameover = True messagebox.showinfo(title="shuchu",message="都没有赢了") return def again(): global board, step, gameover board = [' '] * 9 step = 0 gameover = False canvas.delete('all') draw_grid(canvas) def main(): root = tk.Tk() root.title("九宫格") root.geometry("500x600") lb1 = tk.Label(root, text='请要输入落子的位置(1~9):') lb1.place(x=150, y=350) global e1 e1 = tk.Entry(root, bd=5, width=20) e1.place(x=150, y=380) button1 = tk.Button(root, text="按下落子", width=10, height=2, fg='black', command=problem) button1.place(x=180, y=420) button2 = tk.Button(root, text="重新开始", width=10, height=2, fg='black', command=again) button2.place(x=180, y=480) global canvas canvas = tk.Canvas(root, width=350, height=350,) canvas.pack() draw_grid(canvas) root.mainloop() if __name__ == "__main__": board = [' '] * 9 gameover = False step = 0 foot =0 main()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。