井字棋——ai PK you

挑战人工智能,体验经典井字棋的对决!AI 拥有强大的逻辑计算能力,每一步都经过精准推演。你能战胜它吗?还是会被 AI 彻底碾压?

特点:

智能 AI,难度可调
极简界面,快速上手
实时胜负统计,见证你的进步


代码如下:

import sys
from random import choice
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QVBoxLayout, QHBoxLayout, QLabel
from PyQt5.QtCore import Qt


class TicTacToe(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('井字棋游戏')
        self.setGeometry(100, 100, 400, 400)

        self.buttons = []
        self.current_player = 'X'  # 玩家是X,AI是O
        self.game_over = False
        self.board = ['' for _ in range(9)]

        self.initUI()

    def initUI(self):
        # 顶部信息标签
        self.info_label = QLabel("玩家的回合 - 点击格子放置X", self)
        self.info_label.setAlignment(Qt.AlignCenter)

        # 创建3x3按钮网格
        layout = QVBoxLayout()
        layout.addWidget(self.info_label)

        for i in range(3):
            row = QHBoxLayout()
            for j in range(3):
                index = i * 3 + j
                button = QPushButton('', self)
                button.setFixedSize(100, 100)
                button.clicked.connect(lambda _, idx=index: self.button_clicked(idx))
                row.addWidget(button)
                self.buttons.append(button)
            layout.addLayout(row)

        # 重新开始按钮
        restart_button = QPushButton('重新开始', self)
        restart_button.clicked.connect(self.reset_game)
        layout.addWidget(restart_button)

        self.setLayout(layout)

    def button_clicked(self, index):
        if self.game_over or self.board[index] != '' or self.current_player != 'X':
            return

        # 玩家下棋
        self.board[index] = 'X'
        self.buttons[index].setText('X')
        self.buttons[index].setEnabled(False)

        # 检查游戏是否结束
        if self.check_winner('X'):
            self.info_label.setText("玩家胜利!")
            self.game_over = True
            QMessageBox.information(self, "游戏结束", "你赢了!", QMessageBox.Ok)
            return

        # 检查是否平局
        if '' not in self.board:
            self.info_label.setText("平局!")
            self.game_over = True
            QMessageBox.information(self, "游戏结束", "平局!", QMessageBox.Ok)
            return

        # AI下棋
        self.ai_move()

    def ai_move(self):
        self.current_player = 'O'
        self.info_label.setText("AI的回合...")

        # 简单AI: 随机选择一个空格子
        empty_spots = [i for i, val in enumerate(self.board) if val == '']
        if empty_spots:
            # 可以在这里实现更复杂的AI逻辑
            move = self.simple_ai()
            self.board[move] = 'O'
            self.buttons[move].setText('O')
            self.buttons[move].setEnabled(False)
            self.info_label.setText("玩家的回合 - 点击格子放置X")
            self.current_player = 'X'

            # 检查游戏是否结束
            if self.check_winner('O'):
                self.info_label.setText("AI胜利!")
                self.game_over = True
                QMessageBox.information(self, "游戏结束", "AI赢了!", QMessageBox.Ok)
                return

            # 检查是否平局
            if '' not in self.board:
                self.info_label.setText("平局!")
                self.game_over = True
                QMessageBox.information(self, "游戏结束", "平局!", QMessageBox.Ok)
                return

    def simple_ai(self):
        # 先检查是否有必胜的机会
        for i in range(9):
            if self.board[i] == '':
                self.board[i] = 'O'
                if self.check_winner('O'):
                    self.board[i] = ''
                    return i
                self.board[i] = ''

        # 如果没有必胜机会,再检查是否需要阻挡玩家
        for i in range(9):
            if self.board[i] == '':
                self.board[i] = 'X'
                if self.check_winner('X'):
                    self.board[i] = ''
                    return i
                self.board[i] = ''

        # 如果没有必胜或阻挡的必要,尝试占据中心
        if self.board[4] == '':
            return 4

        # 尝试占据角位
        corners = [0, 2, 6, 8]
        empty_corners = [i for i in corners if self.board[i] == '']
        if empty_corners:
            return choice(empty_corners)

        # 最后选择边位
        edges = [1, 3, 5, 7]
        empty_edges = [i for i in edges if self.board[i] == '']
        return choice(empty_edges) if empty_edges else -1

    def check_winner(self, player):
        # 检查行
        for i in range(0, 9, 3):
            if self.board[i] == self.board[i + 1] == self.board[i + 2] == player:
                return True

        # 检查列
        for i in range(3):
            if self.board[i] == self.board[i + 3] == self.board[i + 6] == player:
                return True

        # 检查对角线
        if self.board[0] == self.board[4] == self.board[8] == player:
            return True
        if self.board[2] == self.board[4] == self.board[6] == player:
            return True

        return False

    def reset_game(self):
        for i in range(9):
            self.buttons[i].setText('')
            self.buttons[i].setEnabled(True)
        self.board = ['' for _ in range(9)]
        self.current_player = 'X'
        self.game_over = False
        self.info_label.setText("玩家的回合 - 点击格子放置X")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    game = TicTacToe()
    game.show()
    sys.exit(app.exec_())

效果展示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

准时准点睡觉

如果觉得不错可以点点这里哦

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

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

打赏作者

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

抵扣说明:

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

余额充值