-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathrun_player.js
More file actions
105 lines (93 loc) · 2.41 KB
/
run_player.js
File metadata and controls
105 lines (93 loc) · 2.41 KB
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
const readline = require('readline');
// Random player implementation
const GameLogic = require('./src/random/logic');
/**
* Random client implementation of the UTTT Game
*/
function input() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Load player's code
let player = new GameLogic(1);
rl.on('line', function (input) {
const parts = input.split(' ');
const action = parts[0];
switch (action) {
case 'init':
player.init();
break;
case 'move':
try {
const coords = player.getMove();
player.addMove(coords.board, coords.move);
writeMove(coords);
} catch(e) {
console.error('Player Error: Failed to get a move', e);
}
break;
case 'opponent':
try {
addMove(parts[1], player);
if (!player.game.isFinished()) {
const coords = player.getMove();
player.addMove(coords.board, coords.move);
writeMove(coords);
}
} catch(e) {
console.error('Player Error: Failed to get a move', e);
}
break;
case 'timeout':
player.timeout();
break;
case 'game':
{
const lastMove = parts.length > 2 ? addMove(parts[2], player) : undefined;
player.gameOver(parts[1], lastMove);
break;
}
case 'match':
{
const lastMove = parts.length > 2 ? addMove(parts[2], player) : undefined;
player.matchOver(parts[1], lastMove);
break;
}
}
});
}
function addMove(move, player) {
if (!move) return;
// the move will be in the format x,y;x,y
// where the first pair are the board's coordinates
// and the second one are the move's coordinates
const next = move.split(';');
const boardCoords = next[0].split(',').map((coord) => parseInt(coord, 10));
const moveCoords = next[1].split(',').map((coord) => parseInt(coord, 10));
player.addOpponentMove(
[
boardCoords[0],
boardCoords[1]
],
[
moveCoords[0],
moveCoords[1]
]
);
return next;
}
function writeMove(coords) {
const move = 'send:' + coords.board[0] + ',' + coords.board[1] + ';' +
coords.move[0] + ',' + coords.move[1];
write(move);
}
function player() {
input();
}
function write(output) {
if (output) {
console.log(output);
}
}
player();