如何生成骑士的所有动作? [英] How do I generate all of a knight's moves?

查看:57
本文介绍了如何生成骑士的所有动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写一个Chess程序,该程序需要生成骑士的所有动作。对于不熟悉国际象棋的人,骑士会以L形运动。



因此,给定位置(2,4)骑士可以移动到(0,3)(0,5)(1、2)(3、2 )等,总共(最多)八个不同的动作。 / p>

我想编写一个名为 knight_moves 的函数,该函数在列表中生成这些元组。在Python中最简单的方法是什么?

  def knight_moves(position):
'''返回a给定骑士当前位置的新位置列表。 '''
通过


解决方案

好的感谢Niall Byrne,我想到了这个:

 从itertools进口产品
def knight_moves(position):
x,y =位置
移动= list(product([x-1,x + 1],[y-2,y + 2]))+ list(product([x-2,x + 2],[y-1,y + 1]))
moves = [(x,y)对于x,y,如果x> = 0且y> = 0且x< 8并且y< 8]
返回移动


I am writing a Chess program in Python that needs to generate all the moves of a knight. For those not familiar with chess, a knight moves in an L shape.

So, given a position of (2, 4) a knight could move to (0, 3), (0, 5), (1, 2), (3, 2), etc. for a total of (at most) eight different moves.

I want to write a function called knight_moves that generates these tuples in a list. What is the easiest way to do this in Python?

def knight_moves(position):
    ''' Returns a list of new positions given a knight's current position. '''
    pass

解决方案

Ok, so thanks to Niall Byrne, I came up with this:

from itertools import product
def knight_moves(position):
    x, y = position
    moves = list(product([x-1, x+1],[y-2, y+2])) + list(product([x-2,x+2],[y-1,y+1]))
    moves = [(x,y) for x,y in moves if x >= 0 and y >= 0 and x < 8 and y < 8]
    return moves

这篇关于如何生成骑士的所有动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆