簡體   English   中英

國際象棋騎士,可用動作

[英]Chess Knight, Available movement

# Input coordinates for position, convert to integers.
start = [int(input("x: ")),int(input("y: "))] 

# Available moves for Knight ( 3 steps like **L**)
available = [
    [start[0]-1,start[1]-2],
    [start[0]-2,start[1]-1],
    [start[0]+1,start[1]-2],
    [start[0]+2,start[1]-1],
    [start[0]-1,start[1]+2],
    [start[0]-2,start[1]+1],
    [start[0]+1,start[1]+2],
    [start[0]+2,start[1]+1]
]  

對於每一行水平打印 (1-8) 和每一列字符“O” 。如果坐標**(x,y)** 在可用列表中打印M 其次,如果檢查棋盤移動的位置是可能的。

used_positions = 0

for y in range(8):
    print(y+1,end=" ")0-8  #  y+1 will start from 1-8 and not 0- 8       
    
letters = ['A','B','C','D','E','F','G','H']


    for x in range(8):
        chr = "O"
        if [x+1,y+1] == start:
            chr = "S"
        if [x+1,y+1] in available:
            used_positions+=1
            chr = "M"
        print(chr,end="") # skips newline
    print() # after every column  newline
print(end="  ") # newline, 2 whitespaces
for l in letters:
    print(l,end="") # prints letters

print() # newline

print("Possible positions:",used_positions) # prints how many positions are possible
print(available,end='') # prints available positions in same line

那是因為騎士在L移動。 所以,-1 和 -2 是為了遵循這種方式。 例如:



下 2 步,左 1 步。

例如,我的輸入是x=2, y=2 四個可能的位置: [4,1]、[3,4]、[4,3]、[1,4] ,標記為M 每個 x 和 y 都是在可用位置計算的。 例如 [start[0]-1,start[1]-2], 2-1 = 1 (x = 1), 2-2 = 0 (y), [1,0]。

1 OOOMOOOO
2 OSOOOOOO
3 OOOMOOOO
4 MOMOOOOO
5 OOOOOOOO
6 OOOOOOOO
7 OOOOOOOO
8 OOOOOOOO
  ABCDEFGH
Possible positions: 4
[[1, 0], [0, 1], [3, 0], [4, 1], [1, 4], [0, 3], [3, 4], [4, 3]]

您可以在過濾掉“董事會外”職位的列表理解中實現這一點:

def knightMoves(x,y):
    return [(x+dx,y+dy)
            for h,v   in [(1,2),(2,1)]                     # magnitudes
            for dx,dy in [(h,v),(h,-v),(-h,v),(-h,-v)]     # directions
            if x+dx in range(1,9) and y+dy in range(1,9) ] # in-board

output:

knightMoves(4,5)
[(5, 7), (5, 3), (3, 7), (3, 3), (6, 6), (6, 4), (2, 6), (2, 4)]

knightMoves(8,8)
[(7, 6), (6, 7)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM