2016-08-10 39 views
0

首先感謝您嘗試提供幫助。在TicTacToe遊戲中製作具有動態裝訂檢查功能的方法

我有一個井字遊戲在Python完成,你可以在這裏看看:https://github.com/Weffe/TicTacToe

目前,一切都運行了一個3x3的比賽場地完全正常。我想讓遊戲充滿活力,因爲它可以輕鬆擴展到9x9而不會出現任何問題。但是,我有點腦殘,無法找出最簡單的方法來實現這一點。主要問題在於Player.py的函數get_player_loc_input()。

現在它只是配置爲3x3的遊戲場。但是,我想讓它變得動態。

原始代碼:

def get_player_loc_input(self): 
    player_input = input('Enter in location for your move: ') # player input is with respect to field index location 
    translated_input = int(player_input) 

    if 7 <= translated_input <= 9: 
     translated_input = [0, (translated_input - 7)] # row, col 
    elif 4 <= translated_input <= 6: 
     translated_input = [1, (translated_input - 4)] # row, col 
    elif 1 <= translated_input <= 3: 
     translated_input = [2, (translated_input - 1)] # row, col 
    else: 
     raise ValueError('Input is not an index on the playing field. Try again\n') 
    return translated_input 

我目前的動態嘗試:

def get_player_loc_input(self, num_rows, num_cols): 
    value = num_rows*num_cols 
    num_rows = num_rows - 1 #adjust from n+1 to n 
    for x in range(value, 0, 3): 
     lower_bound = x-2 
     upper_bound = x 
     if lower_bound <= translated_input <= upper_bound: 
      translated_input = [num_rows, (translated_input - lower_bound)] 
      num_rows = num_rows - 1 #move down to the next row we're on 
    return translated_input 

比賽場地

------------- 
| 7 | 8 | 9 | #row 0 
------------- 
| 4 | 5 | 6 | #row 1 
------------- 
| 1 | 2 | 3 | #row 2 
------------- 

它的工作方式是通過輸入的數量的圖片您要替換的索引。然後該函數將該數字轉換爲[row,col]「value」。

因此,例如,4 => [1,0] OR 3 => [2,2]

任何想法?要去做點別的事情來清理我的頭。

+0

只需使用整數除法並且它是餘數 - 例如row = input/rowlength,而col = input%rowlength。當你從上到下統計行數時,行將被恢復,但希望你明白。 –

回答

0

有點不是分裂&模更復雜,因爲行是不正確的順序

下面是這適用於所有值

泛型函數
def get_player_loc_input(nb_rows, nb_cols, pinput): 
    pinput -= 1 
    rval = (nb_rows-(pinput//nb_cols)-1,pinput%nb_cols) 
    return rval 

print(get_player_loc_input(3,3,3)) 
print(get_player_loc_input(3,3,4)) 
print(get_player_loc_input(3,3,7)) 

輸出:

(2, 2) 
(1, 0) 
(0, 0) 

注你的代碼一定有問題,因爲你有一個方法,self,仍然通過nb_rows & nb_cols作爲參數。應該是班級成員(並且translated_input未定義)

+0

哇,它的工作原理!是的,對不起,如果我不清楚我原來的工作原理。該函數提示用戶輸入,然後接受該輸入並返回「真實值」,例如(2,2)。謝謝您的幫助。現在我只需要弄清楚如何檢查玩家想要插入的位置是否有效。所以它不是越界。 – Weffe