用Python编写的简单双人对战五子棋游戏

本文详细介绍了如何使用Python的Tkinter库创建一个五子棋游戏的图形用户界面,包括GobangGame类的设计,make_move和check_winner函数的功能,以及如何在Spyder环境下进行开发。
摘要由CSDN通过智能技术生成

本文是使用python创建的一个基于tkinter库的GUI界面,用于实现五子棋游戏。编辑器使用的是spyder,该工具。既方便做数据分析,又可以做小工具开发,   

首先,导入tkinter库:import tkinter as tk,这里使用tkinter库来创建GUI界面。

然后创建GobangGame类:这个类包含了五子棋游戏的逻辑和界面显示。其中,make_move函数是在玩家点击棋盘上的按钮时调用的函数,用于处理玩家的落子操作。具体来说,当玩家点击棋盘上的某个按钮时,make_move函数会被调用,并传入按钮所在的行和列的索引。然后,该函数会检查对应的棋盘位置是否为空,如果为空,则将该位置标记为当前玩家的标记('X'或'O'),并禁用对应的按钮,表示该位置已经落子。接着,函数会检查当前玩家是否获胜,如果有则显示获胜信息,并禁用所有按钮。否则,切换到另一个玩家,准备让另一个玩家继续落子。

class GobangGame:
    def __init__(self, root):
        self.root = root
        self.root.title("五子棋游戏")

        self.board = [[' ' for _ in range(15)] for _ in range(15)]
        self.current_player = 'X'

        self.buttons = [[tk.Button(root, text=' ', width=2, height=1, command=lambda i=i, j=j: self.make_move(i, j)) for j in range(15)] for i in range(15)]
        for i in range(15):
            for j in range(15):
                self.buttons[i][j].grid(row=i, column=j)

        self.status_label = tk.Label(root, text=f"当前玩家: {self.current_player}")
        self.status_label.grid(row=15, columnspan=15)

    def make_move(self, i, j):
        if self.board[i][j] == ' ':
            self.board[i][j] = self.current_player
            self.buttons[i][j].config(text=self.current_player, state='disabled')
            if self.check_winner(i, j):
                self.status_label.config(text=f"玩家 {self.current_player} 赢了!")
                for i in range(15):
                    for j in range(15):
                        self.buttons[i][j].config(state='disabled')
            else:
                self.current_player = 'O' if self.current_player == 'X' else 'X'
                self.status_label.config(text=f"当前玩家: {self.current_player}")

    def check_winner(self, i, j):
        directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
        for dx, dy in directions:
            count = 1
            for k in range(1, 5):
                x, y = i + k*dx, j + k*dy
                if 0 <= x < 15 and 0 <= y < 15 and self.board[x][y] == self.current_player:
                    count += 1
                else:
                    break
            for k in range(1, 5):
                x, y = i - k*dx, j - k*dy
                if 0 <= x < 15 and 0 <= y < 15 and self.board[x][y] == self.current_player:
                    count += 1
                else:
                    break
            if count >= 5:
                return True
        return False

check_winner函数用于检查当前玩家是否获胜。它遍历四个方向(水平、垂直、正斜线、反斜线),检查是否有连续的五个棋子,如果有则返回True,表示当前玩家获胜。具体来说,该函数会对每个棋盘位置进行检查,以当前位置为起点,向四个方向(水平、垂直、正斜线、反斜线)延伸,统计相同标记的棋子数目。如果在某个方向上找到了连续的五个相同标记的棋子,就表示当前玩家获胜。

完整代码如下:

import tkinter as tk

class GobangGame:
    def __init__(self, root):
        self.root = root
        self.root.title("五子棋游戏")

        self.board = [[' ' for _ in range(15)] for _ in range(15)]
        self.current_player = 'X'

        self.buttons = [[tk.Button(root, text=' ', width=2, height=1, command=lambda i=i, j=j: self.make_move(i, j)) for j in range(15)] for i in range(15)]
        for i in range(15):
            for j in range(15):
                self.buttons[i][j].grid(row=i, column=j)

        self.status_label = tk.Label(root, text=f"当前玩家: {self.current_player}")
        self.status_label.grid(row=15, columnspan=15)

    def make_move(self, i, j):
        if self.board[i][j] == ' ':
            self.board[i][j] = self.current_player
            self.buttons[i][j].config(text=self.current_player, state='disabled')
            if self.check_winner(i, j):
                self.status_label.config(text=f"玩家 {self.current_player} 赢了!")
                for i in range(15):
                    for j in range(15):
                        self.buttons[i][j].config(state='disabled')
            else:
                self.current_player = 'O' if self.current_player == 'X' else 'X'
                self.status_label.config(text=f"当前玩家: {self.current_player}")

    def check_winner(self, i, j):
        directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
        for dx, dy in directions:
            count = 1
            for k in range(1, 5):
                x, y = i + k*dx, j + k*dy
                if 0 <= x < 15 and 0 <= y < 15 and self.board[x][y] == self.current_player:
                    count += 1
                else:
                    break
            for k in range(1, 5):
                x, y = i - k*dx, j - k*dy
                if 0 <= x < 15 and 0 <= y < 15 and self.board[x][y] == self.current_player:
                    count += 1
                else:
                    break
            if count >= 5:
                return True
        return False

# 创建主窗口
root = tk.Tk()
game = GobangGame(root)
root.mainloop()

运行结果如下,支持双人对战

  • 21
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是一个简单五子棋游戏Python代码,支持人机对战双人对战: ```python import random # 棋盘大小 BOARD_SIZE = 15 # 空白位置标记 EMPTY = 0 # 玩家和电脑标记 PLAYER = 1 COMPUTER = 2 # 初始化棋盘 def init_board(): board = [] for i in range(BOARD_SIZE): row = [EMPTY] * BOARD_SIZE board.append(row) return board # 打印棋盘 def print_board(board): print(" ", end="") for x in range(BOARD_SIZE): print("{0:2d}".format(x+1), end="") print() for i in range(BOARD_SIZE): print("{0:2d}".format(i+1), end="") for j in range(BOARD_SIZE): if board[i][j] == EMPTY: print(" .", end="") elif board[i][j] == PLAYER: print(" O", end="") elif board[i][j] == COMPUTER: print(" X", end="") print() # 判断胜负 def check_win(board, player): # 判断横向是否有五子连珠 for i in range(BOARD_SIZE): for j in range(BOARD_SIZE - 4): if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player: return True # 判断纵向是否有五子连珠 for i in range(BOARD_SIZE - 4): for j in range(BOARD_SIZE): if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player: return True # 判断斜向是否有五子连珠 for i in range(BOARD_SIZE - 4): for j in range(BOARD_SIZE - 4): if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player and board[i+4][j+4] == player: return True # 判断反斜向是否有五子连珠 for i in range(4, BOARD_SIZE): for j in range(BOARD_SIZE - 4): if board[i][j] == player and board[i-1][j+1] == player and board[i-2][j+2] == player and board[i-3][j+3] == player and board[i-4][j+4] == player: return True return False # 人类玩家下棋 def player_move(board): while True: row = int(input("请输入行号(1~15):")) col = int(input("请输入列号(1~15):")) if row < 1 or row > BOARD_SIZE or col < 1 or col > BOARD_SIZE: print("输入错误,请重新输入!") elif board[row-1][col-1] != EMPTY: print("该位置已经有棋子,请重新输入!") else: board[row-1][col-1] = PLAYER break # 计算每个位置的分数 def calculate_score(board, player): # 分数表 score_table = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 20, 30, 35, 40, 40, 35, 30, 20, 0, 0, 0, 0, 0, 0], [0, 30, 40, 45, 50, 50, 45, 40, 30, 0, 0, 0, 0, 0, 0], [0, 35, 45, 50, 55, 55, 50, 45, 35, 0, 0, 0, 0, 0, 0], [0, 40, 50, 55, 60, 60, 55, 50, 40, 0, 0, 0, 0, 0, 0], [0, 40, 50, 55, 60, 60, 55, 50, 40, 0, 0, 0, 0, 0, 0], [0, 35, 45, 50, 55, 55, 50, 45, 35, 0, 0, 0, 0, 0, 0], [0, 30, 40, 45, 50, 50, 45, 40, 30, 0, 0, 0, 0, 0, 0], [0, 20, 30, 35, 40, 40, 35, 30, 20, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ] # 计算每个位置的得分 scores = [] for i in range(BOARD_SIZE): row = [] for j in range(BOARD_SIZE): if board[i][j] == EMPTY: score = score_table[i][j] # 横向 if j > 0 and j < BOARD_SIZE-4: if board[i][j-1] == player and board[i][j+1] == player: score += 30 elif board[i][j-1] == player or board[i][j+1] == player: score += 15 # 纵向 if i > 0 and i < BOARD_SIZE-4: if board[i-1][j] == player and board[i+1][j] == player: score += 30 elif board[i-1][j] == player or board[i+1][j] == player: score += 15 # 斜向 if i > 0 and i < BOARD_SIZE-4 and j > 0 and j < BOARD_SIZE-4: if board[i-1][j-1] == player and board[i+1][j+1] == player: score += 30 elif board[i-1][j-1] == player or board[i+1][j+1] == player: score += 15 # 反斜向 if i > 0 and i < BOARD_SIZE-4 and j > 3 and j < BOARD_SIZE: if board[i-1][j+1] == player and board[i+1][j-1] == player: score += 30 elif board[i-1][j+1] == player or board[i+1][j-1] == player: score += 15 row.append(score) else: row.append(0) scores.append(row) return scores # 电脑玩家下棋 def computer_move(board): # 计算每个位置的得分 player_scores = calculate_score(board, PLAYER) computer_scores = calculate_score(board, COMPUTER) # 找到最高分数的位置 max_score = 0 candidates = [] for i in range(BOARD_SIZE): for j in range(BOARD_SIZE): if board[i][j] == EMPTY: score = player_scores[i][j] + computer_scores[i][j] if score > max_score: max_score = score candidates = [(i, j)] elif score == max_score: candidates.append((i, j)) # 在候选位置中随机选择一个 row, col = random.choice(candidates) board[row][col] = COMPUTER # 游戏主循环 def main(): board = init_board() print_board(board) while True: # 人类玩家下棋 player_move(board) print_board(board) if check_win(board, PLAYER): print("恭喜你获胜!") break # 电脑玩家下棋 computer_move(board) print_board(board) if check_win(board, COMPUTER): print("很遗憾,你输了!") break if __name__ == '__main__': main() ``` 运行程序后,按照提示输入行号和列号即可下棋。如果选择人机对战,电脑会自动计算每个位置的得分,并选择得分最高的位置下棋。如果选择双人对战,两个玩家轮流下棋,直到有一方获胜。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mrji1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值