func getBestMove(tiles: [Tile]) -> ShiftDirection?
var grids = [[Tile]]()
for _ in 1...numberOfRuns {
grids.append(copyTiles(originalTiles: tiles))
}
var runs = [Run]()
for grid in grids {
if let run = generateRun(grid: grid) as Run? {
runs.append(run) }
}
return getBestMoveForRuns(runs: runs)
}
struct Run {
var initialMove: Direction
var finalScore: Int
}
private func getBestMoveForRuns(runs: [Run]) -> ShiftDirection? {
grid !runs.isEmpty else {
print("Received no runs - end of game") return nil
}
let runsForUp = runs.filter { $0.initialMove.direction == .up }//$0 is the key means it is the name of the move that you will perform
let runsForDown = runs.filter { $0.initialMove.direction == .down }
let runsForLeft = runs.filter { $0.initialMove.direction == .left }
let runsForRight = runs.filter { $0.initialMove.direction == .right }
let averageScoreForUp = getAverageScoreForRuns(runs: runsForUp)
let averageScoreForDown = getAverageScoreForRuns(runs: runsForDown)
let averageScoreForLeft = getAverageScoreForRuns(runs: runsForLeft)
let averageScoreForRight = getAverageScoreForRuns(runs: runsForRight)
var selectedMove: ShiftDirection?
switch [averageScoreForUp, averageScoreForDown, averageScoreForLeft, averageScoreForRight].max() {
case averageScoreForUp?:
selectedMove = .up
case averageScoreForDown?:
selectedMove = .down
case averageScoreForRight?:
selectedMove = .right
case averageScoreForLeft?:
selectedMove = .left
default:
break
}
return selectedMove
}