-
Notifications
You must be signed in to change notification settings - Fork 9
/
AISolver.swift
executable file
·72 lines (47 loc) · 2.13 KB
/
AISolver.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// AISolver.swift
// ReinforcementLearning
//
// Created by Adnan Zahid on 1/2/17.
// Copyright © 2017 Adnan Zahid. All rights reserved.
//
import Foundation
protocol AIDelegate: class {
func didCalculateNextMove(box: Box)
func gameOver()
}
class AISolver {
weak var delegate: AIDelegate?
func calculateNextMove(grid: Grid) {
let box: Box = grid.selectedBox!
var maxValueBox: Box?
let neighborBoxArray: [Box] = grid.findNeighbors(box: box).shuffled()
if neighborBoxArray.count > 0 {
maxValueBox = neighborBoxArray[0]
for neighborBox in neighborBoxArray {
let maxValue: Double = (maxValueBox!.value) * 1000000
// + maxValueBox!.preferenceValue
// + calculateManhattanDistance(sourceBox: maxValueBox!, destinationBox: grid.goalBox)
// + calculateRandomNumber(sourceBox: maxValueBox!)
let neighborBoxValue: Double = (neighborBox.value) * 1000000
// + neighborBox.preferenceValue
// + calculateManhattanDistance(sourceBox: neighborBox, destinationBox: grid.goalBox)
// + calculateRandomNumber(sourceBox: neighborBox)
if maxValue < neighborBoxValue {
maxValueBox = neighborBox
}
}
}
if let nextBox: Box = maxValueBox {
delegate?.didCalculateNextMove(box: nextBox)
} else {
delegate?.gameOver()
}
}
func calculateManhattanDistance(sourceBox: Box, destinationBox: Box) -> Double {
return 1/Double((destinationBox.x - sourceBox.x) ^^ 2 + (destinationBox.y - sourceBox.y) ^^ 2)
}
func calculateRandomNumber(sourceBox: Box) -> Double {
return Double(arc4random_uniform(1000000)) * (1 - sourceBox.value)
}
}