值得一提的是,這裏有一個用Python編寫的暴力破解器。有趣!你甚至可以用N> 2來運行它,以便每回合放下更多的棋子。請注意,失敗的玩家只是玩最左邊的有效動作。
一,輸出。我以不同的棋盤尺寸(從這裏的2到16)開始了比賽。
Size = 2
..
11
Player 1 Wins!
Size = 3
...
11.
Player 1 Wins!
Size = 4
....
.11.
Player 1 Wins!
Size = 5
.....
11...
1122.
Player 2 Wins!
Size = 6
......
..11..
2211..
221111
Player 1 Wins!
Size = 7
.......
11.....
1122...
112211.
Player 1 Wins!
Size = 8
........
.11.....
.1122...
.112211.
Player 1 Wins!
Size = 9
.........
11.......
1122.....
112211...
11221122.
Player 2 Wins!
Size = 10
..........
....11....
22..11....
22..1111..
22221111..
2222111111
Player 1 Wins!
Size = 11
...........
11.........
1122.......
112211.....
11221122...
1122112211.
Player 1 Wins!
Size = 12
............
.11.........
.1122.......
.112211.....
.11221122...
.1122112211.
Player 1 Wins!
Size = 13
.............
...11........
22.11........
22.11.11.....
22.11.1122...
22.11.112211.
Player 1 Wins!
Size = 14
..............
......11......
22....11......
22....1111....
2222..1111....
2222..111111..
222222111111..
22222211111111
Player 1 Wins!
Size = 15
...............
11.............
11...22........
1111.22........
1111.22.22.....
1111.22.2211...
1111.22.221122.
Player 2 Wins!
Size = 16
................
.....11.........
22...11.........
2211.11.........
2211.1122.......
2211.112211.....
2211.11221122...
2211.1122112211.
Player 1 Wins!
下面的代碼:
N = 2 # number of pieces placed per turn
CACHE = {}
def compute_moves(board):
gaps = [0] * len(board)
previous = 0
for i in range(len(board) - 1, -1, -1):
if board[i]:
previous = 0
gaps[i] = 0
else:
previous += 1
gaps[i] = previous
return [i for i, gap in enumerate(gaps) if gap >= N]
def do_move(board, index, player):
for i in range(N):
board[index + i] = player
def undo_move(board, index):
for i in range(N):
board[index + i] = 0
def search(board):
key = tuple(board)
if key in CACHE:
return CACHE[key]
moves = compute_moves(board)
for move in moves:
do_move(board, move, 1)
a, _ = search(board)
undo_move(board, move)
if not a:
result = (True, move)
break
else:
result = (False, moves[0] if moves else None)
CACHE[key] = result
return result
def play(board):
player = 0
while True:
print ''.join(str(x or '.') for x in board)
_, index = search(board)
if index is None:
break
do_move(board, index, player + 1)
player = int(not player)
print 'Player %d Wins!' % (int(not player) + 1)
for size in range(2, 17):
print 'Size = %d' % size
board = [0] * size
play(board)
print
你會如何慶祝,如果一個特定的狀態是贏或輸?另外,什麼是K? – user1248092 2012-03-14 18:05:22
@ user1248092看到我上面的僞代碼。數字「k」是任何整數。關鍵在於拍攝點的數量總是偶數,因此對於某些非負整數「k」,其形式爲「4k」或「4k + 2」(例如,如果拍攝的點數是「14」那麼'k = 3'因爲'14 = 4 * 3 + 2')。 – PengOne 2012-03-14 18:15:58
我剛剛在板子上運行你的代碼[0,0,0,0],它說錯誤。 P1應該贏。 – user1248092 2012-03-14 18:27:50