This commit is contained in:
syuilo 2018-03-08 17:57:57 +09:00
parent ac98858ae6
commit 8fad927a69
12 changed files with 956 additions and 457 deletions

View File

@ -7,12 +7,15 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
if (myErr) return rej('invalid my param'); if (myErr) return rej('invalid my param');
const q = my ? { const q = my ? {
is_started: true,
$or: [{ $or: [{
black_user_id: user._id user1_id: user._id
}, { }, {
white_user_id: user._id user2_id: user._id
}] }]
} : {}; } : {
is_started: true
};
// Fetch games // Fetch games
const games = await Game.find(q, { const games = await Game.find(q, {

View File

@ -3,6 +3,7 @@ import Matching, { pack as packMatching } from '../../models/othello-matching';
import Game, { pack as packGame } from '../../models/othello-game'; import Game, { pack as packGame } from '../../models/othello-game';
import User from '../../models/user'; import User from '../../models/user';
import { publishOthelloStream } from '../../event'; import { publishOthelloStream } from '../../event';
import { eighteight } from '../../../common/othello/maps';
module.exports = (params, user) => new Promise(async (res, rej) => { module.exports = (params, user) => new Promise(async (res, rej) => {
// Get 'user_id' parameter // Get 'user_id' parameter
@ -26,16 +27,21 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
_id: exist._id _id: exist._id
}); });
const parentIsBlack = Math.random() > 0.5; // Create game
// Start game
const game = await Game.insert({ const game = await Game.insert({
created_at: new Date(), created_at: new Date(),
black_user_id: parentIsBlack ? exist.parent_id : user._id, user1_id: exist.parent_id,
white_user_id: parentIsBlack ? user._id : exist.parent_id, user2_id: user._id,
turn_user_id: parentIsBlack ? exist.parent_id : user._id, user1_accepted: false,
user2_accepted: false,
is_started: false,
is_ended: false, is_ended: false,
logs: [] logs: [],
settings: {
map: eighteight,
bw: 'random',
is_llotheo: false
}
}); });
// Reponse // Reponse

View File

@ -2,6 +2,7 @@ import * as mongo from 'mongodb';
import deepcopy = require('deepcopy'); import deepcopy = require('deepcopy');
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import { IUser, pack as packUser } from './user'; import { IUser, pack as packUser } from './user';
import { Map } from '../../common/othello/maps';
const Game = db.get<IGame>('othello_games'); const Game = db.get<IGame>('othello_games');
export default Game; export default Game;
@ -9,12 +10,28 @@ export default Game;
export interface IGame { export interface IGame {
_id: mongo.ObjectID; _id: mongo.ObjectID;
created_at: Date; created_at: Date;
black_user_id: mongo.ObjectID; started_at: Date;
white_user_id: mongo.ObjectID; user1_id: mongo.ObjectID;
turn_user_id: mongo.ObjectID; user2_id: mongo.ObjectID;
user1_accepted: boolean;
user2_accepted: boolean;
/**
* ()
* 1 ... user1
* 2 ... user2
*/
black: number;
is_started: boolean;
is_ended: boolean; is_ended: boolean;
winner_id: mongo.ObjectID; winner_id: mongo.ObjectID;
logs: any[]; logs: any[];
settings: {
map: Map;
bw: string | number;
is_llotheo: boolean;
};
} }
/** /**
@ -24,6 +41,20 @@ export const pack = (
game: any, game: any,
me?: string | mongo.ObjectID | IUser me?: string | mongo.ObjectID | IUser
) => new Promise<any>(async (resolve, reject) => { ) => new Promise<any>(async (resolve, reject) => {
let _game: any;
// Populate the game if 'game' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(game)) {
_game = await Game.findOne({
_id: game
});
} else if (typeof game === 'string') {
_game = await Game.findOne({
_id: new mongo.ObjectID(game)
});
} else {
_game = deepcopy(game);
}
// Me // Me
const meId: mongo.ObjectID = me const meId: mongo.ObjectID = me
@ -34,15 +65,13 @@ export const pack = (
: (me as IUser)._id : (me as IUser)._id
: null; : null;
const _game = deepcopy(game);
// Rename _id to id // Rename _id to id
_game.id = _game._id; _game.id = _game._id;
delete _game._id; delete _game._id;
// Populate user // Populate user
_game.black_user = await packUser(_game.black_user_id, meId); _game.user1 = await packUser(_game.user1_id, meId);
_game.white_user = await packUser(_game.white_user_id, meId); _game.user2 = await packUser(_game.user2_id, meId);
if (_game.winner_id) { if (_game.winner_id) {
_game.winner = await packUser(_game.winner_id, meId); _game.winner = await packUser(_game.winner_id, meId);
} else { } else {

View File

@ -1,8 +1,8 @@
import * as websocket from 'websocket'; import * as websocket from 'websocket';
import * as redis from 'redis'; import * as redis from 'redis';
import Game from '../models/othello-game'; import Game, { pack } from '../models/othello-game';
import { publishOthelloGameStream } from '../event'; import { publishOthelloGameStream } from '../event';
import Othello from '../../common/othello'; import Othello from '../../common/othello/core';
export default function(request: websocket.request, connection: websocket.connection, subscriber: redis.RedisClient, user: any): void { export default function(request: websocket.request, connection: websocket.connection, subscriber: redis.RedisClient, user: any): void {
const gameId = request.resourceURL.query.game; const gameId = request.resourceURL.query.game;
@ -17,6 +17,19 @@ export default function(request: websocket.request, connection: websocket.connec
const msg = JSON.parse(data.utf8Data); const msg = JSON.parse(data.utf8Data);
switch (msg.type) { switch (msg.type) {
case 'accept':
accept(true);
break;
case 'cancel-accept':
accept(false);
break;
case 'update-settings':
if (msg.settings == null) return;
updateSettings(msg.settings);
break;
case 'set': case 'set':
if (msg.pos == null) return; if (msg.pos == null) return;
set(msg.pos); set(msg.pos);
@ -24,38 +37,118 @@ export default function(request: websocket.request, connection: websocket.connec
} }
}); });
async function updateSettings(settings) {
const game = await Game.findOne({ _id: gameId });
if (game.is_started) return;
if (!game.user1_id.equals(user._id) && !game.user2_id.equals(user._id)) return;
if (game.user1_id.equals(user._id) && game.user1_accepted) return;
if (game.user2_id.equals(user._id) && game.user2_accepted) return;
await Game.update({ _id: gameId }, {
$set: {
settings
}
});
publishOthelloGameStream(gameId, 'update-settings', settings);
}
async function accept(accept: boolean) {
const game = await Game.findOne({ _id: gameId });
if (game.is_started) return;
let bothAccepted = false;
if (game.user1_id.equals(user._id)) {
await Game.update({ _id: gameId }, {
$set: {
user1_accepted: accept
}
});
publishOthelloGameStream(gameId, 'change-accepts', {
user1: accept,
user2: game.user2_accepted
});
if (accept && game.user2_accepted) bothAccepted = true;
} else if (game.user2_id.equals(user._id)) {
await Game.update({ _id: gameId }, {
$set: {
user2_accepted: accept
}
});
publishOthelloGameStream(gameId, 'change-accepts', {
user1: game.user1_accepted,
user2: accept
});
if (accept && game.user1_accepted) bothAccepted = true;
} else {
return;
}
if (bothAccepted) {
// 3秒後、まだacceptされていたらゲーム開始
setTimeout(async () => {
const freshGame = await Game.findOne({ _id: gameId });
if (freshGame == null || freshGame.is_started || freshGame.is_ended) return;
let bw: number;
if (freshGame.settings.bw == 'random') {
bw = Math.random() > 0.5 ? 1 : 2;
} else {
bw = freshGame.settings.bw as number;
}
await Game.update({ _id: gameId }, {
$set: {
started_at: new Date(),
is_started: true,
black: bw
}
});
publishOthelloGameStream(gameId, 'started', await pack(gameId));
}, 3000);
}
}
async function set(pos) { async function set(pos) {
const game = await Game.findOne({ _id: gameId }); const game = await Game.findOne({ _id: gameId });
if (!game.is_started) return;
if (game.is_ended) return; if (game.is_ended) return;
if (!game.black_user_id.equals(user._id) && !game.white_user_id.equals(user._id)) return; if (!game.user1_id.equals(user._id) && !game.user2_id.equals(user._id)) return;
const o = new Othello(); const o = new Othello(game.settings.map, {
isLlotheo: game.settings.is_llotheo
game.logs.forEach(log => {
o.set(log.color, log.pos);
}); });
const myColor = game.black_user_id.equals(user._id) ? 'black' : 'white'; game.logs.forEach(log => {
const opColor = myColor == 'black' ? 'white' : 'black'; o.put(log.color, log.pos);
});
if (!o.canReverse(myColor, pos)) return; const myColor =
o.set(myColor, pos); (game.user1_id.equals(user._id) && game.black == 1) || (game.user2_id.equals(user._id) && game.black == 2)
? 'black'
: 'white';
let turn; if (!o.canPut(myColor, pos)) return;
if (o.getPattern(opColor).length > 0) { o.put(myColor, pos);
turn = myColor == 'black' ? game.white_user_id : game.black_user_id;
} else if (o.getPattern(myColor).length > 0) {
turn = myColor == 'black' ? game.black_user_id : game.white_user_id;
} else {
turn = null;
}
const isEnded = turn === null;
let winner; let winner;
if (isEnded) { if (o.isEnded) {
winner = o.blackCount == o.whiteCount ? null : o.blackCount > o.whiteCount ? game.black_user_id : game.white_user_id; if (o.winner == 'black') {
winner = game.black == 1 ? game.user1_id : game.user2_id;
} else if (o.winner == 'white') {
winner = game.black == 1 ? game.user2_id : game.user1_id;
} else {
winner = null;
}
} }
const log = { const log = {
@ -68,8 +161,7 @@ export default function(request: websocket.request, connection: websocket.connec
_id: gameId _id: gameId
}, { }, {
$set: { $set: {
turn_user_id: turn, is_ended: o.isEnded,
is_ended: isEnded,
winner_id: winner winner_id: winner
}, },
$push: { $push: {

View File

@ -1,325 +0,0 @@
const BOARD_SIZE = 8;
export default class Othello {
public board: Array<'black' | 'white'>;
public stats: Array<{
b: number;
w: number;
}> = [];
/**
*
*/
constructor() {
this.board = [
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, 'white', 'black', null, null, null,
null, null, null, 'black', 'white', null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null
];
this.stats.push({
b: 0.5,
w: 0.5
});
}
public prevPos = -1;
public get blackCount() {
return this.board.filter(s => s == 'black').length;
}
public get whiteCount() {
return this.board.filter(s => s == 'white').length;
}
public get blackP() {
return this.blackCount / (this.blackCount + this.whiteCount);
}
public get whiteP() {
return this.whiteCount / (this.blackCount + this.whiteCount);
}
public setByNumber(color, n) {
const ps = this.getPattern(color);
this.set2(color, ps[n][0], ps[n][1]);
}
private write(color, x, y) {
const pos = x + (y * 8);
this.board[pos] = color;
}
/**
*
*/
public set2(color, x, y) {
this.prevPos = x + (y * 8);
this.write(color, x, y);
const reverses = this.getReverse(color, x, y);
reverses.forEach(r => {
switch (r[0]) {
case 0: // 上
for (let c = 0, _y = y - 1; c < r[1]; c++, _y--) {
this.write(color, x, _y);
}
break;
case 1: // 右上
for (let c = 0, i = 1; c < r[1]; c++, i++) {
this.write(color, x + i, y - i);
}
break;
case 2: // 右
for (let c = 0, _x = x + 1; c < r[1]; c++, _x++) {
this.write(color, _x, y);
}
break;
case 3: // 右下
for (let c = 0, i = 1; c < r[1]; c++, i++) {
this.write(color, x + i, y + i);
}
break;
case 4: // 下
for (let c = 0, _y = y + 1; c < r[1]; c++, _y++) {
this.write(color, x, _y);
}
break;
case 5: // 左下
for (let c = 0, i = 1; c < r[1]; c++, i++) {
this.write(color, x - i, y + i);
}
break;
case 6: // 左
for (let c = 0, _x = x - 1; c < r[1]; c++, _x--) {
this.write(color, _x, y);
}
break;
case 7: // 左上
for (let c = 0, i = 1; c < r[1]; c++, i++) {
this.write(color, x - i, y - i);
}
break;
}
});
this.stats.push({
b: this.blackP,
w: this.whiteP
});
}
public set(color, pos) {
const x = pos % BOARD_SIZE;
const y = Math.floor(pos / BOARD_SIZE);
this.set2(color, x, y);
}
public get(x, y) {
const pos = x + (y * 8);
return this.board[pos];
}
/**
*
*/
public getPattern(myColor): number[][] {
const result = [];
this.board.forEach((stone, i) => {
if (stone != null) return;
const x = i % BOARD_SIZE;
const y = Math.floor(i / BOARD_SIZE);
if (this.canReverse2(myColor, x, y)) result.push([x, y]);
});
return result;
}
/**
* (1)
*/
public canReverse2(myColor, x, y): boolean {
return this.canReverse(myColor, x + (y * 8));
}
public canReverse(myColor, pos): boolean {
if (this.board[pos] != null) return false;
const x = pos % BOARD_SIZE;
const y = Math.floor(pos / BOARD_SIZE);
return this.getReverse(myColor, x, y) !== null;
}
private getReverse(myColor, targetx, targety): number[] {
const opponentColor = myColor == 'black' ? 'white' : 'black';
const createIterater = () => {
let opponentStoneFound = false;
let breaked = false;
return (x, y): any => {
if (breaked) {
return;
} else if (this.get(x, y) == myColor && opponentStoneFound) {
return true;
} else if (this.get(x, y) == myColor && !opponentStoneFound) {
breaked = true;
} else if (this.get(x, y) == opponentColor) {
opponentStoneFound = true;
} else {
breaked = true;
}
};
};
const res = [];
let iterate;
// 上
iterate = createIterater();
for (let c = 0, y = targety - 1; y >= 0; c++, y--) {
if (iterate(targetx, y)) {
res.push([0, c]);
break;
}
}
// 右上
iterate = createIterater();
for (let c = 0, i = 1; i <= Math.min(BOARD_SIZE - targetx, targety); c++, i++) {
if (iterate(targetx + i, targety - i)) {
res.push([1, c]);
break;
}
}
// 右
iterate = createIterater();
for (let c = 0, x = targetx + 1; x < BOARD_SIZE; c++, x++) {
if (iterate(x, targety)) {
res.push([2, c]);
break;
}
}
// 右下
iterate = createIterater();
for (let c = 0, i = 1; i < Math.min(BOARD_SIZE - targetx, BOARD_SIZE - targety); c++, i++) {
if (iterate(targetx + i, targety + i)) {
res.push([3, c]);
break;
}
}
// 下
iterate = createIterater();
for (let c = 0, y = targety + 1; y < BOARD_SIZE; c++, y++) {
if (iterate(targetx, y)) {
res.push([4, c]);
break;
}
}
// 左下
iterate = createIterater();
for (let c = 0, i = 1; i <= Math.min(targetx, BOARD_SIZE - targety); c++, i++) {
if (iterate(targetx - i, targety + i)) {
res.push([5, c]);
break;
}
}
// 左
iterate = createIterater();
for (let c = 0, x = targetx - 1; x >= 0; c++, x--) {
if (iterate(x, targety)) {
res.push([6, c]);
break;
}
}
// 左上
iterate = createIterater();
for (let c = 0, i = 1; i <= Math.min(targetx, targety); c++, i++) {
if (iterate(targetx - i, targety - i)) {
res.push([7, c]);
break;
}
}
return res.length === 0 ? null : res;
}
public toString(): string {
//return this.board.map(row => row.map(state => state === 'black' ? '●' : state === 'white' ? '○' : '┼').join('')).join('\n');
//return this.board.map(row => row.map(state => state === 'black' ? '⚫️' : state === 'white' ? '⚪️' : '🔹').join('')).join('\n');
return 'wip';
}
public toPatternString(color): string {
//const num = ['', '', '', '', '', '', '', '', '', ''];
/*const num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '🔟', '🍏', '🍎', '🍐', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🍈', '🍒', '🍑', '🍍'];
const pattern = this.getPattern(color);
return this.board.map((row, y) => row.map((state, x) => {
const i = pattern.findIndex(p => p[0] == x && p[1] == y);
//return state === 'black' ? '●' : state === 'white' ? '○' : i != -1 ? num[i] : '┼';
return state === 'black' ? '⚫️' : state === 'white' ? '⚪️' : i != -1 ? num[i] : '🔹';
}).join('')).join('\n');*/
return 'wip';
}
}
export function ai(color: string, othello: Othello) {
const opponentColor = color == 'black' ? 'white' : 'black';
function think() {
// 打てる場所を取得
const ps = othello.getPattern(color);
if (ps.length > 0) { // 打てる場所がある場合
// 角を取得
const corners = ps.filter(p =>
// 左上
(p[0] == 0 && p[1] == 0) ||
// 右上
(p[0] == (BOARD_SIZE - 1) && p[1] == 0) ||
// 右下
(p[0] == (BOARD_SIZE - 1) && p[1] == (BOARD_SIZE - 1)) ||
// 左下
(p[0] == 0 && p[1] == (BOARD_SIZE - 1))
);
if (corners.length > 0) { // どこかしらの角に打てる場合
// 打てる角からランダムに選択して打つ
const p = corners[Math.floor(Math.random() * corners.length)];
othello.set(color, p[0], p[1]);
} else { // 打てる角がない場合
// 打てる場所からランダムに選択して打つ
const p = ps[Math.floor(Math.random() * ps.length)];
othello.set(color, p[0], p[1]);
}
// 相手の打つ場所がない場合続けてAIのターン
if (othello.getPattern(opponentColor).length === 0) {
think();
}
}
}
think();
}

42
src/common/othello/ai.ts Normal file
View File

@ -0,0 +1,42 @@
import Othello, { Color } from './core';
export function ai(color: Color, othello: Othello) {
//const opponentColor = color == 'black' ? 'white' : 'black';
/* wip
function think() {
// 打てる場所を取得
const ps = othello.canPutSomewhere(color);
if (ps.length > 0) { // 打てる場所がある場合
// 角を取得
const corners = ps.filter(p =>
// 左上
(p[0] == 0 && p[1] == 0) ||
// 右上
(p[0] == (BOARD_SIZE - 1) && p[1] == 0) ||
// 右下
(p[0] == (BOARD_SIZE - 1) && p[1] == (BOARD_SIZE - 1)) ||
// 左下
(p[0] == 0 && p[1] == (BOARD_SIZE - 1))
);
if (corners.length > 0) { // どこかしらの角に打てる場合
// 打てる角からランダムに選択して打つ
const p = corners[Math.floor(Math.random() * corners.length)];
othello.set(color, p[0], p[1]);
} else { // 打てる角がない場合
// 打てる場所からランダムに選択して打つ
const p = ps[Math.floor(Math.random() * ps.length)];
othello.set(color, p[0], p[1]);
}
// 相手の打つ場所がない場合続けてAIのターン
if (othello.getPattern(opponentColor).length === 0) {
think();
}
}
}
think();*/
}

239
src/common/othello/core.ts Normal file
View File

@ -0,0 +1,239 @@
import { Map } from './maps';
export type Color = 'black' | 'white';
export type MapPixel = 'null' | 'empty';
export type Options = {
isLlotheo: boolean;
};
/**
*
*/
export default class Othello {
public map: Map;
public mapData: MapPixel[];
public board: Color[];
public turn: Color = 'black';
public opts: Options;
public stats: Array<{
b: number;
w: number;
}>;
/**
*
*/
constructor(map: Map, opts: Options) {
this.map = map;
this.opts = opts;
// Parse map data
this.board = this.map.data.split('').map(d => {
if (d == '-') return null;
if (d == 'b') return 'black';
if (d == 'w') return 'white';
return undefined;
});
this.mapData = this.map.data.split('').map(d => {
if (d == '-' || d == 'b' || d == 'w') return 'empty';
return 'null';
});
// Init stats
this.stats = [{
b: this.blackP,
w: this.whiteP
}];
}
public prevPos = -1;
/**
*
*/
public get blackCount() {
return this.board.filter(x => x == 'black').length;
}
/**
*
*/
public get whiteCount() {
return this.board.filter(x => x == 'white').length;
}
/**
*
*/
public get blackP() {
return this.blackCount / (this.blackCount + this.whiteCount);
}
/**
*
*/
public get whiteP() {
return this.whiteCount / (this.blackCount + this.whiteCount);
}
public transformPosToXy(pos: number): number[] {
const x = pos % this.map.size;
const y = Math.floor(pos / this.map.size);
return [x, y];
}
public transformXyToPos(x: number, y: number): number {
return x + (y * this.map.size);
}
/**
*
* @param color
* @param pos
*/
private write(color: Color, pos: number) {
this.board[pos] = color;
}
/**
*
* @param color
* @param pos
*/
public put(color: Color, pos: number) {
if (!this.canPut(color, pos)) return;
this.prevPos = pos;
this.write(color, pos);
// 反転させられる石を取得
const reverses = this.effects(color, pos);
// 反転させる
reverses.forEach(pos => {
this.write(color, pos);
});
this.stats.push({
b: this.blackP,
w: this.whiteP
});
// ターン計算
const opColor = color == 'black' ? 'white' : 'black';
if (this.canPutSomewhere(opColor).length > 0) {
this.turn = color == 'black' ? 'white' : 'black';
} else if (this.canPutSomewhere(color).length > 0) {
this.turn = color == 'black' ? 'black' : 'white';
} else {
this.turn = null;
}
}
/**
*
* @param pos
*/
public get(pos: number) {
return this.board[pos];
}
/**
*
* @param pos
*/
public mapDataGet(pos: number): MapPixel {
if (pos < 0 || pos >= this.mapData.length) return 'null';
return this.mapData[pos];
}
/**
*
*/
public canPutSomewhere(color: Color): number[] {
const result = [];
this.board.forEach((x, i) => {
if (this.canPut(color, i)) result.push(i);
});
return result;
}
/**
* (1)
* @param color
* @param pos
*/
public canPut(color: Color, pos: number): boolean {
// 既に石が置いてある場所には打てない
if (this.get(pos) !== null) return false;
return this.effects(color, pos).length !== 0;
}
/**
*
* @param color
* @param pos
*/
private effects(color: Color, pos: number): number[] {
const enemyColor = color == 'black' ? 'white' : 'black';
const [x, y] = this.transformPosToXy(pos);
let stones = [];
const iterate = (fn: (i: number) => number[]) => {
let i = 1;
const found = [];
while (true) {
const [x, y] = fn(i);
if (x < 0 || y < 0 || x >= this.map.size || y >= this.map.size) break;
const pos = this.transformXyToPos(x, y);
const pixel = this.mapDataGet(pos);
if (pixel == 'null') break;
const stone = this.get(pos);
if (stone == null) break;
if (stone == enemyColor) found.push(pos);
if (stone == color) {
stones = stones.concat(found);
break;
}
i++;
}
};
iterate(i => [x , y - i]); // 上
iterate(i => [x + i, y - i]); // 右上
iterate(i => [x + i, y ]); // 右
iterate(i => [x + i, y + i]); // 右下
iterate(i => [x , y + i]); // 下
iterate(i => [x - i, y + i]); // 左下
iterate(i => [x - i, y ]); // 左
iterate(i => [x - i, y - i]); // 左上
return stones;
}
/**
*
*/
public get isEnded(): boolean {
return this.turn === null;
}
/**
* (null = )
*/
public get winner(): Color {
if (!this.isEnded) return undefined;
if (this.blackCount == this.whiteCount) return null;
if (this.opts.isLlotheo) {
return this.blackCount > this.whiteCount ? 'white' : 'black';
} else {
return this.blackCount > this.whiteCount ? 'black' : 'white';
}
}
}

217
src/common/othello/maps.ts Normal file
View File

@ -0,0 +1,217 @@
/**
*
*
* :
* () ...
* - ...
* b ...
* w ...
*/
export type Map = {
name?: string;
size: number;
data: string;
};
export const fourfour: Map = {
name: '4x4',
size: 4,
data:
'----' +
'-wb-' +
'-bw-' +
'----'
};
export const sixsix: Map = {
name: '6x6',
size: 6,
data:
'------' +
'------' +
'--wb--' +
'--bw--' +
'------' +
'------'
};
export const eighteight: Map = {
name: '8x8',
size: 8,
data:
'--------' +
'--------' +
'--------' +
'---wb---' +
'---bw---' +
'--------' +
'--------' +
'--------'
};
export const roundedEighteight: Map = {
name: '8x8 rounded',
size: 8,
data:
' ------ ' +
'--------' +
'--------' +
'---wb---' +
'---bw---' +
'--------' +
'--------' +
' ------ '
};
export const roundedEighteight2: Map = {
name: '8x8 rounded 2',
size: 8,
data:
' ---- ' +
' ------ ' +
'--------' +
'---wb---' +
'---bw---' +
'--------' +
' ------ ' +
' ---- '
};
export const eighteightWithNotch: Map = {
name: '8x8 with notch',
size: 8,
data:
'--- ---' +
'--------' +
'--------' +
' --wb-- ' +
' --bw-- ' +
'--------' +
'--------' +
'--- ---'
};
export const eighteightWithSomeHoles: Map = {
name: '8x8 with some holes',
size: 8,
data:
'--- ----' +
'----- --' +
'-- -----' +
'---wb---' +
'---bw- -' +
' -------' +
'--- ----' +
'--------'
};
export const sixeight: Map = {
name: '6x8',
size: 8,
data:
' ------ ' +
' ------ ' +
' ------ ' +
' --wb-- ' +
' --bw-- ' +
' ------ ' +
' ------ ' +
' ------ '
};
export const tenthtenth: Map = {
name: '10x10',
size: 10,
data:
'----------' +
'----------' +
'----------' +
'----------' +
'----wb----' +
'----bw----' +
'----------' +
'----------' +
'----------' +
'----------'
};
export const hole: Map = {
name: 'hole',
size: 10,
data:
'----------' +
'----------' +
'--wb--wb--' +
'--bw--bw--' +
'---- ----' +
'---- ----' +
'--wb--wb--' +
'--bw--bw--' +
'----------' +
'----------'
};
export const spark: Map = {
name: 'spark',
size: 10,
data:
' - - ' +
'----------' +
' -------- ' +
' -------- ' +
' ---wb--- ' +
' ---bw--- ' +
' -------- ' +
' -------- ' +
'----------' +
' - - '
};
export const islands: Map = {
name: 'islands',
size: 10,
data:
'-------- ' +
'---wb--- ' +
'---bw--- ' +
'-------- ' +
' - - ' +
' - - ' +
' --------' +
' ---bw---' +
' ---wb---' +
' --------'
};
export const grid: Map = {
name: 'grid',
size: 10,
data:
'----------' +
'- - -- - -' +
'----------' +
'- - -- - -' +
'----wb----' +
'----bw----' +
'- - -- - -' +
'----------' +
'- - -- - -' +
'----------'
};
export const iphonex: Map = {
name: 'iPhone X',
size: 10,
data:
' -- -- ' +
' -------- ' +
' -------- ' +
' -------- ' +
' ---wb--- ' +
' ---bw--- ' +
' -------- ' +
' -------- ' +
' -------- ' +
' ------ '
};

View File

@ -1,23 +1,27 @@
<template> <template>
<div class="root"> <div class="root">
<header><b>{{ game.black_user.name }}</b>() vs <b>{{ game.white_user.name }}</b>()</header> <header><b>{{ blackUser.name }}</b>() vs <b>{{ whiteUser.name }}</b>()</header>
<p class="turn" v-if="!iAmPlayer && !isEnded">{{ turn.name }}のターンです<mk-ellipsis/></p>
<p class="turn" v-if="logPos != logs.length">{{ turn.name }}のターン</p> <p class="turn" v-if="!iAmPlayer && !game.is_ended">{{ turnUser.name }}のターンです<mk-ellipsis/></p>
<p class="turn" v-if="iAmPlayer && !isEnded">{{ isMyTurn ? 'あなたのターンです' : '相手のターンです' }}<mk-ellipsis v-if="!isMyTurn"/></p> <p class="turn" v-if="logPos != logs.length">{{ turnUser.name }}のターン</p>
<p class="result" v-if="isEnded && logPos == logs.length"> <p class="turn" v-if="iAmPlayer && !game.is_ended">{{ isMyTurn ? 'あなたのターンです' : '相手のターンです' }}<mk-ellipsis v-if="!isMyTurn"/></p>
<template v-if="winner"><b>{{ winner.name }}</b>の勝ち</template> <p class="result" v-if="game.is_ended && logPos == logs.length">
<template v-if="game.winner"><b>{{ game.winner.name }}</b>の勝ち{{ game.settings.is_llotheo ? ' (ロセオ)' : '' }}</template>
<template v-else>引き分け</template> <template v-else>引き分け</template>
</p> </p>
<div class="board">
<div class="board" :style="{ 'grid-template-rows': `repeat(${ game.settings.map.size }, 1fr)`, 'grid-template-columns': `repeat(${ game.settings.map.size }, 1fr)` }">
<div v-for="(stone, i) in o.board" <div v-for="(stone, i) in o.board"
:class="{ empty: stone == null, myTurn: isMyTurn, can: o.canReverse(turn.id == game.black_user.id ? 'black' : 'white', i), prev: o.prevPos == i }" :class="{ empty: stone == null, none: o.map.data[i] == ' ', myTurn: isMyTurn, can: turnUser ? o.canPut(turnUser.id == blackUser.id ? 'black' : 'white', i) : null, prev: o.prevPos == i }"
@click="set(i)" @click="set(i)"
> >
<img v-if="stone == 'black'" :src="`${game.black_user.avatar_url}?thumbnail&size=64`" alt=""> <img v-if="stone == 'black'" :src="`${blackUser.avatar_url}?thumbnail&size=128`" alt="">
<img v-if="stone == 'white'" :src="`${game.white_user.avatar_url}?thumbnail&size=64`" alt=""> <img v-if="stone == 'white'" :src="`${whiteUser.avatar_url}?thumbnail&size=128`" alt="">
</div> </div>
</div> </div>
<p>:{{ o.blackCount }} :{{ o.whiteCount }} 合計:{{ o.blackCount + o.whiteCount }}</p> <p>:{{ o.blackCount }} :{{ o.whiteCount }} 合計:{{ o.blackCount + o.whiteCount }}</p>
<div class="graph"> <div class="graph">
<div v-for="n in 61 - o.stats.length"> <div v-for="n in 61 - o.stats.length">
</div> </div>
@ -26,7 +30,8 @@
<div :style="{ height: `${ Math.floor(data.w * 100) }%` }"></div> <div :style="{ height: `${ Math.floor(data.w * 100) }%` }"></div>
</div> </div>
</div> </div>
<div class="player" v-if="isEnded">
<div class="player" v-if="game.is_ended">
<el-button type="primary" @click="logPos = 0" :disabled="logPos == 0">%fa:fast-backward%</el-button> <el-button type="primary" @click="logPos = 0" :disabled="logPos == 0">%fa:fast-backward%</el-button>
<el-button type="primary" @click="logPos--" :disabled="logPos == 0">%fa:backward%</el-button> <el-button type="primary" @click="logPos--" :disabled="logPos == 0">%fa:backward%</el-button>
<span>{{ logPos }} / {{ logs.length }}</span> <span>{{ logPos }} / {{ logs.length }}</span>
@ -38,58 +43,63 @@
<script lang="ts"> <script lang="ts">
import Vue from 'vue'; import Vue from 'vue';
import { OthelloGameStream } from '../../scripts/streaming/othello-game'; import Othello, { Color } from '../../../../../common/othello/core';
import Othello from '../../../../../common/othello';
export default Vue.extend({ export default Vue.extend({
props: ['game'], props: ['game', 'connection'],
data() { data() {
return { return {
o: new Othello(), o: null as Othello,
logs: [], logs: [],
logPos: 0, logPos: 0
turn: null,
isMyTurn: null,
isEnded: false,
winner: null,
connection: null
}; };
}, },
computed: { computed: {
iAmPlayer(): boolean { iAmPlayer(): boolean {
return this.game.black_user_id == (this as any).os.i.id || this.game.white_user_id == (this as any).os.i.id; return this.game.user1_id == (this as any).os.i.id || this.game.user2_id == (this as any).os.i.id;
}, },
myColor(): string { myColor(): Color {
return this.game.black_user_id == (this as any).os.i.id ? 'black' : 'white'; if (!this.iAmPlayer) return null;
if (this.game.user1_id == (this as any).os.i.id && this.game.black == 1) return 'black';
if (this.game.user2_id == (this as any).os.i.id && this.game.black == 2) return 'black';
return 'white';
}, },
opColor(): string { opColor(): Color {
if (!this.iAmPlayer) return null;
return this.myColor == 'black' ? 'white' : 'black'; return this.myColor == 'black' ? 'white' : 'black';
},
blackUser(): any {
return this.game.black == 1 ? this.game.user1 : this.game.user2;
},
whiteUser(): any {
return this.game.black == 1 ? this.game.user2 : this.game.user1;
},
turnUser(): any {
if (this.o.turn == 'black') {
return this.game.black == 1 ? this.game.user1 : this.game.user2;
} else if (this.o.turn == 'white') {
return this.game.black == 1 ? this.game.user2 : this.game.user1;
} else {
return null;
}
},
isMyTurn(): boolean {
if (this.turnUser == null) return null;
return this.turnUser.id == (this as any).os.i.id;
} }
}, },
watch: { watch: {
logPos(v) { logPos(v) {
if (!this.isEnded) return; if (!this.game.is_ended) return;
this.o = new Othello(); this.o = new Othello(this.game.settings.map, {
this.turn = this.game.black_user; isLlotheo: this.game.settings.is_llotheo
});
this.logs.forEach((log, i) => { this.logs.forEach((log, i) => {
if (i < v) { if (i < v) {
this.o.set(log.color, log.pos); this.o.put(log.color, log.pos);
if (log.color == 'black' && this.o.getPattern('white').length > 0) {
this.turn = this.game.white_user;
}
if (log.color == 'black' && this.o.getPattern('white').length == 0) {
this.turn = this.game.black_user;
}
if (log.color == 'white' && this.o.getPattern('black').length > 0) {
this.turn = this.game.black_user;
}
if (log.color == 'white' && this.o.getPattern('black').length == 0) {
this.turn = this.game.white_user;
}
} }
}); });
this.$forceUpdate(); this.$forceUpdate();
@ -97,74 +107,65 @@ export default Vue.extend({
}, },
created() { created() {
this.o = new Othello(this.game.settings.map, {
isLlotheo: this.game.settings.is_llotheo
});
this.game.logs.forEach(log => { this.game.logs.forEach(log => {
this.o.set(log.color, log.pos); this.o.put(log.color, log.pos);
}); });
this.logs = this.game.logs; this.logs = this.game.logs;
this.logPos = this.logs.length; this.logPos = this.logs.length;
this.turn = this.game.turn_user_id == this.game.black_user_id ? this.game.black_user : this.game.white_user;
this.isMyTurn = this.game.turn_user_id == (this as any).os.i.id;
this.isEnded = this.game.is_ended;
this.winner = this.game.winner;
}, },
mounted() { mounted() {
this.connection = new OthelloGameStream((this as any).os.i, this.game);
this.connection.on('set', this.onSet); this.connection.on('set', this.onSet);
}, },
beforeDestroy() { beforeDestroy() {
this.connection.off('set', this.onSet); this.connection.off('set', this.onSet);
this.connection.close();
}, },
methods: { methods: {
set(pos) { set(pos) {
if (!this.isMyTurn) return; if (!this.isMyTurn) return;
if (!this.o.canReverse(this.myColor, pos)) return; if (!this.o.canPut(this.myColor, pos)) return;
this.o.set(this.myColor, pos);
if (this.o.getPattern(this.opColor).length > 0) { this.o.put(this.myColor, pos);
this.isMyTurn = !this.isMyTurn;
this.turn = this.myColor == 'black' ? this.game.white_user : this.game.black_user;
} else if (this.o.getPattern(this.myColor).length == 0) {
this.isEnded = true;
this.winner = this.o.blackCount == this.o.whiteCount ? null : this.o.blackCount > this.o.whiteCount ? this.game.black_user : this.game.white_user;
}
this.connection.send({ this.connection.send({
type: 'set', type: 'set',
pos pos
}); });
this.checkEnd();
this.$forceUpdate(); this.$forceUpdate();
}, },
onSet(x) { onSet(x) {
this.logs.push(x); this.logs.push(x);
this.logPos++; this.logPos++;
this.o.set(x.color, x.pos); this.o.put(x.color, x.pos);
this.checkEnd();
this.$forceUpdate();
},
if (this.o.getPattern('black').length == 0 && this.o.getPattern('white').length == 0) { checkEnd() {
this.isEnded = true; this.game.is_ended = this.o.isEnded;
this.winner = this.o.blackCount == this.o.whiteCount ? null : this.o.blackCount > this.o.whiteCount ? this.game.black_user : this.game.white_user; if (this.game.is_ended) {
} else { if (this.o.winner == 'black') {
if (this.iAmPlayer && this.o.getPattern(this.myColor).length > 0) { this.game.winner_id = this.game.black == 1 ? this.game.user1_id : this.game.user2_id;
this.isMyTurn = true; this.game.winner = this.game.black == 1 ? this.game.user1 : this.game.user2;
} } else if (this.o.winner == 'white') {
this.game.winner_id = this.game.black == 1 ? this.game.user2_id : this.game.user1_id;
if (x.color == 'black' && this.o.getPattern('white').length > 0) { this.game.winner = this.game.black == 1 ? this.game.user2 : this.game.user1;
this.turn = this.game.white_user; } else {
} this.game.winner_id = null;
if (x.color == 'black' && this.o.getPattern('white').length == 0) { this.game.winner = null;
this.turn = this.game.black_user;
}
if (x.color == 'white' && this.o.getPattern('black').length > 0) {
this.turn = this.game.black_user;
}
if (x.color == 'white' && this.o.getPattern('black').length == 0) {
this.turn = this.game.white_user;
} }
} }
this.$forceUpdate();
} }
} }
}); });
@ -182,8 +183,6 @@ export default Vue.extend({
> .board > .board
display grid display grid
grid-template-rows repeat(8, 1fr)
grid-template-columns repeat(8, 1fr)
grid-gap 4px grid-gap 4px
width 300px width 300px
height 300px height 300px
@ -221,6 +220,9 @@ export default Vue.extend({
&.prev &.prev
box-shadow 0 0 0 4px rgba($theme-color, 0.7) box-shadow 0 0 0 4px rgba($theme-color, 0.7)
&.none
border-color transparent !important
> img > img
display block display block
width 100% width 100%

View File

@ -0,0 +1,42 @@
<template>
<div>
<x-room v-if="!g.is_started" :game="g" :connection="connection"/>
<x-game v-else :game="g" :connection="connection"/>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import XGame from './othello.game.vue';
import XRoom from './othello.room.vue';
import { OthelloGameStream } from '../../scripts/streaming/othello-game';
export default Vue.extend({
components: {
XGame,
XRoom
},
props: ['game'],
data() {
return {
connection: null,
g: null
};
},
created() {
this.g = this.game;
this.connection = new OthelloGameStream((this as any).os.i, this.game);
this.connection.on('started', this.onStarted);
},
beforeDestroy() {
this.connection.off('started', this.onStarted);
this.connection.close();
},
methods: {
onStarted(game) {
Object.assign(this.g, game);
this.$forceUpdate();
}
}
});
</script>

View File

@ -0,0 +1,152 @@
<template>
<div class="root">
<header><b>{{ game.user1.name }}</b> vs <b>{{ game.user2.name }}</b></header>
<p>ゲームの設定</p>
<el-select v-model="mapName" placeholder="マップを選択" @change="onMapChange">
<el-option v-for="m in maps" :key="m.name" :label="m.name" :value="m.name"/>
</el-select>
<div class="board" :style="{ 'grid-template-rows': `repeat(${ game.settings.map.size }, 1fr)`, 'grid-template-columns': `repeat(${ game.settings.map.size }, 1fr)` }">
<div v-for="(x, i) in game.settings.map.data"
:class="{ none: x == ' ' }"
>
<template v-if="x == 'b'">%fa:circle%</template>
<template v-if="x == 'w'">%fa:circle R%</template>
</div>
</div>
<div class="rules">
<mk-switch v-model="game.settings.is_llotheo" @change="onIsLlotheoChange" text="石の少ない方が勝ち(ロセオ)"/>
</div>
<div class="actions">
<el-button @click="exit">キャンセル</el-button>
<el-button type="primary" @click="accept" v-if="!isAccepted">準備完了</el-button>
<el-button type="primary" @click="cancel" v-if="isAccepted">準備続行</el-button>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import * as maps from '../../../../../common/othello/maps';
export default Vue.extend({
props: ['game', 'connection'],
data() {
return {
o: null,
isLlotheo: false,
mapName: maps.eighteight.name,
maps: maps
};
},
computed: {
isAccepted(): boolean {
if (this.game.user1_id == (this as any).os.i.id && this.game.user1_accepted) return true;
if (this.game.user2_id == (this as any).os.i.id && this.game.user2_accepted) return true;
return false;
}
},
created() {
this.connection.on('change-accepts', this.onChangeAccepts);
this.connection.on('update-settings', this.onUpdateSettings);
},
beforeDestroy() {
this.connection.off('change-accepts', this.onChangeAccepts);
this.connection.off('update-settings', this.onUpdateSettings);
},
methods: {
exit() {
},
accept() {
this.connection.send({
type: 'accept'
});
},
cancel() {
this.connection.send({
type: 'cancel-accept'
});
},
onChangeAccepts(accepts) {
this.game.user1_accepted = accepts.user1;
this.game.user2_accepted = accepts.user2;
this.$forceUpdate();
},
onUpdateSettings(settings) {
this.game.settings = settings;
this.mapName = this.game.settings.map.name;
},
onMapChange(v) {
this.game.settings.map = Object.entries(maps).find(x => x[1].name == v)[1];
this.connection.send({
type: 'update-settings',
settings: this.game.settings
});
this.$forceUpdate();
},
onIsLlotheoChange(v) {
this.connection.send({
type: 'update-settings',
settings: this.game.settings
});
this.$forceUpdate();
}
}
});
</script>
<style lang="stylus" scoped>
@import '~const.styl'
.root
text-align center
> header
padding 8px
border-bottom dashed 1px #c4cdd4
> .board
display grid
grid-gap 4px
width 300px
height 300px
margin 16px auto
> div
background transparent
border solid 2px #eee
border-radius 6px
overflow hidden
*
pointer-events none
user-select none
width 100%
height 100%
&.none
border-color transparent
> .rules
max-width 300px
margin 0 auto
> .actions
margin-bottom 16px
</style>

View File

@ -1,7 +1,7 @@
<template> <template>
<div class="mk-othello"> <div class="mk-othello">
<div v-if="game"> <div v-if="game">
<x-game :game="game"/> <x-gameroom :game="game"/>
</div> </div>
<div class="matching" v-else-if="matching"> <div class="matching" v-else-if="matching">
<h1><b>{{ matching.name }}</b>を待っています<mk-ellipsis/></h1> <h1><b>{{ matching.name }}</b>を待っています<mk-ellipsis/></h1>
@ -40,18 +40,18 @@
<section v-if="myGames.length > 0"> <section v-if="myGames.length > 0">
<h2>自分の対局</h2> <h2>自分の対局</h2>
<div class="game" v-for="g in myGames" tabindex="-1" @click="game = g"> <div class="game" v-for="g in myGames" tabindex="-1" @click="game = g">
<img :src="`${g.black_user.avatar_url}?thumbnail&size=32`" alt=""> <img :src="`${g.user1.avatar_url}?thumbnail&size=32`" alt="">
<img :src="`${g.white_user.avatar_url}?thumbnail&size=32`" alt=""> <img :src="`${g.user2.avatar_url}?thumbnail&size=32`" alt="">
<span><b>{{ g.black_user.name }}</b> vs <b>{{ g.white_user.name }}</b></span> <span><b>{{ g.user1.name }}</b> vs <b>{{ g.user2.name }}</b></span>
<span class="state">{{ g.is_ended ? '終了' : '進行中' }}</span> <span class="state">{{ g.is_ended ? '終了' : '進行中' }}</span>
</div> </div>
</section> </section>
<section v-if="games.length > 0"> <section v-if="games.length > 0">
<h2>みんなの対局</h2> <h2>みんなの対局</h2>
<div class="game" v-for="g in games" tabindex="-1" @click="game = g"> <div class="game" v-for="g in games" tabindex="-1" @click="game = g">
<img :src="`${g.black_user.avatar_url}?thumbnail&size=32`" alt=""> <img :src="`${g.user1.avatar_url}?thumbnail&size=32`" alt="">
<img :src="`${g.white_user.avatar_url}?thumbnail&size=32`" alt=""> <img :src="`${g.user2.avatar_url}?thumbnail&size=32`" alt="">
<span><b>{{ g.black_user.name }}</b> vs <b>{{ g.white_user.name }}</b></span> <span><b>{{ g.user1.name }}</b> vs <b>{{ g.user2.name }}</b></span>
<span class="state">{{ g.is_ended ? '終了' : '進行中' }}</span> <span class="state">{{ g.is_ended ? '終了' : '進行中' }}</span>
</div> </div>
</section> </section>
@ -61,11 +61,11 @@
<script lang="ts"> <script lang="ts">
import Vue from 'vue'; import Vue from 'vue';
import XGame from './othello.game.vue'; import XGameroom from './othello.gameroom.vue';
export default Vue.extend({ export default Vue.extend({
components: { components: {
XGame XGameroom
}, },
data() { data() {
return { return {