Initial Commit

This commit is contained in:
Lucas Mello 2021-05-15 16:00:26 -03:00
commit e6d570e248
33 changed files with 19224 additions and 0 deletions

3
.browserslistrc Normal file
View file

@ -0,0 +1,3 @@
> 1%
last 2 versions
not dead

5
.editorconfig Normal file
View file

@ -0,0 +1,5 @@
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true

21
.gitignore vendored Normal file
View file

@ -0,0 +1,21 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

16
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,16 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "vuejs: chrome",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}/src",
"breakOnLoad": true,
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
},
]
}

5
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,5 @@
{
"vetur.format.options.tabSize": 4,
"vetur.format.defaultFormatter.js": "vscode-typescript",
"prettier.tabWidth": 4
}

View file

@ -0,0 +1,12 @@
<template>
</template>
<script lang="ts">
import {Vue, Component, Prop, Watch} from "vue-property-decorator";
@Component
export default class $0 extends Vue {
}
</script>

29
README.md Normal file
View file

@ -0,0 +1,29 @@
# take6-viewer-svg
## Project setup
```
yarn install
```
### Compiles and hot-reloads for development
```
yarn serve
```
### Compiles and minifies for production
```
yarn build
```
### Run your unit tests
```
yarn test:unit
```
### Lints and fixes files
```
yarn lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

5
babel.config.js Normal file
View file

@ -0,0 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}

41
package.json Normal file
View file

@ -0,0 +1,41 @@
{
"name": "@gaia-project/take6-viewer",
"version": "0.3.8",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit",
"package": "vue-cli-service build --target lib src/wrapper.ts",
"prepublishOnly": "npm run package"
},
"dependencies": {
"core-js": "^3.6.5",
"lodash": "^4.17.19",
"container-engine": "workspace:../container-engine",
"vue": "^2.6.11",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2"
},
"devDependencies": {
"@types/assert": "^1.4.7",
"@types/chai": "^4.2.11",
"@types/lodash": "^4.14.154",
"@types/mocha": "^5.2.4",
"@vue/cli-plugin-babel": "~4.4.0",
"@vue/cli-plugin-typescript": "~4.4.0",
"@vue/cli-plugin-unit-mocha": "~4.4.0",
"@vue/cli-service": "~4.4.0",
"@vue/test-utils": "^1.0.3",
"chai": "^4.1.2",
"sass": "^1.26.5",
"sass-loader": "^8.0.2",
"typescript": "~3.9.3",
"vue-template-compiler": "^2.6.11"
},
"files": [
"src",
"dist/take6-viewer.umd.min.js",
"dist/take6-viewer.css",
"tsconfig.json"
]
}

8960
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load diff

17
public/index.html Normal file
View file

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- <link rel="icon" href="<%= BASE_URL %>favicon.ico">-->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

View file

@ -0,0 +1,19 @@
<template>
<g>
<g :transform="'rotate(' + rotate + ', 10, 5)'">
<rect width="20" height="10" :fill="color" stroke="black"></rect>
</g>
</g>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
@Component
export default class Container extends Vue {
@Prop()
color?: string;
@Prop()
rotate?: number;
}
</script>

View file

@ -0,0 +1,100 @@
<script lang="ts">
import {Vue, Component } from "vue-property-decorator";
@Component({
mounted(this: Draggable) {
this.$nextTick(() => {
const endDrag = () => this.endDrag();
const drag = (event: MouseEvent | TouchEvent) => this.drag(event);
this.htmlElement.addEventListener("mousedown", event => this.startDrag(event));
this.htmlElement.addEventListener('touchstart', event => this.startDrag(event));
this.svgElement.addEventListener('touchmove', drag);
this.svgElement.addEventListener('touchend', endDrag);
this.svgElement.addEventListener('touchleave', endDrag);
this.svgElement.addEventListener('touchcancel', endDrag);
this.$on("hook:beforeDestroy", () => this.svgElement.removeEventListener("touchmove", drag));
this.$on("hook:beforeDestroy", () => this.svgElement.removeEventListener("touchend", endDrag));
this.$on("hook:beforeDestroy", () => this.svgElement.removeEventListener("touchleave", endDrag));
this.$on("hook:beforeDestroy", () => this.svgElement.removeEventListener("touchcancel", endDrag));
this.svgElement.addEventListener("mouseleave", endDrag);
this.svgElement.addEventListener("mouseup", endDrag);
this.svgElement.addEventListener("mousemove", drag);
this.$on("hook:beforeDestroy", () => this.svgElement.removeEventListener("mouseleave", endDrag));
this.$on("hook:beforeDestroy", () => this.svgElement.removeEventListener("mouseup", endDrag));
this.$on("hook:beforeDestroy", () => this.svgElement.removeEventListener("mousemove", drag));
});
}
})
export default class Draggable extends Vue {
dragging = false;
_offset = {x: 0, y: 0};
_transform?: SVGTransform;
_dragStart?: number;
get svgElement() {
return document.querySelector("#scene") as SVGSVGElement;
}
get htmlElement() {
return this.$el as SVGGElement;
}
startDrag(evt: MouseEvent | TouchEvent) {
this.dragging = true;
this._offset = this.getMousePosition(evt);
// Get all the transforms currently on this element
const transforms: SVGTransformList = this.htmlElement.transform.baseVal;
// Ensure the first transform is a translate transform
if (transforms.numberOfItems === 0 ||
transforms.getItem(0).type !== SVGTransform.SVG_TRANSFORM_TRANSLATE) {
// Create an transform that translates by (0, 0)
const translate = this.svgElement.createSVGTransform();
translate.setTranslate(0, 0);
// Add the translation to the front of the transforms list
this.htmlElement.transform.baseVal.insertItemBefore(translate, 0);
}
// Get initial translation amount
this._transform = transforms.getItem(0);
this._offset.x -= this._transform.matrix.e;
this._offset.y -= this._transform.matrix.f;
this._dragStart = Date.now();
}
drag(evt: MouseEvent | TouchEvent) {
if (!this.dragging) {
return;
}
evt.preventDefault();
const coord = this.getMousePosition(evt);
this._transform!.setTranslate(coord.x - this._offset.x, coord.y - this._offset.y);
this.$emit("draggedTo", {x: coord.x - this._offset.x, y: coord.y - this._offset.y});
}
endDrag() {
this.dragging = false;
if (Date.now() - this._dragStart! < 250) {
this.$emit("fastClick");
}
}
getMousePosition(evt: MouseEvent | TouchEvent) {
if ((evt as TouchEvent).touches) {
evt = (evt as TouchEvent).touches[0] as any;
}
const CTM = this.svgElement.getScreenCTM()!;
return {
x: ((evt as any).clientX - CTM.e) / CTM.a,
y: ((evt as any).clientY - CTM.f) / CTM.d
};
}
}
</script>

View file

@ -0,0 +1,14 @@
<template>
<g>
<circle r="10" :fill="color" stroke="black"></circle>
</g>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
@Component
export default class Factory extends Vue {
@Prop()
color?: string;
}
</script>

759
src/components/Game.vue Normal file
View file

@ -0,0 +1,759 @@
<template>
<div class="game">
<svg viewBox="0 0 1250 650" height="700" id="scene">
<defs>
<filter id="shadow">
<feGaussianBlur stdDeviation="0.5 0.5" result="shadow" />
<feOffset dx="1" dy="1" />
</filter>
</defs>
<rect width="100%" height="100%" x="0" y="0" fill="lightblue" stroke="#000077"></rect>
<rect width="100%" height="100" x="0" y="0" fill="gray"></rect>
<rect width="390" height="220" x="860" y="430" fill="gray"></rect>
<template v-if="G">
<template v-for="(player, i) in G.players">
<PlayerBoard :key="'B' + i" :name="player.name" :color="['dodgerblue', 'red', 'yellow', 'limegreen', 'mediumorchid'][i]" :transform="`translate(${250 * i}, 100)`" />
<rect :key="'I' + i" width="390" height="41" x="860" :y="430 + i * 44" fill="none" stroke-width="3" :stroke="['dodgerblue', 'red', 'yellow', 'limegreen', 'mediumorchid'][i]"></rect>
</template>
</template>
<template v-for="ship in ships">
<Ship :key="'S' + ship.id" :rotate="ship.rotate" :color="ship.color" :transform="`translate(${ship.x}, ${ship.y})`" />
</template>
<template v-for="container in containers">
<Container :key="'C' + container.id" :rotate="container.rotate" :transform="`translate(${container.x}, ${container.y})`" :color="container.color" />
</template>
<template v-for="factory in factories">
<Factory :key="'F' + factory.id" :transform="`translate(${factory.x}, ${factory.y})`" :color="factory.color" />
</template>
<template v-for="warehouse in warehouses">
<Warehouse :key="'W' + warehouse.id" :transform="`translate(${warehouse.x}, ${warehouse.y})`" />
</template>
<template v-for="loanCard in loanCards">
<LoanCard :key="'L' + loanCard.id" :transform="`translate(${loanCard.x}, ${loanCard.y})`" />
</template>
<template v-if="G">
<PointCard :pointCard="G.players[player].pointCard" transform="translate(20, 440)" />
<text x="20" y="620">Money: ${{ G.players[player].money }}</text>
</template>
<!-- Game Info
<GameInfo :round="round" transform="translate(-190, -240)" />
Players
<PlayerLabel :player="G.players[player || 0]" :playerIndex=player :main=true :points=G.players[player||0].points transform="translate(-150, 120)" v-if="G" />
<PlaceHolder :player="player || 0" transform="translate(-220, 170)" :playerTurn="canPlayerMove(player||0)" :enabled="canPlayerMove(player||0) && !G.players[player||0].faceDownCard" v-if="G" @cardDrop="onCardDrop" />
<template v-for="(player, i) in otherPlayers">
<PlayerLabel :player="G.players[player]" :playerIndex=player :points=G.players[player].points :transform="`translate(${i <= 5 ? 173 + 115 * (i % 2) : -300}, ${i <= 5 ? -218 + 110 * Math.floor(i /2) : -218 + 110 * (i - 6)})`" :key="'label-'+player" />
<PlaceHolder :player="player" :playerTurn="canPlayerMove(player)" :key="'placehold-player-' + player" :transform="`translate(${i <= 5 ? 173 + 115 * (i % 2) : -300}, ${i <= 5 ? -163 + 110 * Math.floor(i /2) : -163 + 110 * (i - 6)})`" />
</template>
Board
<template v-for="row in 4">
<template v-for="rowPos in 6">
<PlaceHolder
:key="`board-${row-1}-${rowPos-1}`"
:row=row-1
:rowPos=rowPos-1
:danger="rowPos===6"
:transform="`translate(${-203 + (rowPos-1) * 55}, ${((row - 1) - 1.5) * 80 - 75})`"
:enabled="isPlaceholderEnabled(row-1, rowPos-1)"
@cardDrop="onCardDrop"
/>
</template>
</template>
All the cards
<Card v-for="(card, i) in [...sortedHandCards].reverse()" :card="card" :key="card.number || `hand-${i}`" :targetState="handTargetState(handCards.length - 1 - i)" @fastClick="onCardDrop(card, {player})" />
<template v-if="G">
<template v-for="(player, i) in G.players">
<Card v-if="player.faceDownCard" :card="player.faceDownCard" :key="player.faceDownCard.number || 'player-'+i" :targetState="facedownTargetState(i)" @fastClick="onCardDrop(player.faceDownCard, {player: i, autoChooseRow: true})" />
</template>
</template>
<template v-for="row in 4">
<template v-for="rowPos in 6">
<Card v-if="G && G.rows[row-1][rowPos-1]" :card="G.rows[row-1][rowPos-1]" :key="G.rows[row-1][rowPos-1].number || 'board-card-'+row+'-'+rowPos" :targetState="boardTargetState(row-1, rowPos-1)" />
</template>
</template> -->
<use xlink:href="#dragged" />
</svg>
</div>
</template>
<script lang="ts">
import { Vue, Component, Prop, Watch, Provide, ProvideReactive, } from "vue-property-decorator";
import { LogItem, AvailableMoves, Phase, reconstructState, } from "container-engine";
import type { GameState } from "container-engine";
import { EventEmitter } from "events";
import { range, isEqual, groupBy } from "lodash";
import { Piece, UIData } from "../types/ui-data";
import { logToText } from "../utils/log-to-text";
import { ContainerColor, ShipPosition } from "container-engine/src/gamestate";
import PlayerBoard from "./PlayerBoard.vue";
import Container from "./Container.vue";
import Factory from "./Factory.vue";
import Warehouse from "./Warehouse.vue";
import LoanCard from "./LoanCard.vue";
import PointCard from "./PointCard.vue";
import Ship from "./Ship.vue";
@Component({
created(this: Game) {
this.emitter.on("addLog", this.addLog.bind(this));
this.emitter.on("replayStart", () => {
this.emitter.emit("replay:info", {
start: 1,
current: this.G!.log.length,
end: this._futureState!.log.length,
});
this.paused = true;
});
this.emitter.on("replayTo", (to: number) => {
if (to < this.G!.log.length) {
const baseState = {
players: this.G!.players.map((player, i) => ({
id: i,
pointCard: player.pointCard,
factories: player.factories,
warehouses: player.warehouses,
ship: { containers: [], shipPosition: ShipPosition.OpenSea },
containersOnFactoryStore: player.containersOnFactoryStore,
containersOnWarehouseStore: [],
containersOnIsland: [],
money: 20,
loans: 0,
produced: [],
availableMoves: null,
lastMove: null,
actions: 0,
isDropped: false,
bid: 0,
additionalBid: 0,
})),
currentPlayer: this.G!.currentPlayer,
containersLeft: this.G!.containersLeft,
factoriesLeft: this.G!.factoriesLeft,
warehousesLeft: this.G!.warehousesLeft,
auctioningPlayer: -1,
highestBidders: [],
phase: Phase.Move,
options: this.G!.options,
log: [],
seed: "",
round: 1
};
this.replaceState(
reconstructState(
baseState,
this._futureState!.log.slice(0, to)
),
false
);
}
if (this.G!.log.length + 1 === to) {
this.advanceLog();
} else if (this.G!.log.length + 1 < to) {
this.replaceState(
reconstructState(
this.G!,
this._futureState!.log.slice(this.G!.log.length, to)
),
false
);
}
this.emitter.emit("replay:info", {
start: 1,
current: this.G!.log.length,
end: this._futureState!.log.length,
});
});
this.emitter.on("replayEnd", () => {
this.paused = false;
this.emitter.emit("fetchState");
});
},
components: {
PlayerBoard,
Container,
Factory,
Warehouse,
LoanCard,
PointCard,
Ship
},
})
export default class Game extends Vue {
@Prop()
private state?: GameState;
@Prop()
@ProvideReactive()
player?: number;
@Prop()
emitter!: EventEmitter;
paused = false;
@Provide()
ui: UIData = {
cards: {},
placeholders: { rows: [], players: [] },
waitingAnimations: 0,
};
@Provide()
communicator: EventEmitter = new EventEmitter();
@ProvideReactive()
G?: GameState | null = null;
_futureState?: GameState;
containers: Piece[] = [];
factories: Piece[] = [];
warehouses: Piece[] = [];
loanCards: Piece[] = [];
ships: Piece[] = [];
addLog({ log, availableMoves, start }: { log: LogItem[]; start: number; availableMoves: AvailableMoves[] }) {
console.log("adding log...");
this._pendingAvailableMoves = null;
if (start > this._futureState!.log.length) {
this.emitter.emit("fetchState");
return;
}
if (log.length === 0) {
this.loadAvailableMoves(availableMoves);
return;
}
// edge case when we do a move and another player just did a move
if (
start === this._futureState!.log.length &&
start > 0 &&
isEqual(log[0], this._futureState!.log.slice(-1)[0])
) {
this.emitter.emit("fetchState");
return;
}
this._futureState!.log = [
...this._futureState!.log.slice(0, start),
...log,
];
this._pendingAvailableMoves = {
index: start + log.length,
availableMoves: availableMoves,
};
this.updateUI();
}
@Watch("state", { immediate: true })
onStateChanged(state: GameState) {
this.replaceState(state);
}
replaceState(state: GameState, replaceFuture = true) {
console.log("replace state", state, replaceFuture);
if (replaceFuture) {
this._futureState = state;
}
this.G = JSON.parse(JSON.stringify(state));
if (this.G) {
this.emitter.emit(
"uplink:replaceLog",
[
...this.G!.log.map((x: LogItem) => logToText(this.G!, x)),
].flat(1)
);
}
this.createComponents();
}
createComponents() {
let pieceId = 0;
// if (this.G) {
// let player = this.G.players[0];
// player.ship.shipPosition = ShipPosition.Island;
// player.ship.containers = [ContainerColor.White, ContainerColor.Black, ContainerColor.Orange, ContainerColor.Tan, ContainerColor.Brown];
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnFactoryStore.push({ containerColor: ContainerColor.Black, price: 2 });
// player.containersOnFactoryStore.push({ containerColor: ContainerColor.Black, price: 2 });
// player.containersOnFactoryStore.push({ containerColor: ContainerColor.Black, price: 2 });
// player.containersOnFactoryStore.push({ containerColor: ContainerColor.Black, price: 2 });
// player.containersOnFactoryStore.push({ containerColor: ContainerColor.Tan, price: 2 });
// player = this.G.players[1];
// player.ship.shipPosition = ShipPosition.Island;
// player.ship.containers = [ContainerColor.White, ContainerColor.Black, ContainerColor.Orange, ContainerColor.Tan, ContainerColor.Brown];
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Orange);
// player.containersOnIsland.push(ContainerColor.Black);
// player.containersOnIsland.push(ContainerColor.White);
// player.containersOnIsland.push(ContainerColor.Brown);
// player = this.G.players[2];
// player.ship.shipPosition = ShipPosition.Island;
// player.ship.containers = [ContainerColor.White, ContainerColor.Black, ContainerColor.Orange, ContainerColor.Tan, ContainerColor.Brown];
// player.containersOnIsland.push(ContainerColor.Orange);
// player.containersOnIsland.push(ContainerColor.Orange);
// player.containersOnIsland.push(ContainerColor.Orange);
// player.containersOnIsland.push(ContainerColor.White);
// player.containersOnIsland.push(ContainerColor.Brown);
// player = this.G.players[3];
// player.ship.shipPosition = ShipPosition.Island;
// player.ship.containers = [ContainerColor.White, ContainerColor.Black, ContainerColor.Orange, ContainerColor.Tan, ContainerColor.Brown];
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player = this.G.players[4];
// player.ship.shipPosition = ShipPosition.Island;
// player.ship.containers = [ContainerColor.White, ContainerColor.Black, ContainerColor.Orange, ContainerColor.Tan, ContainerColor.Brown];
// player.containersOnWarehouseStore.push({ containerColor: ContainerColor.Brown, price: 4 });
// player.containersOnWarehouseStore.push({ containerColor: ContainerColor.Brown, price: 5 });
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Tan);
// player.containersOnIsland.push(ContainerColor.Black);
// player.containersOnIsland.push(ContainerColor.Black);
// player.containersOnIsland.push(ContainerColor.White);
// }
// Containers
this.containers = [];
this.G?.players.forEach((player, pi) => {
let grouped = groupBy(player.containersOnFactoryStore, c => c.price);
Object.keys(grouped).forEach(price => {
grouped[price].forEach((container, ci) => {
this.containers.push({
id: pieceId++,
x: 8 + pi * 250 + (container.price - 1) * 48 + (ci % 2) * 20,
y: 160 + Math.floor(ci / 2) * 10,
rotate: 0,
color: container.containerColor.toString() });
});
});
grouped = groupBy(player.containersOnWarehouseStore, c => c.price);
Object.keys(grouped).forEach(price => {
grouped[price].forEach((container, ci) => {
this.containers.push({
id: pieceId++,
x: 8 + pi * 250 + (container.price - 2) * 48 + (ci % 2) * 20,
y: 250 + Math.floor(ci / 2) * 10,
rotate: 0,
color: container.containerColor.toString() });
});
});
let lastColor;
let offset = 0;
player.containersOnIsland.sort().forEach((containerColor, ci) => {
if (containerColor !== lastColor)
offset += 10;
this.containers.push({ id: pieceId++, x: 860 + offset + 12 * ci, y: 445 + 44 * pi, rotate: 90, color: containerColor.toString() });
lastColor = containerColor;
});
player.ship.containers.forEach((containerColor, ci) => {
switch (player.ship.shipPosition) {
case ShipPosition.OpenSea:
this.containers.push({ id: pieceId++, x: 525 - 12 * ci, y: 445 + pi * 44, rotate: 90, color: containerColor.toString() });
break;
case ShipPosition.Island:
this.containers.push({ id: pieceId++, x: 825 - 12 * ci, y: 445 + pi * 44, rotate: 90, color: containerColor.toString() });
break;
case ShipPosition.Player0:
this.containers.push({ id: pieceId++, x: 31 + 62 * (pi - 1), y: 320 + 12 * ci, rotate: 0, color: containerColor.toString() });
break;
case ShipPosition.Player1:
this.containers.push({ id: pieceId++, x: 281 + 62 * (pi > 1 ? pi - 1 : pi), y: 320 + 12 * ci, rotate: 0, color: containerColor.toString() });
break;
case ShipPosition.Player2:
this.containers.push({ id: pieceId++, x: 531 + 62 * (pi > 2 ? pi - 1 : pi), y: 320 + 12 * ci, rotate: 0, color: containerColor.toString() });
break;
case ShipPosition.Player3:
this.containers.push({ id: pieceId++, x: 781 + 62 * (pi > 3 ? pi - 1 : pi), y: 320 + 12 * ci, rotate: 0, color: containerColor.toString() });
break;
case ShipPosition.Player4:
this.containers.push({ id: pieceId++, x: 1031 + 62 * (pi > 4 ? pi - 1 : pi), y: 320 + 12 * ci, rotate: 0, color: containerColor.toString() });
break;
}
});
});
if (this.G?.containersLeft) {
let c = 0;
let lastColor;
this.G?.containersLeft.sort().forEach(containerColor => {
if (lastColor !== containerColor) {
c = 0;
}
const offset = 120 * Object.values(ContainerColor).indexOf(containerColor);
this.containers.push({ id: pieceId++, x: 10 + offset + 22 * (c % 5), y: 40 + Math.floor(c / 5) * 12, rotate: 0, color: containerColor.toString() });
lastColor = containerColor;
c++
});
}
// Factories
this.factories = [];
this.G?.players.forEach((player, pi) => {
player.factories.forEach((factory, i) => {
this.factories.push({ id: pieceId++, x: 28 + pi * 250 + i * 48, y: 140, color: factory.toString() });
});
});
if (this.G?.factoriesLeft) {
let c = 0;
let lastColor;
this.G?.factoriesLeft.sort().forEach(containerColor => {
if (lastColor !== containerColor) {
c = 0;
}
const offset = 120 * Object.values(ContainerColor).indexOf(containerColor);
this.factories.push({ id: pieceId++, x: 20 + offset + 22 * (c % 5), y: 20 + Math.floor(c / 5) * 12, color: containerColor.toString() });
lastColor = containerColor;
c++
});
}
// Warehouses
this.warehouses = [];
this.G?.players.forEach((player, pi) => {
for (let c = 0; c < player.warehouses; c++) {
this.warehouses.push({ id: pieceId++, x: 13 + pi * 250 + c * 48, y: 210 });
}
});
if (this.G?.warehousesLeft) {
for (let c = 0; c < this.G.warehousesLeft; c++) {
this.warehouses.push({ id: pieceId++, x: 620 + 32 * (c % 13), y: 15 + Math.floor(c / 13) * 32 });
}
}
// Loan Cards
this.loanCards = [];
this.G?.players.forEach((player, pi) => {
for (let c = 0; c < player.loans; c++) {
this.loanCards.push({ id: pieceId++, x: 205 + pi * 250 + c * 5, y: 130 - c * 15 });
}
});
this.loanCards.push({ id: pieceId++, x: 1050, y: 15 });
// Ships
this.ships = [];
this.G?.players.forEach((player, pi) => {
const color = ["dodgerblue", "red", "yellow", "limegreen", "mediumorchid"][pi];
switch (player.ship.shipPosition) {
case ShipPosition.OpenSea:
this.ships.push({ id: pieceId++, x: 500, y: 410 + pi * 44, rotate: 90, color });
break;
case ShipPosition.Island:
this.ships.push({ id: pieceId++, x: 800, y: 410 + pi * 44, rotate: 90, color });
break;
case ShipPosition.Player0:
this.ships.push({ id: pieceId++, x: 26 + 62 * (pi - 1), y: 305, rotate: 0, color });
break;
case ShipPosition.Player1:
this.ships.push({ id: pieceId++, x: 276 + 62 * (pi > 1 ? pi - 1 : pi), y: 305, rotate: 0, color });
break;
case ShipPosition.Player2:
this.ships.push({ id: pieceId++, x: 526 + 62 * (pi > 2 ? pi - 1 : pi), y: 305, rotate: 0, color });
break;
case ShipPosition.Player3:
this.ships.push({ id: pieceId++, x: 776 + 62 * (pi > 3 ? pi - 1 : pi), y: 305, rotate: 0, color });
break;
case ShipPosition.Player4:
this.ships.push({ id: pieceId++, x: 1026 + 62 * (pi > 4 ? pi - 1 : pi), y: 305, rotate: 0, color });
break;
}
});
}
get round() {
return this.G?.round;
}
get otherPlayers() {
if (!this.G) {
return [];
}
return range(0, this.G.players.length).filter(pl => pl !== (this.player || 0));
}
canPlayerMove(player: number) {
return !!this.G?.players[player]?.availableMoves;
}
onContainerDrop(container: ContainerColor, { player, row, rowPos, autoChooseRow }: { player?: number; row?: number; rowPos?: number; autoChooseRow?: boolean }) {
console.log("card drop");
if (this.player === undefined || (player !== undefined && player !== this.player)) {
return;
}
const commands = this.G!.players[this.player].availableMoves!;
if (!commands) {
return;
}
if (this.G!.log.length !== this._futureState!.log.length) {
return;
}
this.G!.players[this.player].availableMoves = null;
console.log(player, row, rowPos, autoChooseRow);
// if (player !== undefined && !autoChooseRow) {
// this._futureState!.log.push({
// player: this.player!,
// type: "move",
// move: { name: MoveName.ChooseCard, data: card },
// });
// this.emitter.emit("move", {
// name: MoveName.ChooseCard,
// data: card,
// });
// } else {
// this._futureState!.log.push({
// player: this.player!,
// type: "move",
// move: {
// name: MoveName.PlaceCard,
// data: commands.placeCard!.find((item) => item.row === row)!,
// },
// });
// this.emitter.emit("move", {
// name: MoveName.PlaceCard,
// data: commands.placeCard!.find((item) => item.row === row),
// });
// }
this.updateUI();
}
loadAvailableMoves(availableMoves: AvailableMoves[]) {
for (let i = 0; i < availableMoves.length; i++) {
this.G!.players[i].availableMoves = availableMoves[i];
}
this._pendingAvailableMoves = null;
}
@Watch("ui.waitingAnimations")
updateUI() {
if (this.ui.waitingAnimations > 0) {
return;
}
if (this.animationQueue.length > 0) {
this.animationQueue.shift()!();
setTimeout(() => this.updateUI());
return;
}
if (this.paused) {
return;
}
if (this.G!.log.length < this._futureState!.log.length) {
this.advanceLog();
setTimeout(() => this.updateUI());
return;
}
if (this._pendingAvailableMoves && this._pendingAvailableMoves.index === this.G!.log.length) {
console.log("loading available moves", JSON.stringify(this._pendingAvailableMoves));
this.loadAvailableMoves(this._pendingAvailableMoves.availableMoves);
}
}
advanceLog() {
console.log("advancing log", this.G!.log.length, this._futureState!.log.length);
const logItem = this._futureState!.log[this.G!.log.length];
this.G!.log.push(logItem);
this.emitter.emit("uplink:addLog", logToText(this.G!, logItem));
this.delay(1);
switch (logItem.type) {
case "phase":
return;
case "move": {
const { player, move } = logItem;
switch (move.name) {
// case MoveName.ChooseCard: {
// console.log("choosing card", player);
// this.G!.players[player].faceDownCard = move.data;
// this.delay(200);
// if (player === (this.player || 0)) {
// this.G!.players[this.player!].hand = this.handCards!.filter(card => card.number !== move.data.number);
// } else {
// this.G!.players[player].hand.shift();
// }
// return;
// }
// case MoveName.PlaceCard: {
// console.log("placing card", player);
// const card = this.G!.players[player].faceDownCard!;
// this.G!.players[player].faceDownCard = null;
// if (move.data.replace) {
// // put new card on 6th spot
// this.G!.rows[move.data.row][5] = card;
// this.G!.rows = [...this.G!.rows];
// this.queueAnimation(() => {
// console.log("delaying before taking row");
// this.delay(200);
// });
// this.queueAnimation(() => {
// console.log("Taking row");
// this.G!.players[player].points += sumBy(
// this.G!.rows[move.data.row].slice(0, 5),
// "points"
// );
// this.G!.rows[move.data.row] = [];
// this.G!.rows[move.data.row][5] = card;
// this.G!.rows = [...this.G!.rows];
// console.log("delaying after taking row");
// this.delay(300);
// });
// // Then move card to correct spot
// this.queueAnimation(() => {
// this.G!.rows[move.data.row] = [card];
// this.G!.rows = [...this.G!.rows];
// });
// } else {
// this.G!.rows[move.data.row].push(card);
// this.G!.rows = [...this.G!.rows];
// }
// return;
// }
default:
return;
}
}
case "event": {
const { event } = logItem;
switch (event.name) {
// case GameEventName.RevealCards: {
// const cards = event.cards;
// for (let player = 0; player < cards.length; player++) {
// this.G!.players[player].faceDownCard =
// cards[player];
// }
// this.delay(200);
// return;
// }
// case GameEventName.RoundStart: {
// console.log(JSON.parse(JSON.stringify(event)));
// this.G!.rows = event.cards.board.map((card) => [
// card,
// ]) as [ICard[], ICard[], ICard[], ICard[]];
// for (let i = 0; i < this.G!.players.length; i++) {
// this.G!.players[i].hand = event.cards.players[i];
// }
// return;
// }
default:
return;
}
}
}
}
delay(ms: number) {
this.ui.waitingAnimations += 1;
setTimeout(() => { this.ui.waitingAnimations = Math.max(this.ui.waitingAnimations - 1, 0); }, ms);
}
@Watch("ui.waitingAnimations")
onAnimationNumberChanged() {
console.log("waiting animations", this.ui.waitingAnimations, this._futureState!.log.length, this.state!.log.length);
}
queueAnimation(anim: Function) {
this.animationQueue.push(anim);
}
_pendingAvailableMoves: { index: number; availableMoves: AvailableMoves[]; } | null = null;
animationQueue: Array<Function> = [];
}
</script>
<style lang="scss">
.game {
background-color: white;
display: flex;
align-items: center;
flex-direction: column;
}
#scene {
max-height: 100%;
flex-grow: 1;
}
body,
html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
text {
font-family: "Arial";
pointer-events: none;
dominant-baseline: central;
}
</style>

View file

@ -0,0 +1,24 @@
<template>
<g :class="['game-info']"> >
<text>Round: {{round}}</text>
</g>
</template>
<script lang="ts">
import {Vue, Component, Prop, Watch} from "vue-property-decorator";
@Component
export default class GameInfo extends Vue {
@Prop()
round?: number;
}
</script>
<style lang="scss">
.game-info {
text {
font-size: 12px;
}
}
</style>

View file

@ -0,0 +1,15 @@
<template>
<g>
<rect width="30" height="60" fill="royalblue" stroke="white" stroke-width="2" rx="2"></rect>
<g transform="translate(33, -10) rotate(280, 15, 30)">
<text text-anchor="middle" fill="white">Loan</text>
</g>
</g>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class LoanCard extends Vue {
}
</script>

View file

@ -0,0 +1,63 @@
<template>
<g>
<rect width="250" height="20" x="0" y="0" :fill="color"></rect>
<text x="5" y="10" font-weight="600" fill="black">{{ name }}</text>
<rect width="250" height="180" x="0" y="20" fill="gray"></rect>
<rect width="20" height="80" x="0" y="200" fill="gray"></rect>
<rect width="20" height="80" x="62" y="200" fill="gray"></rect>
<rect width="20" height="80" x="124" y="200" fill="gray"></rect>
<rect width="20" height="80" x="186" y="200" fill="gray"></rect>
<circle r="14" cx="28" cy="40" fill="none" stroke="lightgray"></circle>
<text text-anchor="middle" x="28" y="40" fill="lightgray">-</text>
<circle r="14" cx="76" cy="40" fill="none" stroke="lightgray"></circle>
<text text-anchor="middle" x="76" y="40" fill="lightgray">6</text>
<circle r="14" cx="124" cy="40" fill="none" stroke="lightgray"></circle>
<text text-anchor="middle" x="124" y="40" fill="lightgray">9</text>
<circle r="14" cx="172" cy="40" fill="none" stroke="lightgray"></circle>
<text text-anchor="middle" x="171" y="40" fill="lightgray">12</text>
<rect x="8" y="60" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="28" y="90" fill="lightgray">1</text>
<rect x="56" y="60" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="76" y="90" fill="lightgray">2</text>
<rect x="104" y="60" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="124" y="90" fill="lightgray">3</text>
<rect x="152" y="60" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="172" y="90" fill="lightgray">4</text>
<rect x="8" y="105" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="28" y="125" fill="lightgray">-</text>
<rect x="56" y="105" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="76" y="125" fill="lightgray">4</text>
<rect x="104" y="105" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="124" y="125" fill="lightgray">5</text>
<rect x="152" y="105" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="172" y="125" fill="lightgray">6</text>
<rect x="200" y="105" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="220" y="125" fill="lightgray">7</text>
<rect x="8" y="150" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="28" y="180" fill="lightgray">2</text>
<rect x="56" y="150" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="76" y="180" fill="lightgray">3</text>
<rect x="104" y="150" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="124" y="180" fill="lightgray">4</text>
<rect x="152" y="150" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="172" y="180" fill="lightgray">5</text>
<rect x="200" y="150" width="40" height="40" fill="none" stroke="lightgray"></rect>
<text text-anchor="middle" x="220" y="180" fill="lightgray">6</text>
</g>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
@Component
export default class PlayerBoard extends Vue {
@Prop()
color?: string;
@Prop()
name?: string;
}
</script>

View file

@ -0,0 +1,53 @@
<template>
<g :class="['player-label', {main}]">
<text style="filter: url(#shadow); fill: white" class="shadow" >{{player.name || `Player ${playerIndex + 1}`}}</text>
<text class="player-name">{{player.name || `Player ${playerIndex + 1}`}}</text>
<text class="points" :y="main ? 13 : 11.5" style="stroke: #ffffff33;">{{player.points}}</text>
<text class="points" :y="main ? 13 : 11.5">{{player.points}}</text>
</g>
</template>
<script lang="ts">
import {Vue, Component, Prop, Watch} from "vue-property-decorator";
import type {Player} from "container-engine";
@Component
export default class PlayerLabel extends Vue {
@Prop({default: false})
main!: boolean;
@Prop()
player!: Player;
@Prop()
playerIndex!: number;
}
</script>
<style lang="scss">
.player-label {
&.main {
fill: orange;
}
&.main .player-name {
font-size: 12px;
}
&.main .shadow {
font-size: 12px;
opacity: 0.4;
}
.player-name, .shadow {
font-size: 11px;
}
.shadow {
opacity: 0.2;
}
.points {
font-size: 10px;
}
}
</style>

View file

@ -0,0 +1,25 @@
<template>
<g>
<rect width="100" height="160" fill="silver" stroke="white" stroke-width="2" rx="2"></rect>
<rect x="20" y="15" width="20" height="10" :fill="pointCard.containerValues[0].containerColor" stroke="black"></rect>
<text x="70" y="20" text-anchor="middle">10</text>
<rect x="20" y="45" width="20" height="10" :fill="pointCard.containerValues[1].containerColor" stroke="black"></rect>
<text x="70" y="50" text-anchor="middle">5/10</text>
<rect x="20" y="75" width="20" height="10" :fill="pointCard.containerValues[2].containerColor" stroke="black"></rect>
<text x="70" y="80" text-anchor="middle">6</text>
<rect x="20" y="105" width="20" height="10" :fill="pointCard.containerValues[3].containerColor" stroke="black"></rect>
<text x="70" y="110" text-anchor="middle">4</text>
<rect x="20" y="135" width="20" height="10" :fill="pointCard.containerValues[4].containerColor" stroke="black"></rect>
<text x="70" y="140" text-anchor="middle">2</text>
</g>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
import type { PointCard as PointCardInfo } from "container-engine"
@Component
export default class PointCard extends Vue {
@Prop()
pointCard?: PointCardInfo;
}
</script>

19
src/components/Ship.vue Normal file
View file

@ -0,0 +1,19 @@
<template>
<g>
<g :transform="'rotate(' + rotate + ', 15, 40)'">
<path d="M15 0 L30 10 L30 80 L0 80 L0 10Z" :fill="color" stroke="black"></path>
</g>
</g>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
@Component
export default class Warehouse extends Vue {
@Prop()
color?: string;
@Prop()
rotate?: number;
}
</script>

View file

@ -0,0 +1,12 @@
<template>
<g>
<path d="M15 0 L30 10 L30 30 L0 30 L0 10Z" fill="dimgray" stroke="black"></path>
</g>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class Warehouse extends Vue {
}
</script>

60
src/launch.ts Normal file
View file

@ -0,0 +1,60 @@
import type { Move, GameState } from "container-engine";
import Vue from "vue";
import { EventEmitter } from 'events';
import Game from './components/Game.vue';
function launch(selector: string) {
let params: { state: null | GameState; player?: number; emitter: EventEmitter } = { state: null, emitter: new EventEmitter() };
const app = new Vue({
render: (h) => h(Game, { props: params }, [])
}).$mount(selector);
const item: EventEmitter = new EventEmitter();
let replaying = false;
params.emitter.on("move", (move: Move) => item.emit("move", move));
params.emitter.on("fetchState", () => item.emit("fetchState"));
params.emitter.on("uplink:addLog", (data: string[]) => item.emit("addLog", data));
params.emitter.on("uplink:replaceLog", (data: string[]) => item.emit("replaceLog", data));
params.emitter.on("replay:info", (info: { start: number, current: number, end: number }) => item.emit("replay:info", info));
item.addListener("state", data => {
console.log("updating state to", data);
params.state = data;
app.$forceUpdate();
app.$nextTick().then(() => item.emit('ready'))
});
item.addListener("state:updated", () => item.emit("fetchLog", { start: params.state?.log.length }));
item.addListener("player", data => {
params.player = data.index;
app.$forceUpdate();
});
item.addListener("replay:start", () => {
params.emitter.emit("replayStart");
replaying = true;
});
item.addListener("replay:to", (info) => {
params.emitter.emit("replayTo", info);
// Todo: change log ?
// item.emit("replaceLog", (store.state as any).gaiaViewer.data.moveHistory);
})
item.addListener("replay:end", () => {
params.emitter.emit("replayEnd");
replaying = false;
item.emit("fetchState");
});
item.addListener("gamelog", logData => {
if (replaying) {
return;
}
console.log("receiving log data", logData);
params.emitter.emit("addLog", { start: logData.start, log: logData.data.log, availableMoves: logData.data.availableMoves });
});
return item;
}
export default launch;

3
src/main.ts Normal file
View file

@ -0,0 +1,3 @@
import launchSelfContained from './self-contained';
launchSelfContained();

38
src/self-contained.ts Normal file
View file

@ -0,0 +1,38 @@
import launch from './launch';
import { setup, Move, move as execMove, stripSecret } from "container-engine";
import { cloneDeep } from "lodash";
function launchSelfContained(selector = "#app") {
const emitter = launch(selector);
let gameState = setup(5, {});
for (let i = 0; i < gameState.players.length; i++) {
gameState.players[i].name = `Player ${i + 1}`;
}
emitter.on("move", async (move: Move) => {
console.log("move received", JSON.stringify(move));
const index = gameState.log.length;
gameState = execMove(gameState, move, 0);
setTimeout(() =>
emitter.emit("gamelog", cloneDeep({
start: index,
data: {
log: stripSecret(gameState, 0).log.slice(index),
availableMoves: stripSecret(gameState, 0).players.map(pl => pl.availableMoves)
}
})), 200);
});
emitter.on('fetchSate', () => emitter.emit("state", cloneDeep(stripSecret(gameState, 0))));
emitter.on('addLog', data => console.log('addLog', data));
emitter.on('replaceLog', data => console.log('replaceLog', data));
emitter.emit("player", { index: 0 });
emitter.emit("state", cloneDeep(stripSecret(gameState, 0)));
}
export default launchSelfContained;

13
src/shims-tsx.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
import Vue, { VNode } from 'vue'
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any;
}
}
}

4
src/shims-vue.d.ts vendored Normal file
View file

@ -0,0 +1,4 @@
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}

20
src/types/ui-data.ts Normal file
View file

@ -0,0 +1,20 @@
import type Card from '../components/Card.vue';
import type Placeholder from '../components/Placeholder.vue';
export interface UIData {
cards: { [key: number]: Card };
placeholders: {
rows: Placeholder[][];
players: Placeholder[];
};
dragged?: Vue | null;
waitingAnimations: number;
}
export interface Piece {
id: number;
x: number;
y: number;
color?: string;
rotate?: number;
}

52
src/utils/log-to-text.ts Normal file
View file

@ -0,0 +1,52 @@
import { LogItem, GameState, MoveName, Phase, GameEventName } from 'container-engine';
export function logToText(G: GameState, item: LogItem): string[] {
return [];
// switch (item.type) {
// case "move": {
// switch (item.move.name) {
// case MoveName.ChooseCard: return [`${G.players[item.player].name} made their choice`];
// case MoveName.PlaceCard: {
// const ret = [`${G.players[item.player].name} placed their card on row ${item.move.data.row + 1}`]
// if (item.move.data.replace) {
// ret.push(`**${G.players[item.player].name} takes the row!!**`);
// }
// return ret;
// }
// }
// }
// case "phase": {
// switch (item.phase) {
// case Phase.ChooseCard:
// return ["*Time to make a choice!*"];
// case Phase.PlaceCard:
// return ["*Here we go!*"];
// }
// }
// case "event": {
// switch (item.event.name) {
// case GameEventName.GameStart:
// return ["**Game started!!**"];
// case GameEventName.GameEnd:
// return ["**Game ended!!**"];
// case GameEventName.RevealCards: {
// const ret: string[] = [];
// item.event.cards.forEach((card, i) => {
// ret.push(`${G.players[i].name} reveals ${card.number} (${new Array(card.points).fill('★').join('')})`);
// });
// return ret;
// }
// case GameEventName.RoundStart: {
// return [`**Round ${item.event.round}**`];
// }
// }
// }
// }
}

8
src/wrapper.ts Normal file
View file

@ -0,0 +1,8 @@
// Import vue component
import launch from './launch';
if (typeof window !== 'undefined') {
(window as any).container = { launch };
}
export default launch;

View file

@ -0,0 +1,13 @@
import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).to.include(msg)
})
})

42
tsconfig.json Normal file
View file

@ -0,0 +1,42 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env",
"mocha",
"chai"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}

8754
yarn.lock Normal file

File diff suppressed because it is too large Load diff