2015-02-12 71 views
0

我正在研究Tic-Tac-Toe AI,並且希望找到最後一步(在當前轉向之前對手上一步移動)使用遊戲引擎提供的一長串。找到最後一個int(1-9)存儲在多個位中(每個int都由4位表示)

每個空間都由一個數字1-9整數表示(我將從中減去1以獲得移動0-8,外加9的移動存儲在0xF中)。

0xE用於表示NULL,但會被我的程序視爲與板外移動相同。

以下是本場比賽的狀態是如何編碼:

Used to encode game State, first 4 bits are first move, second 4 bits second move, (4 * 9 = 36 bits) bits 33-36 are the last Move. Each move is the coordinate singleton + 1, therefore the tictactoe board is recorded as... 
    1 | 2 | 3 
    4 | 5 | 6 
    7 | 8 | 9 

Normal equation for singleton is row*3+col, but you cannot record a state as 0, therefore game state moves are row*3+col + 1, note difference Coordinate singleton is 0..8, board game state position is 1..9; 
1 | 2 | 3 
4 | 5 | 6 
7 | 8 | 9 



The game state 0x159, X first move 9; O move 2 is 5;move 3 X is 1 


X _ _ 
_ O _ 
_ _ 9 



Sets off board set all 4 bits (aka 0xf). 


e.g., 0x12f45, On X's second move (game move 3) 
X picked a Coordinate outside the tictactoe range. 


Duplicate guesses onto occupied square are just saved 


e.g., 0x121 implies X has used position 1 on both his 
first and second move 


Null coordinate usually caused by exception is saved as 0xE 


e.g., 0x1E3; implies on game move 2, O first move, O throw an exception 
most likely causes index array out of bounds 

截至目前,這裏是我如何使用引擎的遊戲狀態找到最後的舉動:

private int LastMoveFinder(final Board brd, int move) 
{ 
    char prevMove = Long.toHexString(brd.getGameState()).charAt(0); 

    if(prevMove == 'f' || prevMove == 'e') 
     return 9; 
    else 
     return Character.getNumericValue(prevMove) - 1; 
} 

但是,我肯定有更快的方式(性能明智的)找到最後一步使用某種位移方法,因爲我們的AI將針對速度(nanoSec /移動)和雙贏損失比率進行測試。

我已經閱讀了有關bitshifting和搜索遍及整個stackoverflow爲我的問題的答案,但沒有任何我試圖實施到我的程序已經工作。

我確定我錯過了一些簡單的東西,但還沒有采取一個涵蓋了偏移和屏蔽的課程,所以我有些失落。

感謝您的幫助。

+1

這是爲什麼用java和C++標記的?你想要哪一個? – AndyG 2015-02-12 02:32:14

+0

性能最高的方法是放棄位,並使用常規大小的整數。現代平臺上沒有保存內存的獎勵。我相當確定運行你的程序的平臺將有足夠的內存。 – 2015-02-12 02:34:21

回答

0

通過與位掩碼0xf左移4 * moveNumber位,可以得到4位的int。然後,將結果右移4 * moveNumber位以獲得一個int,並將移動邏輯應用於該int。修改後的方法是:

/** 
    Assumes moveNumber is 0 indexed. 
*/ 
private int LastMoveFinder(final Board brd, int moveNumber) 
{ 
    int moveMask = 0xf << (4 * moveNumber); 
    int prevMove = (brd.getGameState() & moveMask) >>> (4 * moveNumber); 

    if (prevMove == 0xf || prevMove == 0xe) { 
     return 9; 
    } else { 
     return prevMove - 1; 
    } 
} 
+0

感謝您的快速響應!我實現了這個代碼,但它並不工作。到目前爲止,該方法在第一次搜索時發現移動,但後續所有遊戲運行返回-1(prevMode - 1,所以真正的prevMode返回0)。我以1和0開始運行,結果是一樣的。 – Scott 2015-02-12 03:25:27

+0

編輯:工作。移動次數已經減少一次,因爲當前移動總是比遊戲狀態編碼時的移動次數多1次。非常感謝你的幫助! – Scott 2015-02-12 03:32:06

+0

使用位掩碼和bitshift找到最後一步與轉換爲HexString的速度相比要快4倍(.446ms vs 2.22ms) – Scott 2015-02-12 03:39:01

相關問題