mirror of
https://github.com/danbee/chess
synced 2025-03-04 08:39:06 +00:00
83 lines
1.8 KiB
JavaScript
83 lines
1.8 KiB
JavaScript
import _ from "lodash";
|
|
import socket from "./socket";
|
|
import { Presence } from "phoenix";
|
|
import {
|
|
setUserId,
|
|
setPlayers,
|
|
setGame,
|
|
setAvailableMoves,
|
|
setOpponentStatus,
|
|
} from "../store/actions";
|
|
|
|
class Channel {
|
|
constructor(store, gameId) {
|
|
this.store = store;
|
|
this.channel = socket.channel(`game:${gameId}`, {});
|
|
this.presences = {};
|
|
|
|
this.join();
|
|
this.subscribe();
|
|
}
|
|
|
|
join() {
|
|
this.channel.join()
|
|
.receive("error", resp => {
|
|
console.log("Unable to join", resp);
|
|
});
|
|
}
|
|
|
|
leave() {
|
|
this.channel.leave();
|
|
}
|
|
|
|
subscribe() {
|
|
this.channel.on("game:update", this.updateGame.bind(this));
|
|
|
|
this.channel.on("presence_state", data => {
|
|
this.presences = Presence.syncState(this.presences, data);
|
|
this.setOpponentStatus();
|
|
});
|
|
|
|
this.channel.on("presence_diff", data => {
|
|
this.presences = Presence.syncDiff(this.presences, data);
|
|
this.setOpponentStatus();
|
|
});
|
|
}
|
|
|
|
updateGame(data) {
|
|
if (data.player != undefined) {
|
|
this.store.dispatch(setUserId(data.user_id));
|
|
this.store.dispatch(setPlayers(data));
|
|
}
|
|
this.store.dispatch(setGame(data));
|
|
}
|
|
|
|
setOpponentStatus() {
|
|
this.store.dispatch(setOpponentStatus(
|
|
this.opponentOnline() ? "viewing" : "offline"
|
|
));
|
|
}
|
|
|
|
opponentOnline() {
|
|
return _.find(this.presences, (value, id) => {
|
|
return parseInt(id) == this.store.getState().opponentId;
|
|
});
|
|
}
|
|
|
|
getAvailableMoves(square) {
|
|
this.channel.push("game:get_available_moves", { square })
|
|
.receive("ok", (data) => {
|
|
this.store.dispatch(setAvailableMoves(data.moves));
|
|
});
|
|
}
|
|
|
|
sendMove(move) {
|
|
this.channel.push("game:move", move)
|
|
.receive("error", resp => {
|
|
alert(resp.message);
|
|
});
|
|
}
|
|
}
|
|
|
|
export default Channel;
|