Python使用内置库tkinter
实现井字棋游戏
井字棋,也被称为井字游戏、三连棋,是一种非常流行的棋类游戏。它由一个 3 * 3 的方格棋盘组成,玩家轮流在空白的格子中下棋,目标是将自己的棋子连成一条直线,可以是水平、垂直或对角线,先达到这个目标的玩家获胜。
在 Python 中可以使用tkinter
来实现界面化的井字棋游戏。如下是代码示例:
from tkinter import Tk,Button,messagebox,NORMAL,DISABLED
current_player = "X"
game_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
game_over = False
def check_win(player):
# 检查行
for i in range(0, 9, 3):
if game_board[i] == game_board[i + 1] == game_board[i + 2] == player:
return True
# 检查列
for i in range(3):
if game_board[i] == game_board[i + 3] == game_board[i + 6] == player:
return True
# 检查对角线
if game_board[0] == game_board[4] == game_board[8] == player:
return True
if game_board[2] == game_board[4] == game_board[6] == player:
return True
return False
def check_draw():
for i in range(9):
if game_board[i] == " ":
return False
return True
def restart_game():
global current_player, game_board, game_over
current_player = "X"
game_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
game_over = False
for button in board_buttons:
button.config(text=" ", state=NORMAL)
def make_move(index):
global current_player, game_board, game_over
if game_board[index] == " " and not game_over:
game_board[index] = current_player
board_buttons[index].config(text=current_player, state=DISABLED)
if check_win(current_player):
messagebox.showinfo("结果", f"玩家 {current_player} 获胜!")
game_over = True
elif check_draw():
messagebox.showinfo("结果", "平局!")
game_over = True
else:
current_player = "O" if current_player == "X" else "X"
# 创建窗口
root = Tk()
root.title("井字棋")
root.resizable(False, False)
# 创建按钮
board_buttons = []
for i in range(9):
button = Button(root, width=10, height=5, font=("Arial", 20), command=lambda index=i: make_move(index))
button.grid(row=i // 3, column=i % 3)
board_buttons.append(button)
# 创建重新开始按钮
restart_button = Button(root, text="重新开始", font=("Arial", 16), command=restart_game)
restart_button.grid(row=3, column=0, columnspan=3)
# 运行窗口主循环
root.mainloop()
上述代码演示了使用tkinter实现井字棋游戏的功能,运行代码后,将会弹出一个窗口,你可以通过点击按钮来进行井字棋游戏。