summaryrefslogtreecommitdiff
path: root/tour_worker.js
blob: 25163758fb350c057ac4785e176eb9cda10778d0 (plain)
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
#!/usr/bin/env node

if (process.argv.length != 4) {
	console.log("Usage: ./tour_worker.js <num_turns> <logs_dir>");
	console.log("Runs a game with each of the seeds given on stdin with the specified number of turns.");
	console.log("Game logs will be written to hopefully uniquely named files in the pre-existing directory <logs_dir>.");
	console.log("Writes results to stdout, in the format 'seed result', where <result> is the game result.");
	console.log("Quits on EOF on stdin.");
	process.exit(1);
}

const fs = require("fs");
const child_process = require("child_process");

const num_turns = +process.argv[2];
const logs_dir = process.argv[3];

let buffer = "";
process.stdin.on("data", function(data) {
	buffer += data;
	let idx = buffer.indexOf("\n");
	while (idx != -1) {
		const line = buffer.slice(0, idx);
		buffer = buffer.slice(idx + 1);
		idx = buffer.indexOf("\n");

		handle_line(line);
	}
});

function handle_line(seed) {
	const logfile = logs_dir + "/" + seed + "-" + new Date().getTime() + ".txt";
	const file = fs.openSync(logfile, "w");

	const proc = child_process.spawn(
		"node",
		["run_game.js", seed, num_turns + ""],
		{stdio: ["inherit", file, "inherit"]}
	);
	fs.closeSync(file);

	proc.on("exit", function(code, signal) {
		if (code !== 0) {
			console.log(seed + " crash");
		} else {
			let result = fs.readFileSync(logfile).toString().trim().split("\n");
			result = result[result.length - 1];

			console.log(seed + " " + result);
		}
	});
}