Compare commits

..

23 commits

Author SHA1 Message Date
Sorrel
08745443ca
Create LICENSE 2021-04-14 20:31:26 -04:00
Sorrel
177d3a4c42
Merge pull request #14 from sorrelbri/dependabot/npm_and_yarn/lodash-4.17.19
Bump lodash from 4.17.15 to 4.17.19
2020-07-20 13:13:50 -04:00
dependabot[bot]
1d804694b7
Bump lodash from 4.17.15 to 4.17.19
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.19.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.19)

Signed-off-by: dependabot[bot] <support@github.com>
2020-07-20 17:07:39 +00:00
Sorrel
a40253a4fd
Merge pull request #13 from sorrelbri/dependabot/npm_and_yarn/packages/server/lodash-4.17.19
Bump lodash from 4.17.15 to 4.17.19 in /packages/server
2020-07-20 13:05:21 -04:00
Sorrel
1c470ffec0
Merge pull request #15 from sorrelbri/patch/game-service
patch Game service
2020-07-20 12:35:15 -04:00
Sorrel
27cf281670
patch Game service
Bug where player passes were submitted before `game` object was assigned within `Game.makeMove` patched
2020-07-20 12:20:47 -04:00
dependabot[bot]
0fad98a1d0
Bump lodash from 4.17.15 to 4.17.19 in /packages/server
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.19.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.19)

Signed-off-by: dependabot[bot] <support@github.com>
2020-07-19 12:20:31 +00:00
Sorrel
14a94be59e
Merge pull request #12 from sorrelbri/game_record_tree
Game add checkMove hook
2020-07-07 17:30:20 -07:00
sorrelbri
0f3e7942ef refactor Game.makeMove to check legality only if checkMove has not yet been called 2020-07-07 17:08:02 -07:00
sorrelbri
cfec49845b add checkMove hook to Game 2020-07-07 16:52:45 -07:00
Sorrel
2a84644e12
Merge pull request #11 from sorrelbri/game_record_tree
Game Service plays through and ends finished games
2020-07-01 15:06:06 -07:00
Sorrel
e1a6cd9a44
patch rewrite
original written with optional chaining, changed to `&&` operations
2020-07-01 15:01:12 -07:00
Sorrel
a3420c1152
patch to fix gameData is undefined 2020-07-01 14:56:07 -07:00
sorrelbri
c4192f2e33 add support for ending game from game record to game service 2020-07-01 14:32:03 -07:00
sorrelbri
cbf9d461ba adjust endGame query to modify record with win information 2020-07-01 11:42:16 -07:00
sorrelbri
5eca128110 add placement boolean to Move migration, add placement and prior_move selects to move query 2020-07-01 10:54:32 -07:00
Sorrel
dd0289439c
Merge pull request #9 from sorrelbri/guest_account
Guest account
2020-06-27 13:21:27 -07:00
sorrelbri
9cae5ff185 style Continue as Guest button, patch account display on NavBar 2020-06-27 13:05:38 -07:00
sorrelbri
0ec92dd5e9 add random password to guest 2020-06-26 23:33:56 -07:00
sorrelbri
ff3d6c2c24 add service to generate guest account on server 2020-06-26 23:22:17 -07:00
sorrelbri
1e6050a486 add FE service to post to auth/guest 2020-06-26 17:55:52 -07:00
sorrelbri
2f1174c21b stub guest creation on server 2020-06-26 17:35:13 -07:00
Sorrel
ccbeddfa40
Merge pull request #8 from sorrelbri/patch_game_end_bug
patch game end bug
2020-06-26 16:33:33 -07:00
21 changed files with 1193 additions and 12220 deletions

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Sorrel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

12680
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -8500,9 +8500,9 @@
}
},
"lodash": {
"version": "4.17.15",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
"integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A=="
"version": "4.17.19",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz",
"integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ=="
},
"lodash._reinterpolate": {
"version": "3.0.0",

View file

@ -51,3 +51,8 @@ table {
border-collapse: collapse;
border-spacing: 0;
}
button {
background: none;
border: none;
}

View file

@ -0,0 +1,34 @@
import React from "react";
import authServices from "../../../services/authServices";
const Guest = ({ dispatch }) => {
const handleClick = async (e) => {
e.preventDefault();
// dispatch to guest endpoint
const guestResponse = await authServices.guestService();
if (guestResponse.errors) {
const authError = guestResponse.errors[0].auth;
return dispatch({
type: "ERR",
message: "AUTH_ERROR",
body: { authError },
});
}
return dispatch({
type: "AUTH",
message: "GUEST",
body: guestResponse,
});
};
return (
<>
<button className="nav__section__button" onClick={handleClick}>
Continue As Guest
</button>
</>
);
};
export default Guest;

View file

@ -1,45 +1,49 @@
import React, { useState } from 'react';
import React, { useState } from "react";
import Login from '../Login/Login';
import Signup from '../Signup/Signup';
import Login from "../Login/Login";
import Signup from "../Signup/Signup";
import Guest from "../../Button/Guest/Guest";
const Auth = (props) => {
const [ showForm, setShowForm ] = useState('login')
const [showForm, setShowForm] = useState("login");
const { state, dispatch } = props;
return (
<>
<div
className="nav__section nav__section--auth"
onClick={()=>{setShowForm('login')}}
onClick={() => {
setShowForm("login");
}}
>
<p
className="nav__section__label"
>Login</p>
<p className="nav__section__label">Login</p>
{
showForm === 'login'
? <Login dispatch={dispatch} state={state}/>
: <></>
}
{showForm === "login" ? (
<Login dispatch={dispatch} state={state} />
) : (
<></>
)}
</div>
<div
className="nav__section nav__section--auth"
onClick={()=>{setShowForm('signup')}}
onClick={() => {
setShowForm("signup");
}}
>
<p
className="nav__section__label"
>Signup</p>
<p className="nav__section__label">Signup</p>
{
showForm === 'signup'
? <Signup dispatch={dispatch} state={state}/>
: <></>
}
{showForm === "signup" ? (
<Signup dispatch={dispatch} state={state} />
) : (
<></>
)}
</div>
<div className="nav__section nav__section--auth">
<Guest dispatch={dispatch} />
</div>
</>
);
}
};
export default Auth;

View file

@ -1,4 +1,5 @@
@import '../../../../public/stylesheets/partials/mixins';
@import '../../../../public/stylesheets/partials/variables';
div.main-wrapper {
display: flex;
@ -34,3 +35,14 @@ div.main-wrapper {
}
}
}
button {
color:map-get($colors, 'sidebar_link');
cursor: pointer;
font-family: inherit;
font-size: 110%;
font-weight: bold;
margin-bottom: .5em;
padding: 0;
text-decoration: none;
}

View file

@ -1,29 +1,36 @@
import React from 'react';
import { Link } from 'react-router-dom';
import './NavBar.scss';
import Logo from '../../../components/Display/Logo/Logo';
const NavBar = (props) => {
import React from "react";
import { Link } from "react-router-dom";
import "./NavBar.scss";
import Logo from "../../../components/Display/Logo/Logo";
const NavBar = ({ state }) => {
return (
<div className="NavBar" data-testid="NavBar">
<Link to="/home" >
<div className="NavBar__logo"><Logo /></div>
<Link to="/home">
<div className="NavBar__logo">
<Logo />
</div>
</Link>
<Link to="/home" >
<div className="NavBar__menu-item NavBar__home"><p className="--link">Find a Game</p></div>
<Link to="/home">
<div className="NavBar__menu-item NavBar__home">
<p className="--link">Find a Game</p>
</div>
</Link>
<Link to="/news">
<div className="NavBar__menu-item NavBar__news"><p className="--link">News</p></div>
<div className="NavBar__menu-item NavBar__news">
<p className="--link">News</p>
</div>
</Link>
<Link to="/account">
<div className="NavBar__menu-item NavBar__account">{props.user ? props.user.username : <></>}</div>
<div className="NavBar__menu-item NavBar__account">
{state.user.username ? state.user.username : <></>}
</div>
</Link>
</div>
);
}
};
export default NavBar;

View file

@ -1,20 +1,23 @@
export const authReducer = (state, action) => {
switch (action.message) {
case 'LOGIN':
case "LOGIN":
return loginReducer(state, action);
case 'SIGNUP':
case "SIGNUP":
return loginReducer(state, action);
case 'LOGOUT':
case "GUEST":
return loginReducer(state, action);
case "LOGOUT":
return state;
default:
return state;
}
}
};
function loginReducer(state, action) {
const newUser = action.body;
return {...state, user: newUser };
return { ...state, user: newUser };
}

View file

@ -1,43 +1,58 @@
import config from '../config';
import config from "../config";
const authEndpoint = config.authAddress;
const signupEndpoint = `${authEndpoint}/signup`
const loginEndpoint = `${authEndpoint}/login`
const signupEndpoint = `${authEndpoint}/signup`;
const loginEndpoint = `${authEndpoint}/login`;
const guestEndpoint = `${authEndpoint}/guest`;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Sec-Fetch-Site', 'cross-site')
headers.append("Content-Type", "application/json");
headers.append("Accept", "application/json");
headers.append("Sec-Fetch-Site", "cross-site");
const loginService = async(formData) => {
const loginService = async (formData) => {
const response = await fetch(loginEndpoint, {
method: 'POST',
credentials: 'include',
method: "POST",
credentials: "include",
body: JSON.stringify(formData),
headers: headers
headers: headers,
})
.then(res => res.text())
.then(text => JSON.parse(text))
.catch(err => err);
.then((res) => res.text())
.then((text) => JSON.parse(text))
.catch((err) => err);
return response;
}
};
const signupService = async (formData) => {
const response = await fetch(signupEndpoint, {
method: 'POST',
credentials: 'include',
method: "POST",
credentials: "include",
body: JSON.stringify(formData),
headers: headers
headers: headers,
})
.then(res => res.text())
.then(text => JSON.parse(text))
.catch(err => err);
.then((res) => res.text())
.then((text) => JSON.parse(text))
.catch((err) => err);
return response;
}
};
const guestService = async () => {
const response = await fetch(guestEndpoint, {
method: "POST",
credentials: "include",
headers,
})
.then((res) => res.text())
.then((text) => JSON.parse(text))
.catch((err) => err);
return response;
};
export default {
loginService,
signupService
}
signupService,
guestService,
};

View file

@ -1,15 +1,16 @@
const { validationResult } = require('express-validator');
const { validationResult } = require("express-validator");
const userQueries = require('../data/queries/user');
const { hashPassword, compareHash } = require('../services/bcrypt');
const signToken = require('../services/signToken');
const userQueries = require("../data/queries/user");
const { hashPassword, compareHash } = require("../services/bcrypt");
const signToken = require("../services/signToken");
const guestServices = require("../services/guestServices");
const checkValidationErrors = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
}
};
const signup = async (req, res, next) => {
checkValidationErrors(req, res);
@ -20,18 +21,18 @@ const signup = async (req, res, next) => {
const hashedPassword = await hashPassword(user.password);
const secureUser = { ...user, password: hashedPassword };
if (existingUser.length) {
return res.status(409).json({errors: [{auth: 'User already exists!'}]})
return res
.status(409)
.json({ errors: [{ auth: "User already exists!" }] });
}
const newUser = await userQueries.insertUser(secureUser);
signToken(res, newUser)
res.status(201).json({...newUser});
}
catch (err) {
signToken(res, newUser);
res.status(201).json({ ...newUser });
} catch (err) {
res.status(500).json(err);
}
}
};
const login = async (req, res, next) => {
checkValidationErrors(req, res);
@ -42,29 +43,46 @@ const login = async (req, res, next) => {
const savedUser = queryResults[0] || null;
if (!savedUser) {
return res.status(401).send({errors: 'bad credentials'});
return res.status(401).send({ errors: "bad credentials" });
}
const hashedPassword = savedUser.password;
const passwordMatch = await compareHash(user.password, hashedPassword);
if (!passwordMatch) {
return res.status(401).send({errors: 'bad credentials'});
return res.status(401).send({ errors: "bad credentials" });
}
const authorizedUser = {...savedUser};
const authorizedUser = { ...savedUser };
delete authorizedUser.password;
signToken(res, authorizedUser);
res.send({...authorizedUser}).status(200);
res.send({ ...authorizedUser }).status(200);
} catch (e) {
res.status(500).send({ errors: e });
}
};
catch (err) {
res.status(500).send({errors: err});
const guest = async (req, res, next) => {
try {
// username generator returns `Guest-${num}`
const { username, password } = guestServices.generateGuest();
// generateGuestUser();
const email = null;
// id generator returns `
const id = null;
const user = { username, email, id, password };
signToken(res, user);
delete user.password;
res.send(user);
} catch (e) {
console.log(e);
res.status(500).send({ errors: e });
}
}
};
module.exports = {
signup,
login
}
login,
guest,
};

View file

@ -1,49 +1,81 @@
const winType = [
'B+R', 'B+', 'B+T',
'W+R', 'W+', 'W+T',
'0', 'Void', '?'
]
const winType = ["B+R", "B+", "B+T", "W+R", "W+", "W+T", "0", "Void", "?"];
const rankArray = [
'D9', 'D8', 'D7', 'D6', 'D5', 'D4', 'D3', 'D2', 'D1',
'K1', 'K2', 'K3', 'K4', 'K5', 'K6', 'K7', 'K8', 'K9', 'K10',
'K11', 'K12', 'K13', 'K14', 'K15', 'K16', 'K17', 'K18', 'K19', 'K20',
'K21', 'K22', 'K23', 'K24', 'K25', 'K26', 'K27', 'K28', 'K29', 'K30', 'UR'
]
"D9",
"D8",
"D7",
"D6",
"D5",
"D4",
"D3",
"D2",
"D1",
"K1",
"K2",
"K3",
"K4",
"K5",
"K6",
"K7",
"K8",
"K9",
"K10",
"K11",
"K12",
"K13",
"K14",
"K15",
"K16",
"K17",
"K18",
"K19",
"K20",
"K21",
"K22",
"K23",
"K24",
"K25",
"K26",
"K27",
"K28",
"K29",
"K30",
"UR",
];
exports.up = function(knex) {
return knex.schema.createTable("game", table => {
table.increments('id').primary();
table.datetime('date');
table.float('komi').default(6.5);
table.integer('handicap').default(0);
table.integer('board_size').default(19);
table.boolean('open').default(true);
exports.up = function (knex) {
return knex.schema.createTable("game", (table) => {
table.increments("id").primary();
table.datetime("date");
table.float("komi").default(6.5);
table.integer("handicap").default(0);
table.integer("board_size").default(19);
table.boolean("open").default(true);
table.string('application');
table.string('application_version');
table.string("application");
table.string("application_version");
table.timestamps(true, true);
table.string('player_black');
table.string('player_white');
table.enu('player_black_rank', rankArray).default('UR');
table.enu('player_white_rank', rankArray).default('UR');
table.string("player_black");
table.string("player_white");
table.enu("player_black_rank", rankArray).default("UR");
table.enu("player_white_rank", rankArray).default("UR");
table.string('event');
table.string('name');
table.string('description');
table.integer('round');
table.string("event");
table.string("name");
table.string("description");
table.integer("round");
table.enu('win_type', winType);
table.float('score');
table.integer('captures_black');
table.integer('captures_white');
table.enu("win_type", winType);
table.float("score");
table.integer("captures_black");
table.integer("captures_white");
table.integer('user_black').references('id').inTable('user');
table.integer('user_white').references('id').inTable('user');
table.integer('room').references('id').inTable('room');
table.integer('time_setting').references('id').inTable('time_setting');
})
table.integer("user_black").references("id").inTable("user");
table.integer("user_white").references("id").inTable("user");
table.integer("room").references("id").inTable("room");
table.integer("time_setting").references("id").inTable("time_setting");
});
};
exports.down = knex => knex.schema.dropTableIfExists("game");
exports.down = (knex) => knex.schema.dropTableIfExists("game");

View file

@ -1,17 +1,18 @@
const players = ['white', 'black']
const players = ["white", "black"];
exports.up = knex => {
return knex.schema.createTable("move", table => {
table.increments('id').primary();
table.enu('player', players).notNullable();
table.integer('point_x').notNullable();
table.integer('point_y').notNullable();
table.integer('number').notNullable();
table.boolean('game_record').notNullable().default(true);
exports.up = (knex) => {
return knex.schema.createTable("move", (table) => {
table.increments("id").primary();
table.enu("player", players).notNullable();
table.integer("point_x").notNullable();
table.integer("point_y").notNullable();
table.integer("number").notNullable();
table.boolean("game_record").notNullable().default(true);
table.boolean("placement").notNullable().default(false);
table.integer('game').references('id').inTable('game').notNullable();
table.integer('prior_move').references('id').inTable('move');
table.integer("game").references("id").inTable("game").notNullable();
table.integer("prior_move").references("id").inTable("move");
});
};
exports.down = knex => knex.schema.dropTableIfExists("move");
exports.down = (knex) => knex.schema.dropTableIfExists("move");

View file

@ -70,17 +70,23 @@ const findGameByRoom = async (roomId) => {
const insertGame = async (game) => {};
const endGame = async ({ id }) => {
const game = await knex(game).where({ id: id }).update(
{
win_type: winType,
score: score,
captures_black: capturesBlack,
captures_white: capturesWhite,
}
// ["id"]
);
return game;
const endGame = async ({ id, winType, score, bCaptures, wCaptures }) => {
try {
const game = await knex
.from("game")
.returning(gameDetailSelect)
.where({ id: id })
.update({
win_type: winType,
score: score,
captures_black: bCaptures,
captures_white: wCaptures,
open: false,
});
return game;
} catch (e) {
return e;
}
};
module.exports = {

View file

@ -1,36 +1,47 @@
const knex = require('../db');
const knex = require("../db");
const findGameRecord = async (gameId) => {
return await knex('move')
.where({ 'game': gameId, 'game_record': true })
.select('player', 'point_x', 'point_y', 'number')
.orderBy('number')
.then(record => record.map(({player, point_x, point_y}) => ({player, pos: { x: point_x, y: point_y } }) ))
return await knex("move")
.where({ game: gameId, game_record: true })
.select("player", "point_x", "point_y", "number", "prior_move", "placement")
.orderBy("number")
.then((record) =>
record.map(({ player, point_x, point_y }) => ({
player,
pos: { x: point_x, y: point_y },
}))
);
// .then(res => res)
}
};
// id: 1, player: 'black', point_x: 3, point_y: 3, number: 1, game_record: true, game: 1, prior_move: null
const addMove = async ({ gameId, player, x, y, gameRecord, priorMove }) => {
// ! priorMove must be FK not move number
const number = priorMove + 1;
let result;
try {
result = await knex('move')
.returning('*')
.insert({ game: gameId, player, point_x: x, point_y: y, number, game_record: gameRecord, prior_move: priorMove })
.then(res => res);
}
catch (e) {
result = e
}
finally {
result = await knex("move")
.returning("*")
.insert({
game: gameId,
player,
point_x: x,
point_y: y,
number,
game_record: gameRecord,
prior_move: priorMove,
})
.then((res) => res);
} catch (e) {
result = e;
} finally {
console.log(result);
return result;
}
}
};
module.exports = {
findGameRecord,
addMove
}
addMove,
};

View file

@ -1359,9 +1359,9 @@
}
},
"lodash": {
"version": "4.17.15",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
"integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A=="
"version": "4.17.19",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz",
"integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ=="
},
"lodash.includes": {
"version": "4.3.0",

View file

@ -1,10 +1,20 @@
const express = require('express');
const express = require("express");
const router = express.Router();
const app = require('../server');
const authController = require('../controllers/auth');
const { signupValidationRules, loginValidationRules, validate } = require('../middleware/userValidator');
const app = require("../server");
const authController = require("../controllers/auth");
const {
signupValidationRules,
loginValidationRules,
validate,
} = require("../middleware/userValidator");
router.post('/signup', signupValidationRules(), validate, authController.signup);
router.post('/login', loginValidationRules(), validate, authController.login);
router.post(
"/signup",
signupValidationRules(),
validate,
authController.signup
);
router.post("/login", loginValidationRules(), validate, authController.login);
router.post("/guest", authController.guest);
module.exports = router;

View file

@ -181,13 +181,18 @@ const Game = ({ gameData = {}, gameRecord = [] } = {}) => {
this.kos = [];
},
};
if (gameRecord.length) {
// play through all the moves
return gameRecord.reduce(
const game = gameRecord.reduce(
(game, move) => game.makeMove(move),
Game({ gameData }).initGame()
);
// ? why is this being wrapped?
if (gameData && gameData.gameData && gameData.gameData.winner) {
const { winner, score } = gameData.gameData;
return game.manualEnd({ winner, score });
}
return game;
}
return {
winner: gameData.winner || null,
@ -239,28 +244,58 @@ const Game = ({ gameData = {}, gameRecord = [] } = {}) => {
};
},
checkMove: function ({ player, pos: { x, y } }) {
// if game is over
// TODO either change logic here or add additional method for handling moves off of record
if (this.pass > 1) {
return { ...this, success: false };
}
const point = this.boardState[`${x}-${y}`];
const isTurn =
(this.turn === 1 && player === "black") ||
(this.turn === -1 && player === "white");
if (isTurn) {
if (point.legal) {
return { ...this, success: true, move: { player, pos: { x, y } } };
}
}
return { ...this, success: false };
},
makeMove: function ({ player, pos: { x, y } }) {
if (this.pass > 1) {
return { ...this, success: false };
}
if (x === 0) return this.submitPass(player);
let game = this;
let success = false;
const point = game.boardState[`${x}-${y}`];
const isTurn =
(game.turn === 1 && player === "black") ||
(game.turn === -1 && player === "white");
if (isTurn) {
if (point.legal) {
game.pass = 0;
game.addToRecord({ player, pos: { x, y } });
if (this.kos.length) helper.clearKo.call(this);
point.makeMove(game);
game.turn *= -1;
success = true;
}
let game = this;
if (x === 0) return game.submitPass(player);
// if checkMove has not been run, determine legality
if (!game.move) {
game = game.checkMove({ player, pos: { x, y } });
}
if (
// if move is legal
// ? unclear if checking move values is beneficial to prevent race conditions
game.move &&
game.move.player === player &&
game.move.pos.x === x &&
game.move.pos.y
) {
const point = game.boardState[`${x}-${y}`];
game.pass = 0;
// allows for recording of prior move on game record
game.addToRecord(game.move);
if (game.kos.length) helper.clearKo.call(game);
point.makeMove(game);
game.turn *= -1;
success = true;
}
game.boardState = getBoardState(game);
// remove move attribute to prevent duplicate moves
delete game.move;
return { ...game, legalMoves: getLegalMoves(game), success };
},
@ -389,6 +424,14 @@ const Game = ({ gameData = {}, gameRecord = [] } = {}) => {
this.playerState.bScore - (this.playerState.wScore + this.komi);
return { ...this, score, winner: score > 0 ? 1 : -1 };
},
// for playing historic games
manualEnd: function ({ winner, score }) {
this.turn = 0;
this.winner = winner;
this.score = score;
return this;
},
};
};

View file

@ -7,11 +7,33 @@ const GameService = ({ moveQueries, gameQueries }) => {
};
const gamesInProgress = {};
const storeMove = (gameId) => async ({ player, pos: { x, y } }) => {
let move = { player, pos: { x, y } };
try {
if (moveQueries) {
const { id } = await moveQueries.addMove({
gameId,
player,
x,
y,
gameRecord: true,
priorMove: null,
});
move.id = id;
move.success = true;
}
} catch (e) {
console.log(e);
move.success = false;
} finally {
return move;
}
};
return {
initGame({ id, gameRecord = [], ...gameData }) {
if (gamesInProgress[id]) return this.getDataForUI(id);
if (gameRecord.length) {
console.log("here");
gamesInProgress[id] = Game({ gameData, gameRecord });
} else {
gamesInProgress[id] = Game({ gameData }).initGame();
@ -32,6 +54,7 @@ const GameService = ({ moveQueries, gameQueries }) => {
return { message: "error restoring game" };
}
}
gamesInProgress[id] = await gamesInProgress[id].checkMove(move);
gamesInProgress[id] = gamesInProgress[id].makeMove(move);
if (gamesInProgress[id].success === false)
return { message: "illegal move" };
@ -73,6 +96,7 @@ const GameService = ({ moveQueries, gameQueries }) => {
},
resign: ({ id, player }) => {
// add resign gamesQueries
return gamesInProgress[id].submitResign(player).getMeta();
},
@ -108,9 +132,19 @@ const GameService = ({ moveQueries, gameQueries }) => {
async endGame({ id }) {
gamesInProgress[id] = gamesInProgress[id].endGame();
const { winner, score, playerState } = gamesInProgress[id];
const { bCaptures, wCaptures } = playerState;
const winType = winner > 0 ? "B+" : "W+";
try {
if (gameQueries) {
// TODO add end game query
const result = await gameQueries.endGame({
id,
winType,
score,
bCaptures,
wCaptures,
});
console.log(result);
}
} catch (e) {
console.log(e);

View file

@ -0,0 +1,25 @@
const generateRandomPassword = () => {
const minLength = 8,
maxLength = 16,
minUTF = 33,
maxUTF = 126;
const randomize = (min, max) => Math.floor(Math.random() * (max - min) + min);
return Array(randomize(minLength, maxLength))
.fill(0)
.map(() => String.fromCharCode(randomize(minUTF, maxUTF)))
.join("");
};
const guestService = {
currentGuest: 0,
generateGuest() {
// generate unique username
const username = `Guest-${String(this.currentGuest++).padStart(6, 0)}`;
// generate random "password"
// this exists solely to add extra randomness to signed token and is not validated
const password = generateRandomPassword();
return { username, password };
},
};
module.exports = guestService;

View file

@ -1,4 +1,4 @@
// TODO const someSocketLogic = require('./middleware/socketssockets/...');
// TODO const someSocketLogic = require('./middleware/sockets/...');
const socketIO = require("socket.io");
const io = socketIO({ cookie: false });
@ -24,8 +24,23 @@ io.on("connection", async (socket) => {
socket.on("connect_game", (data) => {
const game = `game-${data.game.id}`;
socket.join(game, async () => {
// TODO move this logic into game service
const gameData = await gameQueries.findGameById(data.game.id);
const convertWinType = (winType) => {
if (winType.includes("B")) return 1;
if (winType.includes("W")) return -1;
if (winType.includes("0")) return "D";
return "?";
};
gameData.winner = gameData.win_type
? convertWinType(gameData.win_type)
: 0;
const gameRecord = await moveQueries.findGameRecord(data.game.id);
await gameServices.initGame({ id: data.game.id, gameRecord });
await gameServices.initGame({
id: data.game.id,
gameRecord,
gameData,
});
const { board, ...meta } = await gameServices.getDataForUI(
data.game.id
);
@ -37,7 +52,6 @@ io.on("connection", async (socket) => {
socket.on("make_move", async (data) => {
const { user, move, board, game, room } = data;
const gameNsp = `game-${data.game.id}`;
try {
const { board, message, ...meta } = await gameServices.makeMove({
id: data.game.id,