forked from cprerovsky/rest-quest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
94 lines (82 loc) · 1.65 KB
/
client.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
/*global require,console*/
'use strict';
var request = require('request');
var Player = { name : 'clembot-' + parseInt(Math.random() * 100, 10) };
var BASE_URL = 'http://localhost:3000';
function takeTurn (pos, search) {
var oldPos = pos;
var dir = search ? nextSearchStep() : nextHomeStep(pos);
pos = updatePos(pos, dir);
move(dir, function (data) {
takeTurn(pos, !data.treasure);
});
}
function nextHomeStep(pos) {
if (pos.x > 0) {
return 'left';
}
return 'down';
}
function updatePos (pos, dir) {
var x = pos.x;
var y = pos.y;
if (dir === 'up') {
y++;
} else if (dir === 'right') {
x++;
} else if (dir === 'down') {
y--;
} else if (dir === 'left') {
x--;
}
return { x: x, y: y};
}
function move (dir, cb) {
request({
uri : BASE_URL + '/move/',
method : 'POST',
form : {
player : Player.name,
direction : dir
}
}, function (error, res, body) {
var data = JSON.parse(body);
printView(data.view);
if (data.game) {
console.log(Player.name, data);
reset();
} else {
cb(data);
}
});
}
function nextSearchStep () {
return 'up';
//return Math.random() >= 0.5 ? 'right' : 'up';
}
function reset () {
request({
uri : BASE_URL + '/reset/',
method : 'GET',
}, function () {});
}
function printView (data) {
if (!data || !data.length) return;
for (var y=0; y<data.length; y++) {
var logstr = '';
for (var x=0; x<data.length; x++) {
logstr += data[y][x].castle ? 'C ' : data[y][x].type[0] + ' ';
}
console.log(logstr);
}
console.log('\n');
}
request({
uri : BASE_URL + '/register/',
method : 'POST',
form : {
name : Player.name
}
}, function () {
takeTurn({ x:0, y:0 }, true);
});