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

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的回合。
  • 每回合结束后检查是否有一方获胜,如果有,显示结果并结束游戏。

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


http://www.kler.cn/a/613506.html

相关文章:

  • 【3.31-4.6学习周报】
  • position embedding
  • 近场探头的选型
  • uni-app自动升级功能
  • 5.0 WPF的基础介绍1-Grid,Stack,button
  • 如何编写单元测试
  • jenkins批量复制视图项目到新的视图
  • 关于笔记本电脑突然没有wifi图标解决方案
  • 口腔种植全流程AI导航系统及辅助诊疗与耗材智能化编程分析
  • 代理IP协议详解HTTP、HTTPS、SOCKS5分别适用于哪些场景
  • 大模型在支气管扩张预测及治疗方案制定中的应用研究
  • Windows 图形显示驱动开发-WDDM 2.4功能-GPU 半虚拟化(八)
  • 小迪安全-php模型,mvc架构,动态调试未授权,脆弱及安全,为引用。逻辑错误
  • 计算机三级网络技术大题总结
  • QT计算器开发
  • DeepSeek R1与V3:混合架构下的推理革命与效率破局
  • 特仑苏首发牛奶人文纪录片!如何借势营销重构品牌护城河?
  • SpringBoot项目中,controller 、 entity、mapper和service包的介绍
  • 4、网工软考—VLAN配置—hybird配置
  • 【C++】模拟实现一颗二叉搜索树