-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
88 lines (71 loc) · 2.23 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
import * as core from "@actions/core";
import * as github from "@actions/github";
import { Game } from "./tictactoe.js";
const MOVE_COMMENT_PATTERN = /[A-C][1-3]/;
class Poster {
constructor(octokit, owner, repo, issueNumber) {
this.octokit = octokit;
this.owner = owner;
this.repo = repo;
this.issueNumber = issueNumber;
}
post(comment) {
return this.octokit.issues.createComment({
owner: this.owner,
repo: this.repo,
issue_number: this.issueNumber,
body: comment,
});
}
}
async function run() {
try {
const token = core.getInput("token");
const octokit = github.getOctokit(token);
const payload = github.context.payload;
const body = payload.comment.body;
const owner = payload.repository.owner.login;
const repo = payload.repository.name;
const issueNumber = payload.issue.number;
const poster = new Poster(octokit, owner, repo, issueNumber);
if(body.match(MOVE_COMMENT_PATTERN)) {
let response = "";
const commentsRequest = await octokit.request(
"GET /repos/{owner}/{repo}/issues/{issue_number}/comments", {
owner: owner,
repo: repo,
issue_number: issueNumber,
});
if(commentsRequest.status != 200) {
throw new Error("Could not retrieve comments");
}
const comments = commentsRequest.data;
const moves = comments.filter((c) => c.body.match(MOVE_COMMENT_PATTERN));
// reconstruct game session
const game = new Game();
try {
moves.forEach((c) => game.makeMove(c.body));
} catch(error) {
await poster.post(error.message);
throw error;
}
if(!game.isGameOver()) {
const counterMove = game.calculateBestMove();
game.makeMove(counterMove);
await poster.post(counterMove);
}
if(game.isGameOver()) {
if(game.hasWinner()) {
const winner = game.numMoves() % 2 == 0 ? "O" : "X";
await poster.post(`Game over, ${winner} won!`);
} else {
await poster.post(`Game over, draw!`);
}
}
await poster.post("```\n" + game.toString() + "\n```");
}
} catch(error) {
core.setFailed(error.message);
}
}
run();