First commit to the new repository

:
This commit is contained in:
Daniel Ledda
2020-05-10 15:10:12 +02:00
commit d99d7cbfec
49 changed files with 10784 additions and 0 deletions

3
.babelrc Executable file
View File

@@ -0,0 +1,3 @@
{
"presets": ["@babel/env", "@babel/preset-react"]
}

2
.gitignore vendored Executable file
View File

@@ -0,0 +1,2 @@
node_modules
dist

2
.idea/.gitignore generated vendored Executable file
View File

@@ -0,0 +1,2 @@
# Default ignored files
/workspace.xml

7
.idea/inspectionProfiles/Project_Default.xml generated Executable file
View File

@@ -0,0 +1,7 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="TsLint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>

9
.idea/kadi_game.iml generated Executable file
View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$/../kadi_game" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="kadi_backend" />
</component>
</module>

6
.idea/misc.xml generated Executable file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="JSX" />
</component>
</project>

10
.idea/modules.xml generated Executable file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/kadi_board.iml" filepath="$PROJECT_DIR$/.idea/kadi_board.iml" />
<module fileurl="file://$PROJECT_DIR$/../kadi_frontend/.idea/kniffel.iml" filepath="$PROJECT_DIR$/../kadi_frontend/.idea/kniffel.iml" />
<module fileurl="file://$PROJECT_DIR$/../../expressjs/kniffel_backend/.idea/kniffel_backend.iml" filepath="$PROJECT_DIR$/../../expressjs/kniffel_backend/.idea/kniffel_backend.iml" />
</modules>
</component>
</project>

7
.idea/vcs.xml generated Executable file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$/../kadi_frontend" vcs="Git" />
</component>
</project>

7608
package-lock.json generated Executable file

File diff suppressed because it is too large Load Diff

46
package.json Executable file
View File

@@ -0,0 +1,46 @@
{
"name": "kadi-board",
"version": "1.0.0",
"description": "",
"homepage": "/kadi/game/",
"license": "ISC",
"author": "Daniel Ledda",
"scripts": {
"build": "webpack --mode development",
"postbuild": "rsync -avu --delete dist/ ../kadi_backend/dist/game/static",
"start": "webpack-dev-server --mode development",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.9.6",
"@babel/preset-env": "^7.9.6",
"@babel/preset-react": "^7.9.4",
"@types/node": "^13.11.1",
"@types/react": "^16.9.34",
"@types/react-dom": "^16.9.7",
"@types/react-router-dom": "^5.1.5",
"font-loader": "^0.1.2",
"ignore-loader": "^0.1.2",
"babel-loader": "^8.1.0",
"css-loader": "^3.5.3",
"file-loader": "^6.0.0",
"react-hot-loader": "^4.12.21",
"style-loader": "^1.2.1",
"ts-loader": "^7.0.3",
"tslint": "^6.1.1",
"tslint-react": "^4.2.0",
"typescript": "^3.8.3",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"axios": "^0.19.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^0.88.2"
}
}

22
public/index.html Executable file
View File

@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Score dice games with K A D I"
/>
<link rel="manifest" href="manifest.json" />
<title>K A D I - Digital Dice</title>
</head>
<body>
<div id="root"></div>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<script src="static/bundle.js"></script>
</body>
</html>

BIN
public/static/favicon.ico Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

25
public/static/manifest.json Executable file
View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
public/static/robots.txt Executable file
View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

9
src/App.test.js Executable file
View File

@@ -0,0 +1,9 @@
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

29
src/App.tsx Executable file
View File

@@ -0,0 +1,29 @@
import React, {ReactNode} from "react";
import Game from "./Components/Game";
import {LocaleContext, localeDefaultVal} from "./static/strings";
import "semantic-ui-css/semantic.min.css";
interface AppState {
}
interface AppProps {}
class App extends React.Component<AppProps, AppState> {
constructor(props: AppProps) {
super(props);
this.state = {
};
}
render(): ReactNode {
return (
<LocaleContext.Provider value={localeDefaultVal}>
<Game/>
</LocaleContext.Provider>
);
}
}
App.contextType = LocaleContext;
export default App;

95
src/Classes/Caretaker.ts Executable file
View File

@@ -0,0 +1,95 @@
export interface Memento {
}
export interface Originator {
getSnapshot(): Memento;
restoreSnapshot(snapshot: Memento): void;
}
export class Caretaker {
private history: Memento[] = [];
private currentHistoryIndex: number;
private readonly originator: Originator;
private readonly maxHistorySize: number;
constructor(maxHistorySize: number, originator: Originator) {
this.maxHistorySize = maxHistorySize;
this.originator = originator;
this.currentHistoryIndex = -1;
this.save();
}
undo(): void {
if (this.undosLeft()) {
this.currentHistoryIndex--;
const mementoToRestore = this.history[this.currentHistoryIndex];
this.originator.restoreSnapshot(mementoToRestore);
}
}
redo(): void {
if (this.redosLeft()) {
this.currentHistoryIndex++;
const mementoToRestore = this.history[this.currentHistoryIndex];
this.originator.restoreSnapshot(mementoToRestore);
}
}
save(): void {
const relativeHistory = this.history.slice(0, this.currentHistoryIndex + 1);
this.history = relativeHistory.concat(this.originator.getSnapshot());
this.currentHistoryIndex++;
this.fixHistorySize();
}
undosLeft(): boolean {
return this.inHistoryBounds(this.currentHistoryIndex - 1);
}
redosLeft(): boolean {
return this.inHistoryBounds(this.currentHistoryIndex + 1);
}
private fixHistorySize(): void {
if (this.history.length > this.maxHistorySize) {
this.history = this.history.slice(1, this.maxHistorySize + 1);
this.currentHistoryIndex = this.history.length - 1;
}
}
private inHistoryBounds(index: number): boolean {
const outsideBounds: boolean = index < 0 || index >= this.history.length;
return !outsideBounds;
}
}
export class CaretakerSet {
private readonly caretakers: Caretaker[] = [];
constructor(maxHistorySize: number, ...originators: Originator[]) {
originators.forEach(originator => {
this.caretakers.push(new Caretaker(maxHistorySize, originator));
});
}
undo(): void {
this.caretakers.forEach(c => c.undo());
}
redo(): void {
this.caretakers.forEach(c => c.redo());
}
save(): void {
this.caretakers.forEach(c => c.save());
}
undosLeft(): boolean {
return this.caretakers[0].undosLeft();
}
redosLeft(): boolean {
return this.caretakers[0].redosLeft();
}
}

128
src/Classes/PlayerScoreCard.ts Executable file
View File

@@ -0,0 +1,128 @@
import {ScoreCellValue} from "./ScoreCell";
import ScoreBlock, {createBlockFromDef, BlockState, ScoreBlockJSONRepresentation} from "./ScoreBlock";
import {BlockDef, GameSchema} from "../static/rulesets";
import { Memento, Originator } from "./Caretaker";
import {CellFlag} from "../static/enums";
export type CellLocation = { blockId: string, cellId: string };
class PlayerScoreCard implements Originator {
private readonly playerId: string;
private readonly blocks: ScoreBlock[];
constructor(playerId: string, gameSchema: GameSchema) {
this.playerId = playerId;
this.blocks = PlayerScoreCard.generateBlocks(gameSchema.blocks);
}
private static generateBlocks(blockDefs: BlockDef[]): ScoreBlock[] {
const blocks = [];
for (const blockDef of blockDefs) {
blocks.push(createBlockFromDef(blockDef));
}
return blocks;
}
getTotal(): number {
let playerTotal = 0;
for (const block of this.blocks) {
playerTotal += block.getTotal();
}
return playerTotal;
}
getBlockTotalById(blockId: string): number {
return this.getBlockById(blockId).getTotal();
}
getBlockSubTotalById(blockId: string): number {
return this.getBlockById(blockId).getSubtotal();
}
blockWithIdHasBonus(blockId: string): boolean {
return this.getBlockById(blockId).bonusAttained();
}
updateCellByLocationWithValue(loc: CellLocation, value: ScoreCellValue | CellFlag): void {
this.getBlockById(loc.blockId).updateCellByIdWithValue(loc.cellId, value);
}
getCellScoreByLocation(loc: CellLocation): number {
return this.getBlockById(loc.blockId).getCellScoreById(loc.cellId);
}
cellAtLocationIsStruck(loc: CellLocation): boolean {
return this.getBlockById(loc.blockId).cellWithIdIsStruck(loc.cellId);
}
getSnapshot(): Memento {
return new PlayerScoreCardMemento(this.getState());
}
private getState(): PlayerScoreCardState {
const state: PlayerScoreCardState = {
blocks: []
};
state.blocks = this.blocks.map(block => block.getState());
return state;
}
restoreSnapshot(snapshot: PlayerScoreCardMemento): void {
const state = snapshot.getState();
state.blocks.forEach(block => {
const correspondingBlock = this.getBlockById(block.id);
correspondingBlock.restoreCellsFromStates(block.cellStates);
});
}
private getBlockById(blockId: string): ScoreBlock {
const foundScoreBlock = this.blocks.find(block => block.getId() === blockId);
if (foundScoreBlock !== undefined) {
return foundScoreBlock;
}
else {
throw new Error("ScoreBlock with ID " + blockId + " not found for player" + this.playerId + "!")
}
}
filledOut(): boolean {
for (const block in this.blocks) {
if (!this.blocks[block].filledOut()) {
return false;
}
}
return true;
}
getJSONRepresentation(): PlayerScoreCardJSONRepresentation {
const JSONRepresentation: PlayerScoreCardJSONRepresentation = {
playerId: this.playerId,
blocks: []
};
this.blocks.forEach(block => JSONRepresentation.blocks.push(block.getJSONRepresentation()));
return JSONRepresentation;
}
}
interface PlayerScoreCardState {
blocks: BlockState[];
}
export interface PlayerScoreCardJSONRepresentation {
playerId: string;
blocks: ScoreBlockJSONRepresentation[];
}
class PlayerScoreCardMemento implements Memento {
private readonly state: PlayerScoreCardState;
constructor(state: PlayerScoreCardState) {
this.state = state;
}
getState(): PlayerScoreCardState {
return this.state;
}
}
export default PlayerScoreCard;

153
src/Classes/ScoreBlock.ts Executable file
View File

@@ -0,0 +1,153 @@
import ScoreCell, {
createCellFromDef,
ScoreCellValue,
CellState,
ScoreCellJSONRepresentation
} from "./ScoreCell";
import {CellDef, BlockDef, BonusBlockDef, NoBonusBlockDef } from "../static/rulesets";
import {CellFlag} from "../static/enums";
export const createBlockFromDef = (blockDef: BlockDef) : ScoreBlock => {
if (blockDef.hasBonus) {
return new ScoreBlockWithBonus(blockDef);
}
else {
return new ScoreBlockNoBonus(blockDef);
}
};
export interface BlockState {
id: string;
cellStates: CellState[];
}
export interface ScoreBlockJSONRepresentation {
id: string;
cells: ScoreCellJSONRepresentation[];
}
abstract class ScoreBlock {
protected cells: ScoreCell[];
protected id: string;
protected constructor(blockDef: BlockDef) {
this.cells = ScoreBlock.generateCells(blockDef.cells);
this.id = blockDef.id;
}
private static generateCells(cellDefs: CellDef[]): ScoreCell[] {
const cells = [];
for (const cellDef of cellDefs) {
cells.push(createCellFromDef(cellDef));
}
return cells;
}
abstract getTotal(): number;
abstract bonusAttained(): boolean;
getSubtotal(): number {
let blockScore = 0;
for (const cell of this.cells) {
blockScore += cell.getScore();
}
return blockScore;
}
updateCellByIdWithValue(cellId: string, value: ScoreCellValue | CellFlag): void {
this.getCellById(cellId).update(value);
}
getCellScoreById(cellId: string): number {
return this.getCellById(cellId).getScore();
}
cellWithIdIsStruck(cellId: string): boolean {
return this.getCellById(cellId).isStruck();
}
private getCellById(cellId: string): ScoreCell {
const foundScoreCell = this.cells.find(cell => cell.getId() === cellId);
if (foundScoreCell !== undefined) {
return foundScoreCell;
}
else {
throw new Error("ScoreCell with ID " + cellId + " not found in block with ID " + this.id + "!")
}
}
getId(): string {
return this.id;
}
getState(): BlockState {
const state: BlockState = {
id: this.id,
cellStates: []
};
state.cellStates = this.cells.map(cell => cell.getState());
return Object.assign({}, state);
}
restoreCellsFromStates(cellStates: CellState[]): void {
cellStates.forEach(cellState => {
const correspondingCell = this.getCellById(cellState.id);
correspondingCell.restoreFromState(cellState);
})
}
filledOut(): boolean {
for (const cell in this.cells) {
if (!this.cells[cell].filledOut()) {
return false;
}
}
return true;
}
getJSONRepresentation(): ScoreBlockJSONRepresentation {
const JSONRepresentation: ScoreBlockJSONRepresentation = {
id: this.id,
cells: []
};
this.cells.forEach(cell => JSONRepresentation.cells.push(cell.getJSONRepresentation()));
return JSONRepresentation;
}
}
class ScoreBlockWithBonus extends ScoreBlock {
protected readonly bonus: number;
protected readonly bonusFor: number;
constructor(blockDef: BonusBlockDef) {
super(blockDef);
this.bonus = blockDef.bonusScore;
this.bonusFor = blockDef.bonusFor;
}
getTotal(): number {
const prelimScore = this.getSubtotal();
return prelimScore >= this.bonusFor ? prelimScore + this.bonus : prelimScore;
}
bonusAttained(): boolean {
return this.getSubtotal() >= this.bonusFor;
}
}
class ScoreBlockNoBonus extends ScoreBlock {
constructor(blockDef: NoBonusBlockDef) {
super(blockDef);
}
getTotal(): number {
return this.getSubtotal();
}
bonusAttained(): boolean {
return false;
}
}
export default ScoreBlock;

255
src/Classes/ScoreCell.ts Executable file
View File

@@ -0,0 +1,255 @@
import {CellFlag, FieldType} from "../static/enums";
import {BoolCellDef, CellDef, MultiplierCellDef, NumberCellDef, YahtzeeCellDef} from "../static/rulesets"
export const createCellFromDef = (cellDef: CellDef) : ScoreCell => {
switch (cellDef.fieldType) {
case FieldType.number:
return new NumberScoreCell(cellDef);
case FieldType.bool:
return new BoolScoreCell(cellDef);
case FieldType.multiplier:
return new MultiplierScoreCell(cellDef);
case FieldType.yahtzee:
return new YahtzeeScoreCell(cellDef);
}
};
export type ScoreCellValue = number | boolean;
export interface CellState {
id: string;
struck: boolean;
value: number | boolean;
currentIteratorIndex?: number;
}
export interface ScoreCellJSONRepresentation {
id: string;
value: number | boolean | CellFlag.strike;
}
abstract class ScoreCell {
protected readonly id: string;
protected static readonly fieldType: FieldType;
protected struck: boolean;
protected value: number | boolean;
protected constructor(cellDef: CellDef) {
this.id = cellDef.id;
this.struck = false;
this.value = 0;
}
abstract getScore(): number;
abstract update(value: ScoreCellValue | CellFlag): void;
isStruck(): boolean {
return this.struck;
}
protected unstrike(): void {
this.struck = false;
}
strike(): void {
this.struck = true;
}
getId(): string {
return this.id;
}
getState(): CellState {
const state: CellState = {
id: this.id,
struck: this.struck,
value: this.value
};
return Object.assign({}, state);
}
restoreFromState(cellState: CellState): void {
this.struck = cellState.struck;
this.value = cellState.value;
}
filledOut(): boolean {
return this.value > 0 || this.isStruck();
}
getJSONRepresentation(): ScoreCellJSONRepresentation {
return { id: this.id, value: this.isStruck() ? CellFlag.strike : this.value };
}
}
type IterableSequenceValues = boolean | number | CellFlag.strike;
abstract class IterableScoreCell extends ScoreCell {
protected iteratedSequence: IterableSequenceValues[];
protected currentIteratorIndex: number;
protected constructor(cellDef: CellDef) {
super(cellDef);
this.iteratedSequence = [];
this.currentIteratorIndex = 0;
}
update(value: ScoreCellValue | CellFlag): void {
if (value == CellFlag.strike) {
this.strike();
}
else if (this.struck) {
this.unstrike();
}
else {
this.iterate();
}
}
getState(): CellState {
const state: CellState = {
id: this.id,
struck: this.struck,
value: this.value,
currentIteratorIndex: this.currentIteratorIndex
};
return Object.assign({}, state);
}
restoreFromState(state: CellState): void {
this.struck = state.struck;
this.value = state.value;
this.currentIteratorIndex = state.currentIteratorIndex as number;
}
private iterate(): void {
if (this.inIteratorBounds(this.currentIteratorIndex + 1)) {
this.currentIteratorIndex++;
}
else {
this.currentIteratorIndex = 0;
}
this.setValueFromIterator();
}
private inIteratorBounds(index: number): boolean {
const outsideBounds: boolean = index < 0 || index >= this.iteratedSequence.length;
return !outsideBounds;
}
private setValueFromIterator(): void {
const valueAtIteratorIndex = this.iteratedSequence[this.currentIteratorIndex];
if (this.isStruck()) {
this.unstrike();
}
if (valueAtIteratorIndex == CellFlag.strike) {
this.strike();
}
else {
this.value = valueAtIteratorIndex;
}
}
}
class NumberScoreCell extends ScoreCell {
protected static readonly fieldType = FieldType.number;
constructor(cellDef: NumberCellDef) {
super(cellDef);
this.value = 0;
}
getScore(): number {
return this.value as number;
}
update(value: ScoreCellValue | CellFlag): void {
switch (value){
case CellFlag.strike:
this.strike();
break;
case CellFlag.unstrike:
this.unstrike();
break;
default:
this.value = value;
break;
}
}
}
class BoolScoreCell extends IterableScoreCell {
protected static readonly fieldType = FieldType.bool;
private readonly score: number;
protected value: boolean;
constructor(cellDef: BoolCellDef) {
super(cellDef);
this.score = cellDef.score;
this.value = false;
this.iteratedSequence = [false, true];
}
getScore(): number {
if (this.value && !this.isStruck()) {
return this.score;
}
else {
return 0;
}
}
}
class YahtzeeScoreCell extends IterableScoreCell {
protected static readonly fieldType = FieldType.yahtzee;
private readonly score: number;
protected value: number;
constructor(cellDef: YahtzeeCellDef) {
super(cellDef);
this.score = cellDef.score;
this.value = 0;
for (let i = 0; i <= cellDef.maxYahtzees; i++) {
this.iteratedSequence.push(i);
}
}
getScore(): number {
if (this.isStruck()) {
return 0;
}
else {
return this.score * this.value;
}
}
}
class MultiplierScoreCell extends IterableScoreCell {
protected static readonly fieldType = FieldType.multiplier;
protected readonly multiplier: number;
protected value: number;
constructor(cellDef: MultiplierCellDef) {
super(cellDef);
this.multiplier = cellDef.multiplier;
this.value = 0;
for (let i = 0; i <= cellDef.maxMultiples; i++) {
this.iteratedSequence.push(i);
}
}
getScore(): number {
if (this.isStruck()) {
return 0;
}
else {
return this.multiplier * this.value;
}
}
}
export default ScoreCell;

66
src/Components/Game.tsx Executable file
View File

@@ -0,0 +1,66 @@
import React, {ReactNode} from "react";
import "../static/css/game.css";
import KadiBoard from "./KadiBoard";
import GameSetup, {GameSettings} from "./GameSetup"
import Settings from "../static/settings.json";
import {SupportedLang} from "../static/enums";
interface GameState {
currentSettings: GameSettings;
settingUp: boolean;
}
interface GameProps {}
class Game extends React.Component<GameProps, GameState> {
state: GameState;
constructor(props: GameProps) {
super(props);
const startupSettings: GameSettings = {
playerIds: Settings.players,
ruleset: Settings.ruleset,
lang: Settings.lang as SupportedLang
};
this.state = {
currentSettings: startupSettings,
settingUp: true,
};
}
onSetupComplete: (gameSettings: GameSettings) => void = (gameSettings) => {
this.setState({
currentSettings: gameSettings,
settingUp: false
});
};
returnToSetup: () => void = () => {
this.setState({settingUp: true});
};
render(): ReactNode {
return (
<>
{this.state.settingUp ?
(
<GameSetup
onSetupComplete={this.onSetupComplete}
settings={this.state.currentSettings}
/>
) :
(
<KadiBoard
settings={this.state.currentSettings}
returnToSetup={this.returnToSetup}
/>
)
}
</>
);
}
}
export default Game;

252
src/Components/GameSetup.tsx Executable file
View File

@@ -0,0 +1,252 @@
import React, {ChangeEvent, FocusEvent, KeyboardEvent, ReactNode} from "react";
import {getSchemaListings, SchemaListing} from "../static/rulesets";
import {LocaleContext, LanguageNames} from "../static/strings";
import {SupportedLang} from "../static/enums";
class GameSetup extends React.Component<GameSetupProps, GameSetupState> {
private readonly availableRulesets: SchemaListing[];
private changeLang: (lang: string) => void;
state: GameSetupState;
constructor(props: GameSetupProps) {
super(props);
this.availableRulesets = getSchemaListings();
this.changeLang = () => {};
this.state = {
selectedLang: this.props.settings.lang,
selectedRuleset: this.props.settings.ruleset,
enteredPlayerIds: this.props.settings.playerIds,
editingPlayerName: false,
};
}
componentDidMount(): void {
this.changeLang = this.context.changeLang;
}
onLanguageChange: (lang: SupportedLang) => void = (lang) => {
this.setState({ selectedLang: lang });
this.changeLang(lang);
};
onRulesetChange: (ruleset: string) => void = (ruleset) => {
this.setState({ selectedRuleset: ruleset });
};
removePlayer: (index: number) => void = (index) => {
const newPlayers = this.state.enteredPlayerIds.slice();
newPlayers.splice(index, 1);
this.setState({enteredPlayerIds: newPlayers});
};
addPlayer: (playerSubmission: string, keepEditing: boolean) => void = (playerSubmission, keepEditing) => {
const newPlayers = this.state.enteredPlayerIds.slice();
if (!newPlayers.find(enteredPlayer => enteredPlayer == playerSubmission)) {
newPlayers.push(playerSubmission);
}
this.setState({enteredPlayerIds: newPlayers, editingPlayerName: keepEditing});
};
submitSettings: () => void = () => {
this.props.onSetupComplete({
ruleset: this.state.selectedRuleset,
playerIds: this.state.enteredPlayerIds,
lang: this.state.selectedLang,
});
};
render(): ReactNode {
const Locale = this.context.strings;
const langOptions: ReactNode[] = [];
for (const lang in SupportedLang) {
let className = "option";
if (this.state.selectedLang === lang) {
className += " selected";
}
langOptions.push((
<div
key={lang + "lang_option"}
className={className}
onClick={() => this.onLanguageChange(lang as SupportedLang)}
>
{LanguageNames[lang as SupportedLang]}
<span className={"selectorBox"}/>
</div>
));
}
const rulesetOptions: ReactNode[] = [];
for (const rulesetListing of this.availableRulesets) {
let className = "option";
if (this.state.selectedRuleset === rulesetListing.id) {
className += " selected";
}
rulesetOptions.push((
<div
key={rulesetListing.id + "ruleset_option"}
className={className}
onClick={() => this.onRulesetChange(rulesetListing.id)}
>
{rulesetListing.label}
<span className={"selectorBox"}/>
</div>
));
}
const playerListing: ReactNode[] = [];
for (let i = 0; i < this.state.enteredPlayerIds.length; i++) {
const playerName = this.state.enteredPlayerIds[i];
playerListing.push((
<div
key={playerName + "_list"}
className={"option playerOption"}
>
{playerName}
<span
className={"trashButton"}
onClick={() => this.removePlayer(i)}
/>
</div>
));
}
playerListing.push((
<AddPlayerField
playersListEmpty={playerListing.length === 0}
submitNewPlayer={this.addPlayer}
userEditing={this.state.editingPlayerName}
/>
));
return (
<div className={"gameSetup"}>
<div className={"setupFormContainer"}>
<div className={"setupForm"}>
<div className={"optionGroup"}>
<div className={"optionGroupTitleContainer"}>
<span className={"optionGroupTitle"}>
{Locale.setupScreen.players}
</span>
</div>
<div className={"playerList optionList"}>
{playerListing}
</div>
</div>
<div className={"optionGroup"}>
<div className={"optionGroupTitleContainer"}>
<span className={"optionGroupTitle"}>
{Locale.setupScreen.selectRuleset}
</span>
</div>
<div className={"rulesetOptions optionList"}>
{rulesetOptions}
</div>
</div>
<div className={"optionGroup"}>
<div className={"optionGroupTitleContainer"}>
<span className={"optionGroupTitle"}>
{Locale.setupScreen.selectLanguage}
</span>
</div>
<div className={"languageOptions optionList"}>
{langOptions}
</div>
</div>
<div className={"playButtonContainer"}>
<button
className={"playButton"}
onClick={this.submitSettings}
disabled={this.state.enteredPlayerIds.length < 1}
>
{Locale.setupScreen.startGame}
</button>
</div>
</div>
</div>
</div>
);
}
}
GameSetup.contextType = LocaleContext;
interface GameSetupProps {
onSetupComplete: (settings: GameSettings) => void;
settings: GameSettings;
}
interface GameSetupState {
selectedLang: SupportedLang;
selectedRuleset: string;
enteredPlayerIds: string[];
editingPlayerName: boolean;
}
export interface GameSettings {
ruleset: string;
playerIds: string[];
lang: SupportedLang;
}
const AddPlayerField: React.FunctionComponent<AddPlayerFieldProps> = ({playersListEmpty, submitNewPlayer, userEditing}) => {
const Locale = React.useContext(LocaleContext).strings;
const [beingEdited, updateBeingEdited] = React.useState(false);
const [currentEditValue, updateCurrentEditValue] = React.useState("");
const placeholderText = playersListEmpty ?
Locale.setupScreen.noPlayersEntered :
Locale.setupScreen.clickToAddPlayer;
const displayText = beingEdited ? currentEditValue : placeholderText;
const handleFocus = () => {
updateBeingEdited(true);
};
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
updateCurrentEditValue(e.target.value);
};
const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
attemptPlayerSubmit(e.target.value, false);
updateBeingEdited(false);
};
const handleKeyUp = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
attemptPlayerSubmit(e.currentTarget.value, true);
}
};
const attemptPlayerSubmit = (input: string, keepEditing: boolean) => {
if (input !== "") {
submitNewPlayer(input, keepEditing);
updateCurrentEditValue("");
}
};
return (
<div
key={"noplayer_list"}
className={"option playerOption inputPlayerField" + (beingEdited ? "" : " faded")}
>
<input
type={"text"}
value={displayText}
autoFocus={userEditing}
onFocus={handleFocus}
onChange={handleChange}
onBlur={handleBlur}
onKeyUp={handleKeyUp}
/>
</div>
);
};
interface AddPlayerFieldProps {
playersListEmpty: boolean;
submitNewPlayer: (name: string, keepEditing: boolean) => void;
userEditing: boolean;
}
export default GameSetup;

View File

@@ -0,0 +1,17 @@
import React from "react";
interface GenericKadiRowContainerProps {
cellCssClassName: string;
label: string;
}
const GenericKadiRowContainer: React.FunctionComponent<GenericKadiRowContainerProps> = ({ cellCssClassName, label, children }) => {
return (
<tr className={"kadiRow " + cellCssClassName}>
<td className="kadiCell rowLabelCell">{label}</td>
{children}
</tr>
);
};
export default GenericKadiRowContainer;

View File

@@ -0,0 +1,29 @@
import React, {ReactNode} from "react";
import KadiCell from "./KadiCell";
import {FieldType} from "../static/enums";
import {CellScores} from "./KadiBoard";
interface KadiBlockBonusRowProps {
blockId: string;
bonusScore: number;
scores: CellScores;
}
const KadiBlockBonusRow: React.FunctionComponent<KadiBlockBonusRowProps> = ({ blockId, bonusScore, scores}) => {
const cells: ReactNode[] = [];
for (const playerId in scores) {
cells.push((
<KadiCell
key={"cell_bonus_" + blockId + "_" + playerId}
location={{ blockId, cellId: "bonus"}}
fieldType={FieldType.bonus}
playerId={playerId}
value={scores[playerId] ? bonusScore : 0}
onCellEdit={() => {}}
/>
));
}
return <>{cells}</>;
};
export default KadiBlockBonusRow;

View File

@@ -0,0 +1,83 @@
import {BlockDef} from "../static/rulesets";
import {CellLocation} from "../Classes/PlayerScoreCard";
import React, {ReactElement} from "react";
import {formatUnicorn, LocaleContext} from "../static/strings";
import {FieldType} from "../static/enums";
import {BlockScores, CellEventResponse} from "./KadiBoard";
import GenericKadiRowContainer from "./GenericKadiRowContainer";
import KadiEditableRowCells from "./KadiEditableRowCells";
import KadiBlockTotalRow from "./KadiBlockTotalRow";
import KadiBlockSubtotalRow from "./KadiBlockSubtotalRow";
import KadiBlockBonusRow from "./KadiBlockBonusRow";
interface BlockRendererProps {
blockSchema: BlockDef;
showResults: boolean;
onCellEdit(res: CellEventResponse): void;
scores: BlockScores;
}
const KadiBlockRenderer: React.FunctionComponent<BlockRendererProps> = ({ blockSchema , showResults, scores, onCellEdit}) => {
const rowsInBlock: ReactElement[] = [];
const Locale = React.useContext(LocaleContext).strings;
for (const cell of blockSchema.cells) {
rowsInBlock.push((
<GenericKadiRowContainer
key={"rowCont" + cell.id + blockSchema.id}
label={cell.label}
cellCssClassName={cell.fieldType}
>
<KadiEditableRowCells
location={{blockId: blockSchema.id, cellId: cell.id}}
fieldType={cell.fieldType}
scores={scores[cell.id]}
onCellEdit={onCellEdit}
/>
</GenericKadiRowContainer>
));
}
if (blockSchema.hasBonus) {
rowsInBlock.push(
<GenericKadiRowContainer
key={"rowContSubtotal" + blockSchema.id}
label={Locale.rowLabels.subtotal}
cellCssClassName={FieldType.subtotal + (showResults ? "" : " hideResults")}
>
<KadiBlockSubtotalRow
blockId={blockSchema.id}
scores={scores.subtotals}
/>
</GenericKadiRowContainer>
);
rowsInBlock.push(
<GenericKadiRowContainer
key={"rowContBonus" + blockSchema.id}
label={Locale.rowLabels.bonus}
cellCssClassName={FieldType.bonus + (showResults ? "" : " hideResults")}
>
<KadiBlockBonusRow
blockId={blockSchema.id}
bonusScore={blockSchema.bonusScore}
scores={scores.bonuses}
/>
</GenericKadiRowContainer>
);
}
rowsInBlock.push(
<GenericKadiRowContainer
key={"rowContTotal" + blockSchema.id}
label={formatUnicorn(Locale.rowLabels.blockTotal, blockSchema.label)}
cellCssClassName={FieldType.total + (showResults ? "" : " hideResults")}
>
<KadiBlockTotalRow
blockId={blockSchema.id}
scores={scores.totals}
/>
</GenericKadiRowContainer>
);
return <>{rowsInBlock}</>;
};
export default KadiBlockRenderer;

View File

@@ -0,0 +1,28 @@
import React, {ReactNode} from "react";
import KadiCell from "./KadiCell";
import {FieldType} from "../static/enums";
import {CellScores} from "./KadiBoard";
interface KadiBlockSubtotalRowProps {
blockId: string;
scores: CellScores;
}
const KadiBlockSubtotalRow: React.FunctionComponent<KadiBlockSubtotalRowProps> = ({ blockId, scores}) => {
const cells: ReactNode[] = [];
for (const playerId in scores) {
cells.push((
<KadiCell
key={"cell_subtotal_" + blockId + "_" + playerId}
location={{ blockId, cellId: "subtotal"}}
fieldType={FieldType.subtotal}
playerId={playerId}
value={scores[playerId]}
onCellEdit={() => {}}
/>
));
}
return <>{cells}</>;
};
export default KadiBlockSubtotalRow;

View File

@@ -0,0 +1,28 @@
import React, {ReactNode} from "react";
import KadiCell from "./KadiCell";
import {FieldType} from "../static/enums";
import {CellScores} from "./KadiBoard";
interface KadiBlockTotalRowProps {
blockId: string;
scores: CellScores;
}
const KadiBlockTotalRow: React.FunctionComponent<KadiBlockTotalRowProps> = ({ blockId, scores }) => {
const cells: ReactNode[] = [];
for (const playerId in scores) {
cells.push((
<KadiCell
key={"cell_total_" + blockId + "_" + playerId}
location={{ blockId, cellId: "total"}}
fieldType={FieldType.total}
playerId={playerId}
value={scores[playerId]}
onCellEdit={() => {}}
/>
));
}
return <>{cells}</>;
};
export default KadiBlockTotalRow;

308
src/Components/KadiBoard.tsx Executable file
View File

@@ -0,0 +1,308 @@
import React, {ReactElement, ReactNode, useContext} from "react";
import PlayerScoreCard, {CellLocation, PlayerScoreCardJSONRepresentation} from "../Classes/PlayerScoreCard";
import {BlockDef, GameSchema, getGameSchemaById} from "../static/rulesets";
import {formatUnicorn, LocaleContext} from "../static/strings";
import {CellFlag} from "../static/enums";
import {ScoreCellValue} from "../Classes/ScoreCell";
import {CaretakerSet} from "../Classes/Caretaker";
import {GameSettings} from "./GameSetup";
import Settings from "../static/settings.json";
import axios from "axios";
import {Button, Container, Header, Icon, Image} from "semantic-ui-react";
import logo from "../static/images/kadi.png";
import KadiGrandTotalRow from "./KadiGrandTotalRow";
import KadiBlockRenderer from "./KadiBlockRenderer";
import {KadiCellDisplayValue} from "./KadiCell";
export interface CellScores {
[key: string]: KadiCellDisplayValue;
}
export interface BlockScores {
[key: string]: CellScores;
bonuses: CellScores;
subtotals: CellScores;
totals: CellScores;
}
export interface CellEventResponse {
value: ScoreCellValue | CellFlag;
playerId: string;
location: CellLocation;
}
export interface KadiBoardProps {
settings: GameSettings;
returnToSetup: () => void;
}
interface KadiBoardState {
scoreSheet: ScoreSheet;
playerIds: string[];
showResults: boolean;
savingGame: boolean;
}
interface ScoreSheet {
[key: string]: PlayerScoreCard;
}
class KadiBoard extends React.Component<KadiBoardProps, KadiBoardState> {
private readonly gameSchema: GameSchema;
private readonly caretaker: CaretakerSet;
state: KadiBoardState;
constructor(props: KadiBoardProps) {
super(props);
this.gameSchema = getGameSchemaById(this.props.settings.ruleset);
this.state = {
scoreSheet: this.generateNewScoreSheet(this.props.settings.playerIds),
playerIds: this.props.settings.playerIds,
showResults: true,
savingGame: false,
};
this.caretaker = new CaretakerSet(
Settings.maxHistoryLength,
...this.state.playerIds.map(
pid => this.state.scoreSheet[pid]
)
);
}
private generateNewScoreSheet(playerIds: string[]): ScoreSheet {
const scoreSheet: ScoreSheet = {};
for (const playerId of playerIds) {
scoreSheet[playerId] = new PlayerScoreCard(playerId, this.gameSchema);
}
return scoreSheet;
}
private onCellEdit = (response: CellEventResponse): void => {
const newScoreSheet = this.state.scoreSheet;
KadiBoard.updateScoreSheetFromCellResponse(newScoreSheet, response);
this.setState({ scoreSheet: newScoreSheet });
this.caretaker.save();
};
private static updateScoreSheetFromCellResponse(scoreSheet: ScoreSheet, response: CellEventResponse): void {
const playerScoreCard = scoreSheet[response.playerId];
playerScoreCard.updateCellByLocationWithValue(response.location, response.value);
}
toggleShowResults = () => {
this.setState({ showResults: !this.state.showResults });
};
private getCellDisplayValueByPlayerIdAndLocation(playerId: string, location: CellLocation): KadiCellDisplayValue {
const playerSheet = this.state.scoreSheet[playerId];
let cellValue: KadiCellDisplayValue = playerSheet.getCellScoreByLocation(location);
cellValue = playerSheet.cellAtLocationIsStruck(location) ? CellFlag.strike : cellValue;
return cellValue;
};
private getBlockSubtotalByPlayerId(blockId: string, playerId: string): number {
return this.state.scoreSheet[playerId].getBlockSubTotalById(blockId);
}
private getBlockTotalByPlayerId(blockId: string, playerId: string): number {
return this.state.scoreSheet[playerId].getBlockTotalById(blockId);
}
private getTotalForPlayer(playerId: string): number {
return this.state.scoreSheet[playerId].getTotal();
}
private playerHasBonusForBlock(playerId: string, blockId: string): boolean {
return this.state.scoreSheet[playerId].blockWithIdHasBonus(blockId);
}
private undo(): void {
this.caretaker.undo();
this.forceUpdate();
}
private redo(): void {
this.caretaker.redo();
this.forceUpdate();
}
private getJSONRepresentationForBoard(): string {
const JSONRepresentation: PlayerScoreCardJSONRepresentation[] = [];
for (const playerId in this.state.scoreSheet) {
JSONRepresentation.push(this.state.scoreSheet[playerId].getJSONRepresentation());
}
return JSON.stringify(JSONRepresentation);
}
private canSave(): boolean {
for (const playerId in this.state.scoreSheet) {
if (!this.state.scoreSheet[playerId].filledOut()) {
return false;
}
}
return true;
}
private saveGame: () => void = async () => {
this.setState({savingGame: true});
axios.post(Settings.rootUrl + "/api/savegame",
this.getJSONRepresentationForBoard(),
{headers: {"Content-Type": "application/json"}}
)
.then(response => this.onGameSave(response.data))
.catch(error => this.onSaveError(error))
.finally(() => this.setState({ savingGame: false }));
};
private onGameSave = (serverResponse: string) => {
console.log("Response:", serverResponse);
};
private onSaveError = (error: any) => {
console.log("Error saving:", error);
};
render(): ReactNode {
const Locale = this.context.strings;
const rows: ReactElement[] = [];
for (const block of this.gameSchema.blocks) {
const scores: BlockScores = {subtotals: {}, bonuses: {}, totals: {}};
for (const cell of block.cells) {
scores[cell.id] = {};
}
this.state.playerIds.forEach(pid => {
scores.totals[pid] = this.getBlockTotalByPlayerId(block.id, pid);
scores.bonuses[pid] = this.playerHasBonusForBlock(pid, block.id);
scores.subtotals[pid] = this.getBlockSubtotalByPlayerId(block.id, pid);
for (const cell of block.cells) {
scores[cell.id][pid] = this.getCellDisplayValueByPlayerIdAndLocation(
pid, { blockId: block.id, cellId: cell.id });
}
});
rows.push(
<KadiBlockRenderer
key={"block" + block.id}
blockSchema={block}
showResults={this.state.showResults}
onCellEdit={this.onCellEdit}
scores={scores}
/>
);
}
const grandTotals: CellScores = {};
this.state.playerIds.forEach(pid =>
grandTotals[pid] = this.getTotalForPlayer(pid)
);
rows.push(
<KadiGrandTotalRow
key={"grandTotalRow"}
showResults={this.state.showResults}
scores={grandTotals}
toggleShowResults={this.toggleShowResults}
/>
);
return (
<div className="game">
<table className="kadiTable">
<thead>
<tr>
<th colSpan={this.state.playerIds.length + 1}>
<Header inverted={true} >
<Image spaced={true} size={"small"} src={logo} />
<Header.Content>
<span className={"brandname"}>K&nbsp;&nbsp;A&nbsp;&nbsp;D&nbsp;&nbsp;I</span>
</Header.Content>
</Header>
</th>
</tr>
</thead>
<tbody>
<ColumnHeadersRow playerIds={this.state.playerIds} />
{rows}
</tbody>
</table>
<Container>
<div className="buttonContainer">
<Button.Group>
<Button
secondary={true}
disabled={!this.caretaker.undosLeft()}
onClick={() => this.undo()}
>
<Icon name={"undo"} />
{Locale.buttons.undoButton}
</Button>
<Button
secondary={true}
disabled={!this.caretaker.redosLeft()}
onClick={() => this.redo()}
>
<Icon name={"redo"} />
{Locale.buttons.redoButton}
</Button>
</Button.Group>
</div>
<div className="buttonContainer">
<Button
icon={true}
labelPosition={"left"}
secondary={true}
onClick={() => this.props.returnToSetup()}
>
<Icon name={"arrow alternate circle left"}/>
{Locale.buttons.returnToSetupButton}
</Button>
<Button
icon={true}
labelPosition={"left"}
primary={true}
disabled={!this.canSave()}
onClick={() => this.saveGame()}
loading={this.state.savingGame}
>
<Icon name={"save"} />
{Locale.buttons.saveGameButton}
</Button>
</div>
</Container>
</div>
);
}
}
KadiBoard.contextType = LocaleContext;
interface ColumnHeadersRowProps {
playerIds: string[];
}
const ColumnHeadersRow: React.FunctionComponent<ColumnHeadersRowProps> = ({ playerIds }) => {
const Locale = useContext(LocaleContext).strings;
const columnHeaders: ReactNode[] = [(
<td className="topLeftBlankCell" key={"blank_header"}>
{Locale.headers.rowLabels}
</td>
)];
for (const playerId of playerIds) {
columnHeaders.push(
<td className="playerNameCell" key={"header" + playerId}>
{playerId}
</td>
);
}
return (
<tr className="columnHeaderRow">
{columnHeaders}
</tr>
);
};
export default KadiBoard;

256
src/Components/KadiCell.tsx Executable file
View File

@@ -0,0 +1,256 @@
import React, {ChangeEvent, FocusEvent, ReactNode, KeyboardEvent} from "react";
import {CellFlag, FieldType} from "../static/enums";
import {ScoreCellValue} from "../Classes/ScoreCell";
import {CellEventResponse} from "./KadiBoard";
import {CellLocation} from "../Classes/PlayerScoreCard";
import {useLongPress} from "./useLongPress";
export type KadiCellDisplayValue = ScoreCellValue | CellFlag.strike;
export interface KadiCellProps {
location: CellLocation;
fieldType: FieldType;
playerId: string;
value: KadiCellDisplayValue;
showResults?: boolean;
onCellEdit: (response: CellEventResponse) => void;
}
interface KadiCellState {}
class KadiCell extends React.Component<KadiCellProps, KadiCellState> {
private readonly standardTimeoutTimeMs: number;
constructor(props: KadiCellProps) {
super(props);
this.standardTimeoutTimeMs = 400;
}
shouldComponentUpdate(
nextProps: Readonly<KadiCellProps>,
nextState: Readonly<KadiCellState>,
nextContext: any): boolean {
return nextProps.value != this.props.value;
}
updateCell = (value: ScoreCellValue): void => {
const response: CellEventResponse = {
value: value,
playerId: this.props.playerId,
location: this.props.location,
};
this.props.onCellEdit(response);
};
strikeCell = (): void => {
const response: CellEventResponse = {
value: CellFlag.strike,
playerId: this.props.playerId,
location: this.props.location,
};
this.props.onCellEdit(response);
};
unstrikeCell = (): void => {
const response: CellEventResponse = {
value: CellFlag.unstrike,
playerId: this.props.playerId,
location: this.props.location,
};
this.props.onCellEdit(response);
};
render(): ReactNode {
const {
fieldType,
value,
} = this.props;
const propsForEditableCell = {
timeoutMs: this.standardTimeoutTimeMs,
updateCell: this.updateCell,
strikeCell: this.strikeCell,
value: value as ScoreCellValue,
};
if (value === CellFlag.strike) {
return <StrikeKadiCell unstrikeCell={this.unstrikeCell} />;
}
else {
switch (fieldType) {
case FieldType.bonus:
case FieldType.subtotal:
case FieldType.total:
case FieldType.globalTotal:
return (
<GenericResultsKadiCell
classNameString={fieldType}
value={value}
/>
);
case FieldType.bool:
return <BoolKadiCell {...propsForEditableCell}/>;
case FieldType.multiplier:
return <MultipleKadiCell {...propsForEditableCell}/>;
case FieldType.number:
return <NumberKadiCell {...propsForEditableCell}/>;
case FieldType.yahtzee:
return <YahtzeeKadiCell {...propsForEditableCell}/>;
}
}
}
}
interface StandardKadiCellProps {
value: ScoreCellValue,
}
interface StrikeKadiCellProps {
unstrikeCell: () => void,
}
interface ResultsKadiCellProps extends StandardKadiCellProps {
}
interface UpdateableKadiCellProps extends StandardKadiCellProps {
updateCell: (updateVal: ScoreCellValue) => void,
}
interface LongPressStrikeKadiCellProps extends StandardKadiCellProps {
timeoutMs: number,
strikeCell: () => void,
}
interface GenericResultsKadiCellProps extends ResultsKadiCellProps {
classNameString: string;
}
type EditableKadiCellProps = UpdateableKadiCellProps & LongPressStrikeKadiCellProps;
const NumberKadiCell: React.FunctionComponent<EditableKadiCellProps> = ({ strikeCell, updateCell, value , timeoutMs}) => {
const [beingEdited, setBeingEdited] = React.useState(false);
const [currentEditValue, setCurrentEditValue] = React.useState("");
const strikeCellOnLongPress = useLongPress(strikeCell, timeoutMs);
const displayText: string = beingEdited ? currentEditValue : value.toString();
const handleFocus = (e: FocusEvent<HTMLInputElement>) => {
setBeingEdited(true);
};
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setCurrentEditValue(e.target.value);
if (e.target.value == "") {
strikeCell();
endInput();
}
};
const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
submitInput(e.target.value);
};
const handleKeyUp = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
submitInput(e.currentTarget.value);
}
};
const submitInput = (input: string) => {
updateCell(Number(input));
endInput();
};
const endInput = () => {
setBeingEdited(false);
setCurrentEditValue("");
};
return (
<td className={"kadiCell editable numberField"}>
<div className={"numberField"}>
<input
type={"number"}
onFocus={handleFocus}
onBlur={handleBlur}
onInput={handleChange}
onChange={handleChange}
onKeyUp={handleKeyUp}
value={displayText}
className={"numberField"}
onAuxClick={strikeCell}
{...strikeCellOnLongPress}
/>
</div>
</td>
)
};
const YahtzeeKadiCell: React.FunctionComponent<EditableKadiCellProps> = ({value, timeoutMs, strikeCell, updateCell}) => {
const handleClick = (): void => updateCell(true);
const strikeCellOnLongPress = useLongPress(strikeCell, timeoutMs);
return (
<td
className={"kadiCell editable yahtzeeField"}
onClick={handleClick}
{...strikeCellOnLongPress}
>
<div className={"yahtzeeField"}>
{value}
</div>
</td>
)
};
const BoolKadiCell: React.FunctionComponent<EditableKadiCellProps> = ({value, timeoutMs, strikeCell, updateCell}) => {
const handleClick = (): void => updateCell(true);
const strikeCellOnLongPress = useLongPress(strikeCell, timeoutMs);
return (
<td
className={"kadiCell editable boolField " + (value ? "checked" : "unchecked")}
>
<div
className="clickableArea"
onClick={handleClick}
{...strikeCellOnLongPress}
/>
</td>
)
};
const MultipleKadiCell: React.FunctionComponent<EditableKadiCellProps> = ({value, timeoutMs, strikeCell, updateCell}) => {
const handleClick = (): void => updateCell(true);
const strikeCellOnLongPress = useLongPress(strikeCell, timeoutMs);
return (
<td
className={"kadiCell editable multipleField"}
onClick={handleClick}
{...strikeCellOnLongPress}
>
<div className={"multipleField"}>
{value}
</div>
</td>
)
};
const GenericResultsKadiCell: React.FunctionComponent<GenericResultsKadiCellProps> = ({value, classNameString}) => {
return (
<td className={"kadiCell " + classNameString}>
<div className={classNameString}>
{value}
</div>
</td>
)
};
const StrikeKadiCell: React.FunctionComponent<StrikeKadiCellProps> = ({unstrikeCell}) => {
const updateCell = () => unstrikeCell();
return (
<td
className={"kadiCell strikeCell"}
onClick={updateCell}
/>
);
};
export default KadiCell;

View File

@@ -0,0 +1,33 @@
import {CellLocation} from "../Classes/PlayerScoreCard";
import {FieldType} from "../static/enums";
import React, {ReactElement} from "react";
import KadiCell from "./KadiCell";
import {CellEventResponse, CellScores} from "./KadiBoard";
interface KadiEditableRowCellsProps {
location: CellLocation;
fieldType: FieldType;
scores: CellScores;
onCellEdit(res: CellEventResponse): void;
}
const KadiEditableRowCells: React.FunctionComponent<KadiEditableRowCellsProps> = ({ location, fieldType, scores, onCellEdit }) => {
const cells: ReactElement[] = [];
for (const playerId in scores) {
cells.push((
<KadiCell
key={"cell" + location.cellId + location.blockId + playerId}
location={location}
fieldType={fieldType}
playerId={playerId}
value={scores[playerId]}
onCellEdit={onCellEdit}
/>
));
}
return <>{cells}</>;
};
export default KadiEditableRowCells;

View File

@@ -0,0 +1,47 @@
import React, {ReactNode} from "react";
import {LocaleContext} from "../static/strings";
import KadiCell from "./KadiCell";
import {FieldType} from "../static/enums";
import {Icon} from "semantic-ui-react";
import {CellScores} from "./KadiBoard";
interface KadiGrandTotalRowProps {
showResults: boolean;
scores: CellScores;
toggleShowResults(): void;
}
const KadiGrandTotalRow: React.FunctionComponent<KadiGrandTotalRowProps> = ({ showResults, toggleShowResults, scores}) => {
const cells: ReactNode[] = [];
const Locale = React.useContext(LocaleContext).strings;
for (const playerId in scores) {
cells.push((
<KadiCell
key={"cell_grandtotal_" + playerId}
location={{blockId: "global", cellId: "grandTotal"}}
fieldType={FieldType.globalTotal}
playerId={playerId}
value={scores[playerId]}
onCellEdit={() => {}}
/>
));
}
return (
<tr
key={"rowContGrandTotal"}
className={"kadiRow " + FieldType.globalTotal + (showResults ? "" : " hideResults")}
>
<td
onClick={toggleShowResults}
className="kadiCell rowLabelCell"
>
{Locale.rowLabels.globalTotal}
<Icon className={"showResultsIcon"} name={showResults ? "hide" : "unhide"} />
</td>
{cells}
</tr>
);
};
export default KadiGrandTotalRow;

45
src/Components/useLongPress.ts Executable file
View File

@@ -0,0 +1,45 @@
import React from "react";
interface useLongPressReturnProps {
onMouseDown: () => void,
onTouchStart: () => void,
onMouseUp: () => void,
onMouseLeave: () => void,
onTouchEnd: () => void,
}
export const useLongPress: (onLongPress: () => void, timeoutMs: number) => useLongPressReturnProps = (
onLongPress: () => void,
timeoutMs: number
) => {
const [doingLongPress, updateDoingLongPress] = React.useState(false);
React.useEffect(() => {
let timerId: number = 0;
if (doingLongPress) {
timerId = window.setTimeout(onLongPress, timeoutMs);
}
else {
window.clearTimeout(timerId);
}
return () => {
window.clearTimeout(timerId);
};
}, [doingLongPress]);
const startLongPress = React.useCallback(() => {
updateDoingLongPress(true);
}, []);
const stopLongPress = React.useCallback(() => {
updateDoingLongPress(false);
}, []);
return {
onMouseDown: startLongPress,
onTouchStart: startLongPress,
onMouseUp: stopLongPress,
onMouseLeave: stopLongPress,
onTouchEnd: stopLongPress,
};
};

16
src/filetypes.d.ts vendored Executable file
View File

@@ -0,0 +1,16 @@
declare module '*.jpg' {
const value: any;
export = value;
}
declare module '*.gif' {
const value: any;
export = value;
}
declare module '*.png' {
const value: any;
export = value;
}
declare module '*.css' {
const value: any;
export = value;
}

18
src/index.tsx Executable file
View File

@@ -0,0 +1,18 @@
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "./filetypes.d";
ReactDOM.render((
<React.StrictMode>
<App />
</React.StrictMode>
),
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

7
src/logo.svg Executable file
View File

@@ -0,0 +1,7 @@
svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

141
src/serviceWorker.js Executable file
View File

@@ -0,0 +1,141 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}

5
src/setupTests.js Executable file
View File

@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';

418
src/static/css/game.css Executable file
View File

@@ -0,0 +1,418 @@
:root {
--bg-border: #333;
--bg-cells: #fff;
--bg-cell-hover: #f3f3f3;
--text-color-input: #000;
--default-field-height: 30px;
--default-field-width: 60px;
--thick-border: 3px solid var(--bg-border);
--thicker-border: 10px solid var(--bg-border);
--outer-radius: 10px;
--default-font-family: Arial;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
position: absolute;
background-color: #e0e0e0 !important;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
* {
box-sizing: border-box;
}
input[type="text"],
input[type="number"] {
border: none;
}
@font-face {
font-family: "Athiti";
font-style: normal;
font-weight: 300;
font-display: swap;
src: url("../fonts/Athiti-ExtraLight.ttf") format("truetype");
}
.brandname {
font-family: "Athiti", monospace;
}
/****************************************\
|* Game *|
\****************************************/
.game {
padding-top: 20px;
padding-bottom: 20px;
width: 100%;
}
.game > table * {
line-height: normal;
user-select: none;
}
.playerNameCell,
.topLeftBlankCell {
font-size: large;
text-align: center;
padding: 8px;
}
.rowLabelCell {
font-size: large;
padding: 8px;
}
.kniffelTable {
margin-left: auto;
margin-right: auto;
border: var(--thick-border);
background-color: var(--bg-border);
border-radius: var(--outer-radius);
}
.kniffelCell,
.rowLabelCell,
.playerNameCell,
.topLeftBlankCell {
background-color: var(--bg-cells);
}
.kniffelCell.editable {
background-color: var(--bg-cells);
transition: background-color 100ms;
}
.kniffelCell.editable:hover {
background-color: var(--bg-cell-hover);
}
tr.subtotalField > .kniffelCell {
border-top: var(--thick-border);
}
tr.totalField > .kniffelCell,
.playerNameCell,
.topLeftBlankCell {
border-top: var(--thick-border);
border-bottom: var(--thick-border);
}
.topLeftBlankCell,
.rowLabelCell {
border-right: var(--thick-border);
}
.kniffelTable > thead {
font-size: xx-large;
text-align: center;
background-color: var(--bg-border);
color: var(--bg-cells);
}
div.subtotalField,
div.totalField,
div.bonusField,
div.globalTotalField,
div.yahtzeeField,
div.multipleField,
div.numberField {
width: var(--default-field-width);
height: var(--default-field-height);
margin: auto;
font-size: 30px;
line-height: 100%;
text-align: center;
color: var(--text-color-input);
font-family: var(--default-font-family);
}
input.numberField {
background: none;
padding: 0;
width: var(--default-field-width);
height: var(--default-field-height);
margin: auto;
font-size: 30px;
line-height: 100%;
text-align: center;
color: var(--text-color-input);
font-family: var(--default-font-family);
-moz-appearance: textfield;
}
input.numberField::-webkit-outer-spin-button,
input.numberField::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* bottom curves inside */
.game tr:last-child > td:last-child {
border-bottom-right-radius: var(--outer-radius);
}
.game tr:last-child > td:first-child {
border-bottom-left-radius: var(--outer-radius);
}
/**/
.boolField {
background-color: white;
position: relative;
}
.boolField.checked {
background-color: palegreen;
color: forestgreen;
transition: background-color 100ms, color 100ms;
}
.boolField.checked:hover {
background-color: #bfb;
color: #3a3;
}
.boolField .clickableArea {
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.boolField.unchecked::after {
content: "";
box-sizing: border-box;
}
.boolField.checked::after {
content: "✔";
box-sizing: border-box;
font-family: Arial, sans-serif;
position: absolute;
top: 0;
left: 0;
width: 100%;
text-align: center;
font-size: 35px;
}
.strikeCell {
background-color: #eebbbb;
text-align: center;
font-size: 30px;
color: darkred;
transition: background-color 100ms, color 100ms;
position: relative;
}
.strikeCell::after {
content: "✘";
box-sizing: border-box;
font-family: Arial, sans-serif;
position: absolute;
top: 0;
left: 0;
width: 100%;
text-align: center;
}
.strikeCell:hover {
color: #a11;
background-color: #fcc;
}
.game .buttonContainer {
margin: 10px;
text-align: center;
}
div.totalField,
div.bonusField,
div.subtotalField,
div.globalTotalField {
transition: filter 200ms;
}
.hideResults > td > div {
filter: blur(6px);
}
.showResultsIcon {
float: right;
}
.globalTotalField > .rowLabelCell {
cursor: pointer;
}
/****************************************\
|* Setup Screen *|
\****************************************/
.gameSetup {
}
.setupFormContainer {
padding-top: 20px;
margin-left: auto;
margin-right: auto;
width: 360px;
}
.setupForm {
height: 100%;
padding: 30px;
background-color: var(--bg-border);
border-radius: var(--outer-radius);
display: grid;
align-content: space-between;
box-shadow: 2px 2px 7px 0 rgba(0,0,0,0.3);
}
.setupForm > * {
margin-top: 10px;
margin-bottom: 10px;
}
.setupForm > *:first-child {
margin-top: 0;
}
.setupForm > *:last-child {
margin-bottom: 0;
}
.optionGroupTitleContainer {
padding: 0 0 10px 0;
}
.optionGroupTitle {
font-weight: bold;
font-size: large;
color: white;
}
.optionList {
box-shadow: inset 1px 1px 5px 0 rgba(0,0,0,0.4);
background-color: white;
color: var(--bg-border);
padding: 10px;
border-radius: 5px;
text-align: center;
display: grid;
align-content: space-evenly;
}
.option {
cursor: pointer;
z-index: 0;
padding: 10px;
height: 40px;
font-weight: normal;
font-size: medium;
background: transparent;
position: relative;
transition: background 200ms;
}
.option:first-child,
.option.selected:first-child > .selectorBox {
border-radius: 5px 5px 0 0;
}
.option:last-child,
.option.selected:last-child > .selectorBox {
border-radius: 0 0 5px 5px;
}
.option:only-child,
.option.selected:only-child > .selectorBox {
border-radius: 5px;
}
.option:hover {
background: #eee;
}
.option.selected:hover {
background: none;
}
@keyframes growFromMiddle {
from {height: 0; top: 20px;}
to {height: 40px; top: 0;}
}
.option.selected > .selectorBox {
z-index: -1;
height: 40px;
width: 100%;
position: absolute;
top: 0;
left: 0;
background-color: lightblue;
animation-name: growFromMiddle;
animation-duration: 100ms;
animation-timing-function: linear;
transition: background-color 200ms;
}
.option.selected:hover > .selectorBox {
background-color: #b7e4f5;
}
.playerOption {
cursor: default;
text-align: left;
}
.playerOption .trashButton {
cursor: pointer;
height: 20px;
width: 20px;
right: 10px;
top: 10px;
position: absolute;
background-size: contain;
background-image: url(../images/trash.png);
background-repeat: no-repeat;
}
.playButtonContainer {
text-align: center;
}
.playButton {
width: 200px;
height: 50px;
font-size: 20px;
}
.option.inputPlayerField {
padding: 0;
}
.option.faded input {
color: #999;
}
.option input {
width: 100%;
height: 100%;
font-size: medium;
background: transparent;
padding-left: 10px;
}

21
src/static/enums.ts Executable file
View File

@@ -0,0 +1,21 @@
export enum FieldType {
number = "numberField",
bool = "boolField",
bonus = "bonusField",
subtotal = "subtotalField",
globalTotal = "globalTotalField",
total = "totalField",
yahtzee = "yahtzeeField",
multiplier = "multiplierField",
}
export enum CellFlag {
strike = "cellFlagStrike",
unstrike = "cellFlagUnstrike",
}
export enum SupportedLang {
en = "en",
de = "de",
it = "it",
}

Binary file not shown.

BIN
src/static/fonts/Athiti-Light.ttf Executable file

Binary file not shown.

BIN
src/static/images/kadi.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

BIN
src/static/images/trash.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

296
src/static/rulesets.ts Executable file
View File

@@ -0,0 +1,296 @@
import { FieldType } from "./enums";
export const defaultCellValues = {
[FieldType.number]: 0,
[FieldType.bool]: false,
[FieldType.subtotal]: 0,
[FieldType.total]: 0,
[FieldType.bonus]: 0,
[FieldType.yahtzee]: 0,
[FieldType.multiplier]: 0,
};
// ----- gameSchema interface definitions
export interface GameSchema {
id: string;
label: string;
blocks: BlockDef[];
}
export type BlockDef = BonusBlockDef | NoBonusBlockDef;
export interface NoBonusBlockDef extends DefaultBlockDef {
hasBonus: false;
}
export interface BonusBlockDef extends DefaultBlockDef {
hasBonus: true;
bonusScore: number;
bonusFor: number;
}
interface DefaultBlockDef {
id: string;
label: string;
cells: CellDef[];
}
export type CellDef = BoolCellDef | MultiplierCellDef | NumberCellDef | YahtzeeCellDef;
export interface BoolCellDef extends DefaultCellDef {
fieldType: FieldType.bool;
score: number;
}
export interface MultiplierCellDef extends DefaultCellDef {
fieldType: FieldType.multiplier;
multiplier: number;
maxMultiples: number;
}
export interface YahtzeeCellDef extends DefaultCellDef {
fieldType: FieldType.yahtzee;
score: number;
maxYahtzees: number;
}
export interface NumberCellDef extends DefaultCellDef {
fieldType: FieldType.number;
}
interface DefaultCellDef {
id: string;
label: string;
}
// ----- Predefined sets
const defaultDiceCount = 5;
const gameSchemas: GameSchema[] = [
{
id: "default_en",
label: "Standard Kadi Rules (en)",
blocks: [
{
id: "top",
label: "Upper",
hasBonus: true,
bonusScore: 35,
bonusFor: 63,
cells: [
{
id: "aces",
fieldType: FieldType.multiplier,
label: "Aces",
multiplier: 1,
maxMultiples: defaultDiceCount,
},
{
id: "twos",
fieldType: FieldType.multiplier,
label: "Twos",
multiplier: 2,
maxMultiples: defaultDiceCount,
},
{
id: "threes",
fieldType: FieldType.multiplier,
label: "Threes",
multiplier: 3,
maxMultiples: defaultDiceCount,
},
{
id: "fours",
fieldType: FieldType.multiplier,
label: "Fours",
multiplier: 4,
maxMultiples: defaultDiceCount,
},
{
id: "fives",
fieldType: FieldType.multiplier,
label: "Fives",
multiplier: 5,
maxMultiples: defaultDiceCount,
},
{
id: "sixes",
fieldType: FieldType.multiplier,
label: "Sixes",
multiplier: 6,
maxMultiples: defaultDiceCount,
}
]
},
{
id: "bottom",
label: "Lower",
hasBonus: false,
cells: [
{
id: "three_kind",
fieldType: FieldType.number,
label: "Three of a Kind",
},
{
id: "four_kind",
fieldType: FieldType.number,
label: "Four of a Kind",
},
{
id: "full_house",
fieldType: FieldType.bool,
label: "Full House",
score: 25,
},
{
id: "sml_straight",
fieldType: FieldType.bool,
label: "Small Straight",
score: 30,
},
{
id: "lg_straight",
fieldType: FieldType.bool,
label: "Large Straight",
score: 40,
},
{
id: "yahtzee",
fieldType: FieldType.yahtzee,
label: "Kadi",
score: 50,
maxYahtzees: 5,
},
{
id: "chance",
fieldType: FieldType.number,
label: "Chance",
}
]
}
]
},
{
id: "default_de",
label: "Standard-Kadi-Regelwerk (de)",
blocks: [
{
id: "top",
label: "Oben",
hasBonus: true,
bonusScore: 35,
bonusFor: 63,
cells: [
{
id: "aces",
fieldType: FieldType.multiplier,
label: "Einser",
multiplier: 1,
maxMultiples: defaultDiceCount,
},
{
id: "twos",
fieldType: FieldType.multiplier,
label: "Zweier",
multiplier: 2,
maxMultiples: defaultDiceCount,
},
{
id: "threes",
fieldType: FieldType.multiplier,
label: "Dreier",
multiplier: 3,
maxMultiples: defaultDiceCount,
},
{
id: "fours",
fieldType: FieldType.multiplier,
label: "Vierer",
multiplier: 4,
maxMultiples: defaultDiceCount,
},
{
id: "fives",
fieldType: FieldType.multiplier,
label: "Fünfer",
multiplier: 5,
maxMultiples: defaultDiceCount,
},
{
id: "sixes",
fieldType: FieldType.multiplier,
label: "Sechser",
multiplier: 6,
maxMultiples: defaultDiceCount,
}
]
},
{
id: "bottom",
label: "Unten",
hasBonus: false,
cells: [
{
id: "three_kind",
fieldType: FieldType.number,
label: "Dreierpasch",
},
{
id: "four_kind",
fieldType: FieldType.number,
label: "Viererpasch",
},
{
id: "full_house",
fieldType: FieldType.bool,
label: "Full House",
score: 25,
},
{
id: "sml_straight",
fieldType: FieldType.bool,
label: "Kleine Straße",
score: 30,
},
{
id: "lg_straight",
fieldType: FieldType.bool,
label: "Große Straße",
score: 40,
},
{
id: "yahtzee",
fieldType: FieldType.yahtzee,
label: "Kadi",
score: 50,
maxYahtzees: 5,
},
{
id: "chance",
fieldType: FieldType.number,
label: "Chance",
}
]
}
]
}
];
export function getGameSchemaById(schemaId: string): GameSchema {
for (const schema of gameSchemas) {
if (schema.id === schemaId) {
return schema;
}
}
throw new RangeError("No such GameSchema with id '" + schemaId + "'!");
}
export interface SchemaListing {
id: string;
label: string;
}
export function getSchemaListings(): SchemaListing[] {
return gameSchemas.map(s => ({ id: s.id, label: s.label }));
}

7
src/static/settings.json Executable file
View File

@@ -0,0 +1,7 @@
{
"lang": "en",
"players": [],
"ruleset": "default_en",
"maxHistoryLength": 256,
"rootUrl": "/kadi"
}

137
src/static/strings.ts Executable file
View File

@@ -0,0 +1,137 @@
import Settings from "./settings.json";
import React from "react";
import {SupportedLang} from "./enums";
// Formats strings
// formatUnicorn("Hello, {0}!", ["World"]) becomes "Hello, World!"
// {0} is the first entry in args, {1} the second, etc.
export function formatUnicorn(fmt: string, ...args: string[]): string {
if (!fmt.match(/^(?:(?:(?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{[0-9]+\}))+$/)) {
throw new Error('Invalid formatUnicorn input string.');
}
return fmt.replace(/((?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{([0-9]+)\})/g, (m: string, str: string, index: number) => {
if (str) {
return str.replace(/(?:{{)|(?:}})/g, m => m[0]);
} else {
if (index >= args.length) {
throw new Error('Argument index is out of range in formatUnicorn call.');
}
return args[index];
}
});
}
export const LanguageNames: Record<SupportedLang, string> = {
en: "English",
de: "Deutsch",
it: "Italiano",
};
const IntlStrings = {
en: {
rowLabels: {
subtotal: "Subtotal",
bonus: "Bonus",
blockTotal: "Total for {0}",
globalTotal: "Total"
},
headers: {
rowLabels: "",
},
buttons: {
showHideResultsButton: {
show: "Show results",
hide: "Hide results",
},
undoButton: "Undo",
redoButton: "Redo",
returnToSetupButton: "Back to setup",
saveGameButton: "Save game",
savingGame: "Saving...",
},
languageNames: {
en: "English",
de: "German",
it: "Italian"
},
setupScreen: {
selectLanguage: "Change language:",
selectRuleset: "Choose a ruleset to play with:",
startGame: "Start playing!",
noPlayersEntered: "No players! Click here to add one...",
clickToAddPlayer: "Click here to add a player...",
players: "Players:",
},
},
de: {
rowLabels: {
subtotal: "Zwischensumme",
bonus: "Bonus",
blockTotal: "Summe {0}",
globalTotal: "Gesamt"
},
headers: {
rowLabels: "",
},
buttons: {
showHideResultsButton: {
show: "Ergebnisse einblenden",
hide: "Ergebnisse ausblenden",
},
undoButton: "Rückgängig",
redoButton: "Wiederholen",
returnToSetupButton: "Zurück zu Einstellungen",
saveGameButton: "Spiel speichern",
savingGame: "Wird gespeichert...",
},
setupScreen: {
selectLanguage: "Sprache ändern:",
selectRuleset: "Wähle ein Regelwerk aus:",
startGame: "Spiel starten!",
noPlayersEntered: "Leer! Hier tippen und hinzufügen...",
clickToAddPlayer: "Zum Hinzufügen hier tippen...",
players: "Mitspieler:",
},
},
it: {
rowLabels: {
subtotal: "Subtotale",
bonus: "Bonus",
blockTotal: "Totale {0}",
globalTotal: "Totale generale"
},
headers: {
rowLabels: "",
},
buttons: {
showHideResultsButton: {
show: "Mostra totali",
hide: "Nasconda totali",
},
undoButton: "Annullo",
redoButton: "Ripristino",
returnToSetupButton: "Torna a impostazioni",
saveGameButton: "Salva gioco",
savingGame: "Salva...",
},
setupScreen: {
selectLanguage: "Cambia lingua:",
selectRuleset: "Sceglia il regolamento:",
startGame: "Gioca!",
noPlayersEntered: "Nessuno! Inserire un nome qui...",
clickToAddPlayer: "Clicca per inserire un altro nome...",
players: "Giocatori:",
},
},
} as const;
export const localeDefaultVal = {
strings: IntlStrings[Settings.lang as SupportedLang],
changeLang: changeLang,
};
export const LocaleContext = React.createContext(localeDefaultVal);
export function changeLang(newLang: SupportedLang): void {
localeDefaultVal.strings = IntlStrings[newLang];
}

23
tsconfig.json Executable file
View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "esnext",
"target": "es5",
"jsx": "react",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"lib": [
"dom",
"dom.iterable",
"esnext"
]
}
}

33
tslint.json Executable file
View File

@@ -0,0 +1,33 @@
{
"defaultSeverity": "error",
"extends": [
"tslint-react"
],
"jsRules": {
},
"rules": {
"jsx-no-multiline-js": false,
"member-access": false,
"prefer-for-of": true,
"prefer-const": true,
"prefer-readonly": true,
"typedef": [
true,
"call-signature",
"property-declaration"
],
"ordered-imports": false,
"quotemark": false,
"no-console": false,
"jsx-no-lambda": false
},
"rulesDirectory": [
],
"linterOptions": {
"exclude": [
"dist/**/*.js",
"config/**/*.js",
"node_modules/**/*.ts"
]
}
}

51
webpack.config.js Executable file
View File

@@ -0,0 +1,51 @@
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.tsx",
mode: "development",
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /(node_modules|bower_components|\.d\.ts$)/,
use: [
{
loader: "babel-loader",
options: { presets: ["@babel/env"] },
},
{ loader: "ts-loader" },
],
},
{
test: /\.d\.ts$/,
loader: 'ignore-loader'
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|jpe?g|gif|ttf|woff2?|eot|svg)$/i,
use: [
{
loader: 'file-loader',
},
],
}
]
},
resolve: { extensions: [".tsx", ".ts", ".js", "*"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/kadi/game/static/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};