This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassGameHandler.php
78 lines (61 loc) · 1.73 KB
/
classGameHandler.php
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
73
74
75
76
77
78
<?php // just loading and saving games
class GameHandler {
private $conn;
private static $winRows = array(
array(1,2,3),
array(4,5,6),
array(7,8,9),
array(1,4,7),
array(2,5,8),
array(3,6,9),
array(1,5,9),
array(3,5,7)
);
function __construct($host, $user, $pass, $database) {
$this->conn = new mysqli($host, $user, $pass, $database);
}
private function findWinner($moves) {
$winningMovesX = 0;
$winningMovesO = 0;
foreach (self::$winRows as $winRow) {
foreach ($moves as $index => $move) {
if (in_array($index, $winRow)) {
if ($move == 'x') {
$winningMovesX++;
} else if ($move == 'o') {
$winningMovesO++;
}
}
}
}
if ($winningMovesX > $winningMovesO) {
return 'x';
} elseif ($winningMovesX < $winningMovesO) {
return 'o';
}
return 'd';
}
public function saveGame($moves) {
// workout who won
$winner = $this->findWinner($moves);
// save moves and who won
$moves = implode('', $moves);
$sql = "INSERT INTO games (moves, winner) VALUES ('$moves', '$winner')";
if ($this->conn->query($sql) !== TRUE) {
throw new Exception("Error: " . $sql . ": " . $this->conn->error);
}
}
public function getScores() {
$sql = "SELECT
COUNT(IF(winner = 'x', 1, NULL)) 'x',
COUNT(IF(winner = 'o', 1, NULL)) 'o',
COUNT(IF(winner = 'd', 1, NULL)) 'd'
FROM games;";
$results = $this->conn->query($sql);
if ($results === FALSE) {
throw new Exception("Error: " . $sql . ": " . $this->conn->error);
}
$row = $results->fetch_assoc();
return $row;
}
}