当前位置: 首页 > news >正文

Python新手练习——五子棋

全局变量和初始设置

import os

board = [[0 for _ in range(9)] for _ in range(9)]
player_row = 0
player_col = 0
cpu_row = 0
cpu_col = 0

  • board 是一个9x9的二维列表,用于表示棋盘。0表示空位,1表示CPU的棋子,2表示玩家的棋子。
  • player_row 和 player_col 记录玩家最近一次落子的行和列。
  • cpu_row 和 cpu_col 记录CPU最近一次落子的行和列。

工具函数

def isBlack(row, col):
    return board[row][col] == 2

  • isBlack() 函数检查给定位置是否是玩家的棋子(黑子)。

胜利检查函数

def checkWin(row, col, player):
    directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
    for dr, dc in directions:
        count = 1
        for i in range(1, 5):
            r, c = row + i * dr, col + i * dc
            if 0 <= r < 9 and 0 <= c < 9 and board[r][c] == player:
                count += 1
            else:
                break
        for i in range(1, 5):
            r, c = row - i * dr, col - i * dc
            if 0 <= r < 9 and 0 <= c < 9 and board[r][c] == player:
                count += 1
            else:
                break
        if count >= 5:
            return True
    return False

  • checkWin() 函数用于检查某个玩家在给定位置是否获胜。
  • 它检查四个方向(水平、垂直、两个对角线)是否有连续5个相同的棋子。
  • drdc分别表示行和列的增量,用于方向控制。

玩家和CPU胜利检查

def isPlayerWin():
    return checkWin(player_row, player_col, 2)

def isCPUWin():
    return checkWin(cpu_row, cpu_col, 1)

  • isPlayerWin() 和 isCPUWin() 使用 checkWin() 函数来检查玩家和CPU是否获胜。

落子函数

def down(row, col, is_player):
    global cpu_row, cpu_col
    if is_player:
        board[row][col] = 2
    else:
        board[row][col] = 1
        cpu_row, cpu_col = row, col

  • down() 函数用于在指定位置落子。
  • 根据 is_player 参数决定落下的是玩家的棋子还是CPU的棋子。

显示棋盘

def showBoard():
    os.system('cls' if os.name == 'nt' else 'clear')
    print('   ' + '   '.join(str(i+1) for i in range(9)))
    print('  +' + '---+' * 9)
    for r in range(len(board)):
        data = f'{r+1} |'
        for c in range(len(board[r])):
            if board[r][c] == 0:
                data += '   |'
            elif board[r][c] == 1:
                data += ' w |'
            else:
                data += ' y |'
        print(data)
        print('  +' + '---+' * 9)

  • showBoard() 函数在控制台上绘制棋盘。
  • 使用不同的符号表示空位、CPU的棋子和玩家的棋子。

显示棋盘改进点:

  1. 边框和分隔线

    • 每行元素之间和列之间添加了|+---+作为分隔符,使棋盘看起来更像一个表格。
    • 给顶行和每行添加了列号,方便用户识别位置。
  2. 输出格式

    • 使用f-string格式化输出,使代码更简洁和易读。
    • 增加了行号和列号的对齐,确保数字和符号输出在同一水平线上。

玩家回合

def playerRound():
    global player_row, player_col
    while True:
        player_input = input('你是黑子,请你输入行列来落子,例如:18  表示1行8列:')
        if len(player_input) != 2 or not player_input.isdigit():
            print("输入格式错误,请输入两个数字,如:18")
            continue
        player_row = int(player_input[0]) - 1
        player_col = int(player_input[1]) - 1
        if 0 <= player_row < 9 and 0 <= player_col < 9 and board[player_row][player_col] == 0:
            down(player_row, player_col, is_player=True)
            break
        else:
            print("位置不合法,请重新输入。")

  • playerRound() 函数处理玩家的回合。
  • 检查用户输入是否合法,并在合法位置落子。
  • 错误输入会提示玩家重新输入。

CPU回合

def cpuRound():
    directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
    max_continue_count = 0
    final_row = None
    final_col = None

    for row in range(9):
        for col in range(9):
            if board[row][col] != 0:
                continue

            for dr, dc in directions:
                continue_count = 1
                for i in range(1, 5):
                    r, c = row + i * dr, col + i * dc
                    if 0 <= r < 9 and 0 <= c < 9 and board[r][c] == 2:
                        continue_count += 1
                    else:
                        break

                for i in range(1, 5):
                    r, c = row - i * dr, col - i * dc
                    if 0 <= r < 9 and 0 <= c < 9 and board[r][c] == 2:
                        continue_count += 1
                    else:
                        break

                if continue_count > max_continue_count:
                    max_continue_count = continue_count
                    final_row = row
                    final_col = col

    if final_row is not None and final_col is not None:
        down(final_row, final_col, is_player=False)
    else:
        for row in range(9):
            for col in range(9):
                if board[row][col] == 0:
                    down(row, col, is_player=False)
                    return

  • cpuRound() 函数处理CPU的回合。
  • 方法是检查所有空位置,计算每个位置在四个方向上与玩家棋子连成一线的最大连续数。
  • 优先阻止玩家形成五子连珠。

主游戏循环

while True:
    showBoard()
    playerRound()
    if isPlayerWin():
        showBoard()
        print('恭喜!你赢了!')
        break
    cpuRound()
    if isCPUWin():
        showBoard()
        print('哎!你输了!')
        break

  • 主循环不断交替进行玩家和CPU的回合。
  • 每回合结束后检查是否有一方获胜,如果有,显示结果并结束游戏。

这段代码实现了基本的五子棋游戏,其中包括输入验证、胜利检查、棋盘显示等功能。游戏通过回合制的方式进行,直到一方获胜为止。

相关文章:

  • 霸王茶姬小程序(2025年1月版)任务脚本
  • 指定 Python 3.12.6-slim 作为基础镜像
  • AwesomeQt分享3(含源码)
  • persist 应用自启流程
  • 硬件测试工装设计不合理的补救措施
  • Linux内核2-TFTP与NFS环境搭建
  • 通过Map类和List类的List<Map<>>组合类体会JSON
  • 信号与系统(郑君里)第一章-绪论 1-19 课后习题解答
  • 从DeepSeek到Qwen,AI大模型的移植与交互实战指南
  • Python贝叶斯分层模型专题|对环境健康、医学心梗患者、体育赛事数据空间异质性实证分析合集|附数据代码
  • elementUI el-image图片加载失败解决
  • 3.28学习总结
  • Java实现定时任务
  • 深入剖析ReentrantLock底层原理:从AQS到公平锁的源码级解析
  • 游戏引擎学习第189天
  • Selenium测试框架快速搭建
  • AILabel标注工具指南(二):禁止图片外标注
  • 技术速递|为 .NET 的 AI 评估解锁新的可能性
  • 跟着尚硅谷学vue-day1
  • Debian ubuntu源
  • 王晋卿读《酒的精神》︱乏味时代的有味之思
  • 同济大学党委常务副书记冯身洪履新中国科协党组副书记
  • 王毅会见美国亚洲协会会长康京和
  • 外交部:中方支持俄乌直接对话谈判,支持政治解决危机
  • 国家发改委:正在会同有关方面,加快构建统一规范、协同共享、科学高效的信用修复制度
  • “十五五”规划编制工作开展网络征求意见活动