下面是用python实现的一个弹窗五子棋游戏的代码示例:

import tkinter as tk

class Gobang:
    def __init__(self, master):
        self.master = master
        self.canvas = tk.Canvas(self.master, width=500, height=500)
        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.place_piece)
        self.board = [[0] * 15 for _ in range(15)]
        self.turn = 1  # 1 for black, 2 for white

    def place_piece(self, event):
        x = event.x // 30
        y = event.y // 30
        if self.board[x][y] == 0:
            if self.turn == 1:
                self.canvas.create_oval(x*30, y*30, (x+1)*30, (y+1)*30, fill="black")
                self.board[x][y] = 1
                self.turn = 2
            else:
                self.canvas.create_oval(x*30, y*30, (x+1)*30, (y+1)*30, fill="white")
                self.board[x][y] = 2
                self.turn = 1
            if self.check_win(x, y):
                winner = "Black" if self.turn == 2 else "White"
                self.canvas.unbind("<Button-1>")
                tk.messagebox.showinfo("Game Over", f"{winner} wins!")
                
    def check_win(self, x, y):
        directions = [(0, 1), (1, 0), (1, 1), (-1, 1)]
        for dx, dy in directions:
            count = 1
            for i in range(1, 5):
                new_x = x + dx * i
                new_y = y + dy * i
                if new_x < 0 or new_x >= 15 or new_y < 0 or new_y >= 15 or self.board[new_x][new_y] != self.turn:
                    break
                count += 1
            for i in range(1, 5):
                new_x = x - dx * i
                new_y = y - dy * i
                if new_x < 0 or new_x >= 15 or new_y < 0 or new_y >= 15 or self.board[new_x][new_y] != self.turn:
                    break
                count += 1
            if count >= 5:
                return True
        return False

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Gobang")
    game = Gobang(root)
    root.mainloop()

这个代码使用了tkinter库来创建窗口和画布。在画布上绘制棋盘,并通过鼠标点击事件来放置棋子。游戏的逻辑使用一个二维列表来表示棋盘,1表示黑子,2表示白子。每次放置棋子后,会检查是否有玩家获胜。如果有玩家获胜,则弹出一个提示框显示胜利者,并禁用鼠标点击事件。

请注意,这个示例只实现了基本的游戏逻辑,还有很多功能可以进一步完善,比如悔棋功能、重新开始游戏等

用python写一个弹窗五子棋游戏

原文地址: https://www.cveoy.top/t/topic/iwE3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录