-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (88 loc) · 2.56 KB
/
index.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var express = require("express");
var request = require("request");
var bodyparser = require("body-parser");
var app = express();
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
// const hostname = "127.0.0.1";
// const port = 3000;
const PORT = process.env.PORT || 5000;
const opponent = "o";
app.get("/", (req, res) => {
console.log("Welcome");
});
const convertTo2DArray = (board) => {
let boardArray = [];
for (let c of board) {
boardArray.push(c);
}
return boardArray;
};
const moreMoves = (board) => {
for (let c of board) if (c === " ") return true;
return false;
};
const winCombinations = (board, player) => {
if (
(board[0] == player && board[1] == player && board[2] == player) ||
(board[3] == player && board[4] == player && board[5] == player) ||
(board[6] == player && board[7] == player && board[8] == player) ||
(board[0] == player && board[3] == player && board[6] == player) ||
(board[1] == player && board[4] == player && board[7] == player) ||
(board[2] == player && board[5] == player && board[8] == player) ||
(board[0] == player && board[4] == player && board[8] == player) ||
(board[2] == player && board[4] == player && board[6] == player)
) {
return true;
} else {
return false;
}
};
const evaluationFunction = (board) => {
if (winCombinations(board, "x")) return -10;
if (winCombinations(board, "o")) return 10;
return 0;
};
const minimax = (board, player) => {
let score = evaluationFunction(board);
if (score === 10 || score === -10) {
return score;
}
if (!moreMoves(board)) return 0;
let bestScore = -100;
for (let i = 0; i < board.length; i++) {
if (board[i] === " ") {
board[i] = player;
bestScore = Math.max(bestScore, minimax(board, player));
board[i] = " ";
}
}
return bestScore;
};
const bestPosition = (board, player) => {
let best = -1000;
let bestPos = -1;
for (let i = 0; i < board.length; i++) {
if (board[i] === " ") {
board[i] = player;
let val = minimax(board, player);
board[i] = " ";
if (val > best && val >= 0) {
bestPos = i;
best = val;
}
}
}
return bestPos;
};
app.get("/play/", (req, res) => {
var board = req.query.board;
const arr = convertTo2DArray(board);
const bestScore = bestPosition(arr, opponent);
console.log("spot: " + bestScore);
arr[bestScore] = opponent;
console.log("new Board", arr);
console.log(`${arr.join("")}`);
res.send(`${arr.join("")}`);
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`));