chg: dev: outsource the Grid generation and interactions to the backend #4
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import React from 'react';
|
||||
import Grid from './grid/grid';
|
||||
import GridControl from './grid/grid-control';
|
||||
|
||||
class MineSeeker extends React.Component {
|
||||
@@ -41,54 +40,10 @@ class MineSeeker extends React.Component {
|
||||
.css('line-height', ($field.width() - 2) + 'px');
|
||||
}
|
||||
|
||||
/**
|
||||
* STEP
|
||||
*/
|
||||
makePointsCalcAndStep(coords) {
|
||||
let users = this.refs.gridControl.refs.userControl,
|
||||
activePlayer = users.state.activePlayer ? 'blue' : 'red',
|
||||
inactivePlayer = users.state.activePlayer ? 'red' : 'blue',
|
||||
redPoints = 'red' === activePlayer
|
||||
? users.refs[activePlayer].state.mines
|
||||
: users.refs[inactivePlayer].state.mines,
|
||||
bluePoints = 'blue' === activePlayer
|
||||
? users.refs[activePlayer].state.mines
|
||||
: users.refs[inactivePlayer].state.mines;
|
||||
|
||||
this.refs.gridControl.stepEvent(coords);
|
||||
|
||||
let mineCache = this.refs.gridControl.state.foundUserMineCache;
|
||||
redPoints += 'red' === activePlayer ? mineCache : 0;
|
||||
bluePoints += 'blue' === activePlayer ? mineCache : 0;
|
||||
|
||||
return { red: redPoints, blue: bluePoints };
|
||||
}
|
||||
|
||||
/**
|
||||
* START
|
||||
*/
|
||||
makeGameStart(payload) {
|
||||
this.refs.gridControl.refs.userControl.setState({ activePlayer: 1 });
|
||||
|
||||
this.refs.gridControl.refs.userControl.refs.red.setState({
|
||||
name: '' !== payload.users.red ? payload.users.red : payload.users.redAnon,
|
||||
});
|
||||
|
||||
this.refs.gridControl.refs.userControl.refs.blue.setState({
|
||||
name: '' !== payload.users.blue ? payload.users.blue : payload.users.blueAnon,
|
||||
desc: 'blue' === this.refs.gridControl.state.webPlayer
|
||||
? this.refs.gridControl.state.desc.you
|
||||
: this.refs.gridControl.state.desc.buddy,
|
||||
active: true,
|
||||
});
|
||||
|
||||
this.refs.gridControl.setState({ overlay: false });
|
||||
}
|
||||
|
||||
/**
|
||||
* THE END
|
||||
*/
|
||||
makeGameEndIfItEnds(bluePoints, redPoints, resign = false) {
|
||||
makeGameEndIfItEnds(bluePoints, redPoints, resign = false, leftMines = []) {
|
||||
let redWins = 25 < redPoints,
|
||||
blueWins = 25 < bluePoints;
|
||||
|
||||
@@ -103,7 +58,7 @@ class MineSeeker extends React.Component {
|
||||
});
|
||||
}
|
||||
|
||||
this.refs.gridControl.showLeftMines();
|
||||
this.refs.gridControl.showLeftMines(leftMines);
|
||||
this.refs.gridControl.refs.userControl.setState({ activePlayer: false });
|
||||
this.refs.gridControl.refs.userControl.refs.red.setState({ desc: '' });
|
||||
this.refs.gridControl.refs.userControl.refs.blue.setState({ desc: '' });
|
||||
@@ -196,16 +151,19 @@ class MineSeeker extends React.Component {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Opponent's step arrived via Mercure — apply the server-resolved revealed cells.
|
||||
*/
|
||||
wTopic(payload) {
|
||||
if (this.refs.gridControl.state.webPlayer !== payload.data.player) {
|
||||
if (null === payload.data.resign) {
|
||||
'dev' === this.state.env && console.warn(payload.user + ' has been stepped to coords: ' + payload.data.coords[0] + ', ' + payload.data.coords[1]);
|
||||
'dev' === this.state.env && console.warn('Opponent stepped: Auto-Step process');
|
||||
'dev' === this.state.env && console.warn(
|
||||
payload.user + ' stepped to ' + payload.data.coords[0] + ',' + payload.data.coords[1],
|
||||
);
|
||||
|
||||
this.refs.gridControl.refs.userControl.setState({ bombSelected: payload.data.bomb });
|
||||
|
||||
let points = this.makePointsCalcAndStep(payload.data.coords);
|
||||
this.makeGameEndIfItEnds(points.blue, points.red);
|
||||
this.refs.gridControl.applyStep(payload.data);
|
||||
this.makeGameEndIfItEnds(payload.data.bluePoints, payload.data.redPoints, false, payload.data.leftMines);
|
||||
} else {
|
||||
this.resignProcess(payload.data.resign);
|
||||
}
|
||||
@@ -216,13 +174,8 @@ class MineSeeker extends React.Component {
|
||||
// Mercure / SSE connection
|
||||
// ------------------------------------------------------------------ //
|
||||
|
||||
/**
|
||||
* Dispatches every incoming SSE message.
|
||||
* Distinguishes subscription events, game-step events, and disconnect events
|
||||
* using the same payload shape as the former WAMP broadcast.
|
||||
*/
|
||||
handleMercureMessage(payload) {
|
||||
let isTopicEvent = 'undefined' !== typeof payload.data;
|
||||
handleMercureMessage(payload) {
|
||||
let isTopicEvent = 'undefined' !== typeof payload.data;
|
||||
let isNotUnsubscribe = 'undefined' === typeof payload.msg;
|
||||
|
||||
if (isTopicEvent) {
|
||||
@@ -244,9 +197,9 @@ class MineSeeker extends React.Component {
|
||||
}
|
||||
|
||||
openEventSource() {
|
||||
const wrapper = document.getElementById('mine-wrapper');
|
||||
const hubUrl = wrapper.dataset.mercureHubUrl;
|
||||
const subscriberJwt = wrapper.dataset.mercureSubscriberJwt;
|
||||
const wrapper = document.getElementById('mine-wrapper');
|
||||
const hubUrl = wrapper.dataset.mercureHubUrl;
|
||||
const subscriberJwt = wrapper.dataset.mercureSubscriberJwt;
|
||||
|
||||
const url = new URL(hubUrl, window.location.origin);
|
||||
url.searchParams.append('topic', this.state.channel);
|
||||
@@ -279,9 +232,16 @@ class MineSeeker extends React.Component {
|
||||
};
|
||||
}
|
||||
|
||||
wInit(gridServer, gridClient) {
|
||||
/**
|
||||
* Initialise the grid control with an empty 16×16 grid.
|
||||
* For inherited games, previously revealed cells are applied after the grid renders.
|
||||
*/
|
||||
wInit(revealedCells = []) {
|
||||
// 16×16 grid of null — cells are filled in lazily as they are revealed by the server
|
||||
let emptyGrid = Array.from({ length: 16 }, () => Array(16).fill(null));
|
||||
|
||||
this.refs.gridControl.setState({
|
||||
grid: this.state.gameInherited ? gridServer : gridClient,
|
||||
grid: emptyGrid,
|
||||
channel: this.state.channel,
|
||||
desc: {
|
||||
buddy: (
|
||||
@@ -314,9 +274,30 @@ class MineSeeker extends React.Component {
|
||||
</div>
|
||||
) : '',
|
||||
renderGridFields: this.state.gameAssoc,
|
||||
}, () => {
|
||||
// After the grid fields are rendered, apply any historically revealed cells
|
||||
revealedCells.forEach(cell => this.refs.gridControl.applyRevealedCell(cell, cell.player));
|
||||
});
|
||||
}
|
||||
|
||||
makeGameStart(payload) {
|
||||
this.refs.gridControl.refs.userControl.setState({ activePlayer: 1 });
|
||||
|
||||
this.refs.gridControl.refs.userControl.refs.red.setState({
|
||||
name: '' !== payload.users.red ? payload.users.red : payload.users.redAnon,
|
||||
});
|
||||
|
||||
this.refs.gridControl.refs.userControl.refs.blue.setState({
|
||||
name: '' !== payload.users.blue ? payload.users.blue : payload.users.blueAnon,
|
||||
desc: 'blue' === this.refs.gridControl.state.webPlayer
|
||||
? this.refs.gridControl.state.desc.you
|
||||
: this.refs.gridControl.state.desc.buddy,
|
||||
active: true,
|
||||
});
|
||||
|
||||
this.refs.gridControl.setState({ overlay: false });
|
||||
}
|
||||
|
||||
/** POST /api/game/join — register this player, broadcast subscription event via Mercure */
|
||||
joinGame() {
|
||||
return fetch('/api/game/join/' + this.state.gameAssoc, {
|
||||
@@ -325,13 +306,13 @@ class MineSeeker extends React.Component {
|
||||
}).catch(e => 'dev' === this.state.env && console.error('Join error', e));
|
||||
}
|
||||
|
||||
/** POST /api/game/step — persist a move and fan it out via Mercure */
|
||||
/** POST /api/game/step — persist a move, fan it out via Mercure, and return revealed cells */
|
||||
publishStep(dataPack) {
|
||||
return fetch('/api/game/step/' + this.state.gameAssoc, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(dataPack),
|
||||
}).catch(e => 'dev' === this.state.env && console.error('Step error', e));
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ //
|
||||
@@ -340,16 +321,14 @@ class MineSeeker extends React.Component {
|
||||
|
||||
async componentDidMount() {
|
||||
if (!this.state.connectionLost) {
|
||||
let gridClient = this.state.gameInherited ? null : new Grid().state.grid;
|
||||
|
||||
try {
|
||||
if (this.state.gameInherited) {
|
||||
/** Fetch existing grid and player info */
|
||||
const resp = await fetch('/api/game/connect/' + this.state.gameAssoc);
|
||||
const b64 = await resp.text();
|
||||
/** Fetch existing player info and previously revealed cells */
|
||||
const resp = await fetch('/api/game/connect/' + this.state.gameAssoc);
|
||||
const b64 = await resp.text();
|
||||
const serverData = JSON.parse(window.atob(b64));
|
||||
|
||||
if ('undefined' === typeof serverData.grid || null === serverData.grid) {
|
||||
if ('undefined' === typeof serverData.users || null === serverData.users) {
|
||||
this.refs.gridControl.setState({
|
||||
overlay: true,
|
||||
overlayTitle: 'This channel does not exists!',
|
||||
@@ -361,21 +340,18 @@ class MineSeeker extends React.Component {
|
||||
|
||||
this.rpcUsers = serverData.users;
|
||||
this.openEventSource();
|
||||
this.wInit(serverData.grid, null);
|
||||
this.wInit(serverData.revealedCells || []);
|
||||
|
||||
} else {
|
||||
/** Create the game record with this client's grid */
|
||||
/** Create the game record — the server generates the grid */
|
||||
await fetch('/api/game/start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
grid: window.btoa(JSON.stringify(gridClient)),
|
||||
gameAssoc: this.state.gameAssoc,
|
||||
}),
|
||||
body: JSON.stringify({ gameAssoc: this.state.gameAssoc }),
|
||||
});
|
||||
|
||||
this.openEventSource();
|
||||
this.wInit(null, gridClient);
|
||||
this.wInit();
|
||||
}
|
||||
|
||||
'dev' === this.state.env && console.info('Connection initialised — joining channel');
|
||||
@@ -403,29 +379,37 @@ class MineSeeker extends React.Component {
|
||||
this.setState({ stepCache: cache });
|
||||
}
|
||||
|
||||
onClick(coords) {
|
||||
async onClick(coords) {
|
||||
let activePlayer = this.refs.gridControl.refs.userControl.state.activePlayer ? 'blue' : 'red';
|
||||
|
||||
if (this.refs.gridControl.checkFieldHasBeenNeverClicked(coords[0], coords[1])) {
|
||||
if (activePlayer === this.refs.gridControl.state.webPlayer) {
|
||||
let points = this.makePointsCalcAndStep(coords);
|
||||
this.makeGameEndIfItEnds(points.blue, points.red);
|
||||
if (!this.refs.gridControl.checkFieldHasBeenNeverClicked(coords[0], coords[1])) {
|
||||
return;
|
||||
}
|
||||
|
||||
let dataPack = {
|
||||
coords: coords,
|
||||
player: activePlayer,
|
||||
bomb: this.refs.gridControl.refs.userControl.state.bombSelected,
|
||||
redPoints: points.red,
|
||||
bluePoints: points.blue,
|
||||
resign: null,
|
||||
redExplodedBomb: 'red' === activePlayer && this.refs.gridControl.refs.userControl.state.bombSelected,
|
||||
blueExplodedBomb: 'blue' === activePlayer && this.refs.gridControl.refs.userControl.state.bombSelected,
|
||||
};
|
||||
if (activePlayer !== this.refs.gridControl.state.webPlayer) {
|
||||
return;
|
||||
}
|
||||
|
||||
!this.state.connectionLost
|
||||
? this.publishStep(dataPack)
|
||||
: this.cachePublish(dataPack);
|
||||
}
|
||||
let dataPack = {
|
||||
coords: coords,
|
||||
player: activePlayer,
|
||||
bomb: this.refs.gridControl.refs.userControl.state.bombSelected,
|
||||
resign: null,
|
||||
};
|
||||
|
||||
if (this.state.connectionLost) {
|
||||
this.cachePublish(dataPack);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.publishStep(dataPack);
|
||||
const result = await resp.json();
|
||||
|
||||
this.refs.gridControl.applyStep(result);
|
||||
this.makeGameEndIfItEnds(result.bluePoints, result.redPoints, false, result.leftMines);
|
||||
} catch (e) {
|
||||
'dev' === this.state.env && console.error('Step error', e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user