2015-03-02 49 views
-1

我真的很感激你對以下事物的幫助。我一直在努力爭取這個小小的滋擾,但沒有運氣。我有這樣的代碼,基本上可以模擬AI對玩家玩TIC TAC TOE。井字棋遊戲中的代碼錯誤

let Result = RowCheck(value: 0) 
if Result != nil { 
    println("Computer has two in a row") 
    var WhereToPlayResult = WhereToPlay(Result.location, pattern: Result.pattern) 
    if !IsOccupied(WhereToPlayResult) { 
     SetImageForSpot(WhereToPlayResult, player: 0) 
     aiDeciding = false 
     CheckForWin() 
     return 
    } 
    return 
} 

RowCheck只是檢查一個模式來對抗。

func RowCheck(#‎value:Int) -> (location:String,pattern:String)? { 
    var AcceptableFinds = ["011","110","101"] 
    var FindFuncs = [CheckTop,CheckBottom,CheckLeft,CheckRight,CheckMiddleAcross,CheckMiddleDown,CheckDiagionalRightLeft,CheckDiagionalLeftRight] 
    for Algorthm in FindFuncs { 
     var AlgorthmResults = Algorthm(value:value) 
     if (find(AcceptableFinds,AlgorthmResults.pattern) != nil) { 
      return AlgorthmResults 
     } 
    } 
    return nil 
} 

但它給我一個錯誤的位置:

var WhereToPlayResult = WhereToPlay(Result.location, pattern: Result.pattern) 
+0

請參閱下面的正確答案。 Swift的「錯誤」信息往往非常煩人:-(我通常將代碼行分解爲單個代碼段,還要注意下面名字中大寫字母的註釋! – 2015-03-02 22:26:08

回答

2

因爲你RowCheck方法返回一個可選的(並可能返回nil),你需要或者解開您的選購或使用不同的分配:


let Result = RowCheck(value: 0) 
if Result != nil { 
    var WhereToPlayResult = WhereToPlay(Result!.location, pattern: Result!.pattern) 
    // ...         ^      ^
} 

if let Result = RowCheck(value: 0) { 
    // ... 
} 

備註:只有類應以大寫字母開頭。要保持Apple的代碼風格,您應該使用result,rowCheck等變量和函數。