【问题标题】:Issue with python skipping code in simple chess programpython在简单国际象棋程序中跳过代码的问题
【发布时间】:2020-02-26 08:33:26
【问题描述】:

我正在为国际象棋创建一个简单的程序,但遇到了一个据称是 python 跳过代码的问题。 程序入口为:find_side()

控制台输出:

Enter your team(1-black 2-white):1
<PlayResult at 0x3ec1dc0 (move=e2e4, ponder=d7d5, info={}, draw_offered=False, resigned=False)>
Enter your enemies move:

根据控制台输出,引擎为白棋随机生成招式,并在思考中做出了反击。但是我对此有输入,看起来,python 比用户输入更早地执行result_engine。 此外,还有一个问题。引擎完全忽略chess.engine.turn = turn 行。 我使用 stockfish 11 作为引擎,import chess 作为 python 代码和具有通用国际象棋引擎的引擎之间的链接 代码:

import chess
import chess.engine
import time
import os

def logic_white():
    engine = chess.engine.SimpleEngine.popen_uci("C:\\Users\\Admin\\Desktop\\sf.exe")
    board = chess.Board()

    turn = True  # True - white False - black
    while True:
        chess.engine.turn = turn # This isn't working
        result_engine = engine.play(board,chess.engine.Limit(time=0.1))
        print(result_engine)

        res = input("Enter your enemie's move: ")
        move = chess.Move.from_uci(res)

        board.push(move)
        turn = not turn
        time.sleep(0.5)

def logic_black():
    engine = chess.engine.SimpleEngine.popen_uci("C:\\Users\\Admin\\Desktop\\sf.exe")
    board = chess.Board()

    turn = True # True - white False - black
    while True:
        chess.engine.turn = turn # This isn't working

        res = input("Enter your enemie's move: ")
        move = chess.Move.from_uci(res) #Inputting the enemy move and putting in on the virtual board
        board.push(move)

        result_engine = engine.play(board,chess.engine.Limit(time=0.1)) #Calculating best move to respond
        print(result_engine)
        board.push(result_engine) #Push the engine's move to the virtual board

        turn = not turn # Inverting turn, so turns can change from black to white, etc.
        time.sleep(0.5)       

def find_side():
    if(input("Enter your team(1-black 2-white):")) == 1:
        logic_black()
    else:
        logic_white()

【问题讨论】:

  • 看起来是个有趣的程序,请附上一个产生此问题的运行代码示例,您发布的代码没有起点。
  • 基本上,这是一个起点。在程序结束时,我只有一个find_side() 调用
  • 不确定这是什么效果,但您可能在顶部的logic_white() 函数中缺少board.push(result_engine)
  • 我的代码是有序的,我在这里发布。函数在上面,它们的调用如下。事实上,给出了输出并且没有给出任何错误。例如 - logic_black not found,我想,python看到了这个函数。而关于board.push(result_engine),先手是白棋,所以我会先输入,然后再计算下一步。将其放在顶部将导致 0 或 RAM 中的任何随机值被写入板上。

标签: python chess


【解决方案1】:

Python 的输入函数返回一个字符串,因此它永远不会等于整数 1。因此,代码将始终进入 else 块。要解决此问题,请将输入转换为整数或将其与“1”进行比较。

def find_side():
    if int(input("Enter your team(1-black 2-white):")) == 1:
        logic_black()
    else:
        logic_white()

【讨论】:

  • 好的,谢谢。也许您对python中的国际象棋库有所了解?为什么在 chess.engine.turn 中忽略 turn?
  • 我正在查看文档,似乎 chess.engine.turn 不是 chess.engine 中存在的属性,因此它没有做任何事情。所以并不是它被忽视了。程序将 turn 的值分配给 chess.engine.turn。只是这个赋值不会产生任何结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
相关资源
最近更新 更多