ai/src/back.ts

440 lines
10 KiB
TypeScript
Raw Normal View History

2018-08-04 01:42:03 +00:00
/**
* -AI-
* Botのバックエンド()
*
*
*
*/
import * as request from 'request-promise-native';
import Reversi, { Color } from 'misskey-reversi';
const config = require('../config.json');
2018-08-05 11:55:27 +00:00
const db = {};
2018-08-04 01:42:03 +00:00
function getUserName(user) {
return user.name || user.username;
}
2018-08-05 09:48:44 +00:00
const titles = [
'さん', 'サン', 'サン', '㌠',
'ちゃん', 'チャン', 'チャン',
'君', 'くん', 'クン', 'クン',
'先生', 'せんせい', 'センセイ', 'センセイ'
];
2018-08-05 11:55:27 +00:00
class Session {
private game: any;
private form: any;
private o: Reversi;
private botColor: Color;
/**
2018-08-06 15:10:02 +00:00
* (-1.0 ~ 1.0)
2018-08-05 11:55:27 +00:00
*/
2018-08-06 15:10:02 +00:00
private cellWeights: number[];
2018-08-05 11:55:27 +00:00
/**
* 稿
*/
private startedNote: any = null;
private get user(): any {
return this.game.user1Id == config.id ? this.game.user2 : this.game.user1;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
private get userName(): string {
2018-08-06 14:26:36 +00:00
const name = getUserName(this.user);
return `?[${name}](${config.host}/@${this.user.username})${titles.some(x => name.endsWith(x)) ? '' : 'さん'}`;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
private get strength(): number {
return this.form.find(i => i.id == 'strength').value;
}
2018-08-05 11:55:27 +00:00
private get isSettai(): boolean {
return this.strength === 0;
}
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
private get allowPost(): boolean {
return this.form.find(i => i.id == 'publish').value;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
private get url(): string {
return `${config.host}/reversi/${this.game.id}`;
}
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
constructor() {
process.on('message', this.onMessage);
}
private onMessage = async (msg: any) => {
switch (msg.type) {
case '_init_': this.onInit(msg); break;
case 'update-form': this.onUpdateForn(msg); break;
case 'started': this.onStarted(msg); break;
case 'ended': this.onEnded(msg); break;
case 'set': this.onSet(msg); break;
}
2018-08-05 11:55:27 +00:00
}
2018-08-05 11:55:27 +00:00
// 親プロセスからデータをもらう
private onInit = (msg: any) => {
this.game = msg.game;
this.form = msg.form;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
/**
*
*/
private onUpdateForn = (msg: any) => {
this.form.find(i => i.id == msg.body.id).value = msg.body.value;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
/**
*
*/
private onStarted = (msg: any) => {
this.game = msg.body;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
// TLに投稿する
this.postGameStarted().then(note => {
this.startedNote = note;
});
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
// リバーシエンジン初期化
this.o = new Reversi(this.game.settings.map, {
isLlotheo: this.game.settings.isLlotheo,
canPutEverywhere: this.game.settings.canPutEverywhere,
loopedBoard: this.game.settings.loopedBoard
});
2018-08-04 01:42:03 +00:00
2018-08-06 15:10:02 +00:00
//#region 各マスの価値を計算しておく
//#region 隅
2018-08-05 11:55:27 +00:00
this.cellWeights = this.o.map.map((pix, i) => {
if (pix == 'null') return 0;
const [x, y] = this.o.transformPosToXy(i);
let count = 0;
const get = (x, y) => {
if (x < 0 || y < 0 || x >= this.o.mapWidth || y >= this.o.mapHeight) return 'null';
return this.o.mapDataGet(this.o.transformXyToPos(x, y));
};
2018-08-04 01:42:03 +00:00
2018-08-06 15:10:02 +00:00
const isNotSumi = (
// -
// +
// -
(get(x - 1, y - 1) == 'empty' && get(x + 1, y + 1) == 'empty') ||
// -
// +
// -
(get(x, y - 1) == 'empty' && get(x, y + 1) == 'empty') ||
// -
// +
// -
(get(x + 1, y - 1) == 'empty' && get(x - 1, y + 1) == 'empty') ||
//
// -+-
//
(get(x - 1, y) == 'empty' && get(x + 1, y) == 'empty')
)
const isSumi = !isNotSumi;
return isSumi ? 1 : 0;
2018-08-05 11:55:27 +00:00
});
2018-08-06 15:10:02 +00:00
//#endregion
//#region 隅の隣は危険
this.cellWeights.forEach((cell, i) => {
const [x, y] = this.o.transformPosToXy(i);
if (cell === 1) return;
if (this.o.mapDataGet(this.o.transformXyToPos(x, y)) == 'null') return;
const get = (x, y) => {
if (x < 0 || y < 0 || x >= this.o.mapWidth || y >= this.o.mapHeight) return 0;
return this.cellWeights[this.o.transformXyToPos(x, y)];
};
const isSumiNear = (
(get(x - 1, y - 1) === 1) || // 左上
(get(x , y - 1) === 1) || // 上
(get(x + 1, y - 1) === 1) || // 右上
(get(x + 1, y ) === 1) || // 右
(get(x + 1, y + 1) === 1) || // 右下
(get(x , y + 1) === 1) || // 下
(get(x - 1, y + 1) === 1) || // 左下
(get(x - 1, y ) === 1) // 左
)
if (isSumiNear) this.cellWeights[i] = -0.5;
});
//#endregion
//#endregion
2018-08-05 11:55:27 +00:00
this.botColor = this.game.user1Id == config.id && this.game.black == 1 || this.game.user2Id == config.id && this.game.black == 2;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
if (this.botColor) {
this.think();
}
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
/**
*
*/
2018-08-05 12:19:06 +00:00
private onEnded = async (msg: any) => {
2018-08-05 11:55:27 +00:00
// ストリームから切断
process.send({
type: 'close'
});
let text: string;
if (msg.body.game.surrendered) {
if (this.isSettai) {
text = `(${this.userName}を接待していたら投了されちゃいました... ごめんなさい)`;
} else {
text = `${this.userName}が投了しちゃいました`;
}
} else if (msg.body.winnerId) {
if (msg.body.winnerId == config.id) {
if (this.isSettai) {
text = `${this.userName}に接待で勝ってしまいました...`;
} else {
text = `${this.userName}に勝ちました♪`;
}
} else {
if (this.isSettai) {
text = `(${this.userName}に接待で負けてあげました...♪)`;
} else {
text = `${this.userName}に負けました...`;
}
}
} else {
if (this.isSettai) {
text = `(${this.userName}に接待で引き分けました...)`;
} else {
text = `${this.userName}と引き分けました~`;
}
}
2018-08-04 01:42:03 +00:00
2018-08-05 12:19:06 +00:00
await this.post(text, this.startedNote);
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
process.exit();
}
/**
*
*/
private onSet = (msg: any) => {
this.o.put(msg.body.color, msg.body.pos);
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
if (msg.body.next === this.botColor) {
this.think();
}
}
2018-08-04 01:42:03 +00:00
/**
* Botにとってある局面がどれだけ有利か取得する
*/
2018-08-05 11:55:27 +00:00
private staticEval = () => {
let score = this.o.canPutSomewhere(this.botColor).length;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
this.cellWeights.forEach((weight, i) => {
2018-08-04 01:42:03 +00:00
// 係数
const coefficient = 30;
weight = weight * coefficient;
2018-08-05 11:55:27 +00:00
const stone = this.o.board[i];
if (stone === this.botColor) {
2018-08-04 01:42:03 +00:00
// TODO: 価値のあるマスに設置されている自分の石に縦か横に接するマスは価値があると判断する
score += weight;
} else if (stone !== null) {
score -= weight;
}
});
// ロセオならスコアを反転
2018-08-05 11:55:27 +00:00
if (this.game.settings.isLlotheo) score = -score;
2018-08-04 01:42:03 +00:00
// 接待ならスコアを反転
2018-08-05 11:55:27 +00:00
if (this.isSettai) score = -score;
2018-08-04 01:42:03 +00:00
return score;
}
2018-08-05 11:55:27 +00:00
private think = () => {
console.log('Thinking...');
console.time('think');
// 接待モードのときは、全力(5手先読みくらい)で負けるようにする
const maxDepth = this.isSettai ? 5 : this.strength;
/**
* αβ
*/
const dive = (pos: number, alpha = -Infinity, beta = Infinity, depth = 0): number => {
// 試し打ち
this.o.put(this.o.turn, pos);
const key = this.o.board.toString();
let cache = db[key];
if (cache) {
if (alpha >= cache.upper) {
this.o.undo();
return cache.upper;
}
if (beta <= cache.lower) {
this.o.undo();
return cache.lower;
}
alpha = Math.max(alpha, cache.lower);
beta = Math.min(beta, cache.upper);
} else {
cache = {
upper: Infinity,
lower: -Infinity
};
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
const isBotTurn = this.o.turn === this.botColor;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
// 勝った
if (this.o.turn === null) {
const winner = this.o.winner;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
// 勝つことによる基本スコア
const base = 10000;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
let score;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
if (this.game.settings.isLlotheo) {
// 勝ちは勝ちでも、より自分の石を少なくした方が美しい勝ちだと判定する
score = this.o.winner ? base - (this.o.blackCount * 100) : base - (this.o.whiteCount * 100);
} else {
// 勝ちは勝ちでも、より相手の石を少なくした方が美しい勝ちだと判定する
score = this.o.winner ? base + (this.o.blackCount * 100) : base + (this.o.whiteCount * 100);
}
// 巻き戻し
this.o.undo();
// 接待なら自分が負けた方が高スコア
return this.isSettai
? winner !== this.botColor ? score : -score
: winner === this.botColor ? score : -score;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
if (depth === maxDepth) {
// 静的に評価
const score = this.staticEval();
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
// 巻き戻し
this.o.undo();
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
return score;
} else {
const cans = this.o.canPutSomewhere(this.o.turn);
let value = isBotTurn ? -Infinity : Infinity;
let a = alpha;
let b = beta;
// 次のターンのプレイヤーにとって最も良い手を取得
for (const p of cans) {
if (isBotTurn) {
const score = dive(p, a, beta, depth + 1);
value = Math.max(value, score);
a = Math.max(a, value);
if (value >= beta) break;
} else {
const score = dive(p, alpha, b, depth + 1);
value = Math.min(value, score);
b = Math.min(b, value);
if (value <= alpha) break;
}
}
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
// 巻き戻し
this.o.undo();
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
if (value <= alpha) {
cache.upper = value;
} else if (value >= beta) {
cache.lower = value;
2018-08-04 01:42:03 +00:00
} else {
2018-08-05 11:55:27 +00:00
cache.upper = value;
cache.lower = value;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
db[key] = cache;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
return value;
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
};
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
const cans = this.o.canPutSomewhere(this.botColor);
const scores = cans.map(p => dive(p));
const pos = cans[scores.indexOf(Math.max(...scores))];
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
console.log('Thinked:', pos);
console.timeEnd('think');
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
process.send({
type: 'put',
pos
});
}
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
/**
* Misskeyに投稿します
*/
private postGameStarted = async () => {
const text = this.isSettai
? `${this.userName}の接待を始めました!`
: `対局を${this.userName}と始めました! (強さ${this.strength})`;
2018-08-04 01:42:03 +00:00
2018-08-05 11:55:27 +00:00
return await this.post(`${text}\n→[観戦する](${this.url})`);
}
/**
* Misskeyに投稿します
* @param text 稿
*/
private post = async (text: string, renote?: any) => {
if (this.allowPost) {
2018-08-05 12:19:06 +00:00
const body = {
i: config.i,
text: text
} as any;
if (renote) {
body.renoteId = renote.id;
}
2018-08-05 11:55:27 +00:00
2018-08-05 12:19:06 +00:00
try {
const res = await request.post(`${config.host}/api/notes/create`, {
json: body
});
return res.createdNote;
} catch (e) {
console.error(e);
return null;
}
2018-08-05 11:55:27 +00:00
} else {
return null;
}
}
2018-08-04 01:42:03 +00:00
}
2018-08-05 11:55:27 +00:00
new Session();