简体   繁体   English

如何在 Python 中找到有效的骑士移动?

[英]How to find a valid knight move in Python?

Chess knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally.棋马可以移动到水平两格垂直一格,或垂直两格水平一格的格子。 Given two different squares of the chessboard, determine whether a knight can go from the first square to the second one in a single move.给定棋盘的两个不同方格,判断一个马是否可以一次移动从第一个方格到第二个方格。 The input is four characters: letters from a to h and numbers from 1 to 8, each specifying the column and the row number.输入是四个字符:从 a 到 h 的字母和从 1 到 8 的数字,每个字符指定列号和行号。 First two are for the first square, and the last two for the second square.前两个用于第一个方格,后两个用于第二个方格。 The program should print True if a knight can go from the first square to the second one in one move.如果骑士可以从第一个方格 go 一次移动到第二个方格,则程序应该打印 True。 Or print False otherwise.否则打印 False 。

Example 1 Can the knight go from d4 to c6?示例 1 骑士 go 可以从 d4 到 c6 吗? Yes!是的! input d 4 c 6 output True Example 2 input d 4 e 2 output True Example 3 There's no move from f6 to g5 for the chess knight输入 d 4 c 6 output 真实示例 2 输入 d 4 e 2 output 真实示例 3 骑士没有从 g5 移动

input f 6 g 5 output False输入 f 6 g 5 output 假

What have you tried so far?你试过什么了?

You can make calculations between the current position and the next one... Considering that knight can only move [1, 2] or [2, 1].您可以在当前的 position 和下一个之间进行计算...考虑到骑士只能移动 [1, 2] 或 [2, 1]。

Based on that I recommend you to work with values intead of letters on the board.基于此,我建议您使用值而不是板上的字母。

def IsMovePossible(player, currentPos, nextPos):

    # You need to replace the currentPos and nextpos for the way you're working on the tiles
    xDif = abs(currentPos[0] - nextPos[0])
    yDif = abs(currentPos[1] - nextPos[1])

    if player == "Knight":
        return (xDif == 2 and yDif == 1) or (xDif == 1 and yDif == 2)

# Considering the chess tiles as array
print(IsMovePossible("Knight", currentPos, nextPos))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM