Merge pull request #1 from jhalitaksoy/feature/use-mancala-js

Feature/use mancala js
This commit is contained in:
Halit Aksoy 2022-05-04 23:47:14 +03:00 committed by GitHub
commit 5bc2159342
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 15470 additions and 6100 deletions

12078
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"mancala.js": "^0.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},

View File

@ -2,24 +2,12 @@ import * as React from 'react';
import { FunctionComponent, useState } from 'react';
import BoardView from './components/BoardView';
import { context } from './context'
import { Board, GameMove, Hole, Store } from './mancala';
import { Game } from './mancala';
import { decodeText, encodeText } from './rtmt/byte_util';
import { Bytes } from './rtmt/rtmt';
import { RTMTWS } from './rtmt/rtmt_websocket';
import { channel_game_move, channel_leave_game, channel_on_game_update, channel_on_game_user_leave } from './channel_names';
import Button from './components/Button';
import InfoPanel from './components/InfoPanel';
const testBoard = (): Board => {
const board = new Board(
[new Hole(0), new Hole(4), new Hole(4), new Hole(3), new Hole(2), new Hole(1)],
[new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(10)],
new Store(0), new Store(0))
return board
}
const testGame = new Game("0", "1", testBoard(), "player2", "playing")
import { CommonMancalaGame, MancalaGame, Pit } from 'mancala.js'
import { GameMove } from './models/GameMove';
type ConnectionState = "connecting" | "error" | "connected" | "reconnecting"
@ -30,7 +18,7 @@ const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
const [searchingOpponent, setSearchingOpponent] = useState<boolean>(false)
const [game, setGame] = useState<Game>(undefined)
const [game, setGame] = useState<CommonMancalaGame>(undefined)
const [crashMessage, setCrashMessage] = useState<string>(undefined)
@ -56,45 +44,32 @@ const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
if (rtmtws) {
rtmtws.initWebSocket(userKey, onConnectionDone, onConnectionLost, onConnectionError)
} else {
console.log("context.rtmt is not RTMTWS");
console.error("context.rtmt is not RTMTWS");
}
})
}
const listenMessages = () => {
context.rtmt.listenMessage(channel_on_game_update, (message: Object) => {
const newGame: Game = message as Game;
console.log("on game update");
console.log(newGame);
setGame(new Game(newGame.player1, newGame.player2, newGame.board, newGame.turn, newGame.state))
})
context.rtmt.listenMessage(channel_on_game_update, (message: Object) => {
const newGame: Game = message as Game;
console.log("on game update");
console.log(newGame);
setGame(new Game(newGame.player1, newGame.player2, newGame.board, newGame.turn, newGame.state))
const newGame: CommonMancalaGame = message as CommonMancalaGame;
setGame(MancalaGame.createFromMancalaGame(newGame))
})
context.rtmt.listenMessage("on_game_start", (message: Object) => {
const newGame: Game = message as Game;
console.log("on_game_start");
console.log(newGame);
const newGame: CommonMancalaGame = message as CommonMancalaGame;
setSearchingOpponent(false)
setGame(new Game(newGame.player1, newGame.player2, newGame.board, newGame.turn, newGame.state))
setGame(MancalaGame.createFromMancalaGame(newGame))
})
context.rtmt.listenMessage("on_game_crashed", (message : any) => {
const newCrashMessage = message as string
console.log("on_game_crash");
console.log(newCrashMessage);
console.error("on_game_crash");
console.error(newCrashMessage);
setCrashMessage(newCrashMessage)
})
context.rtmt.listenMessage(channel_on_game_user_leave, (message : any) => {
const userKeyWhoLeave = message;
console.log("on_game_user_leave");
console.log(channel_on_game_user_leave);
setUserKeyWhoLeave(userKeyWhoLeave)
})
}
@ -120,7 +95,7 @@ const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
context.rtmt.sendMessage(channel_leave_game, {})
}
const onHoleSelect = (index: number, hole: Hole) => {
const onHoleSelect = (index: number, hole: Pit) => {
const gameMove: GameMove = { index: index }
context.rtmt.sendMessage(channel_game_move, gameMove)
}
@ -187,7 +162,7 @@ const Home: FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
<h1 style={{ margin: "10px 0px" }}>{context.texts.Mancala}</h1>
<div>
{renderNewGameButton()}
{game && !userKeyWhoLeave && !crashMessage && game?.state == "playing" && < Button color="#005f73" text={context.texts.Leave} onClick={leaveGame} />}
{game && !userKeyWhoLeave && !crashMessage && (game?.state === "playing" || game?.state === "initial") && < Button color="#005f73" text={context.texts.Leave} onClick={leaveGame} />}
</div>
</div>

View File

@ -1,6 +1,6 @@
import { Bank, MancalaGame, Pit } from 'mancala.js';
import * as React from 'react';
import { FunctionComponent, useState } from 'react';
import { Hole, Store, Game } from '../mancala';
type Theme = {
background : string,
@ -42,8 +42,8 @@ function range(size: number) {
return ans;
}
const HoleView: FunctionComponent<{ hole: Hole, color: string, onClick: () => void }> = ({ hole, color, onClick }) => {
const balls = [...range(hole.ballCount)].map((i) => <BallView color={theme.ballColor}/>)
const HoleView: FunctionComponent<{ hole: Pit, color: string, onClick: () => void }> = ({ hole, color, onClick }) => {
const balls = [...range(hole.stoneCount)].map((i) => <BallView color={theme.ballColor}/>)
return (<div
onClick={onClick}
@ -64,8 +64,8 @@ const HoleView: FunctionComponent<{ hole: Hole, color: string, onClick: () => vo
}
const StoreView: FunctionComponent<
{ store: Store, color: string, gridColumn: string, gridRow: string }> = ({ store, color, gridColumn, gridRow }) => {
const balls = [...range(store.ballCount)].map((i) => <BallView color={theme.ballColor}/>)
{ store: Bank, color: string, gridColumn: string, gridRow: string }> = ({ store, color, gridColumn, gridRow }) => {
const balls = [...range(store.stoneCount)].map((i) => <BallView color={theme.ballColor}/>)
return (<div style={{
gridColumn: gridColumn,
gridRow: gridRow,
@ -82,22 +82,22 @@ const StoreView: FunctionComponent<
</div>)
}
const BoardView: FunctionComponent<{ game?: Game, userKey: string, onHoleSelect: (index: number, hole: Hole) => void }> = ({
const BoardView: FunctionComponent<{ game?: MancalaGame, userKey: string, onHoleSelect: (index: number, hole: Pit) => void }> = ({
game, userKey, onHoleSelect }) => {
const player1Holes = game?.board.player1Holes.map((hole) => (
const player1Pits = game?.board.player1Pits.map((hole) => (
<HoleView hole={hole} color={theme.holeColor} onClick={() => {
if (game.turn == "player1") onHoleSelect(game.board.player1Holes.indexOf(hole), hole)
if (game.turnPlayerId === game.player1Id) onHoleSelect(game.board.player1Pits.indexOf(hole), hole)
}} />
))
const player2Holes = game!!.board.player2Holes.map((hole) => (
const player2Pits = game!!.board.player2Pits.map((hole) => (
<HoleView hole={hole} color={theme.holeColor} onClick={() => {
if (game.turn == "player2") onHoleSelect(game.board.player2Holes.indexOf(hole), hole)
if (game.turnPlayerId === game.player2Id) onHoleSelect(game.board.player2Pits.indexOf(hole), hole)
}} />
))
const isUserTurn = game.checkGameTurn(userKey);
const isUserTurn = game.checkIsPlayerTurn(userKey)
const storeColor = isUserTurn ? theme.storeColor : theme.storeColorWhenPlayerTurn;
@ -112,19 +112,19 @@ const BoardView: FunctionComponent<{ game?: Game, userKey: string, onHoleSelect:
background: isUserTurn ? theme.boardColor : theme.boardColorWhenPlayerTurn
}}>
{
game.getPlayerNameByKey(userKey) == "player2" ? (
userKey === game.player2Id ? (
<>
<StoreView store={game!!.board.player1Store} color={storeColor} gridColumn="1 / 2" gridRow="1 / 3" />
<StoreView store={game!!.board.player2Store} color={storeColor} gridColumn="8 / 9" gridRow="1 / 3" />
{player1Holes.reverse()}
{player2Holes}
<StoreView store={game!!.board.player1Bank} color={storeColor} gridColumn="1 / 2" gridRow="1 / 3" />
<StoreView store={game!!.board.player2Bank} color={storeColor} gridColumn="8 / 9" gridRow="1 / 3" />
{player1Pits.reverse()}
{player2Pits}
</>
) : (
<>
<StoreView store={game!!.board.player2Store} color={storeColor} gridColumn="1 / 2" gridRow="1 / 3" />
<StoreView store={game!!.board.player1Store} color={storeColor} gridColumn="8 / 9" gridRow="1 / 3" />
{player2Holes.reverse()}
{player1Holes}
<StoreView store={game!!.board.player2Bank} color={storeColor} gridColumn="1 / 2" gridRow="1 / 3" />
<StoreView store={game!!.board.player1Bank} color={storeColor} gridColumn="8 / 9" gridRow="1 / 3" />
{player2Pits.reverse()}
{player1Pits}
</>
)
}

View File

@ -1,10 +1,10 @@
import { MancalaGame } from 'mancala.js';
import * as React from 'react';
import { FunctionComponent } from "react"
import { context } from '../context';
import { Game } from '../mancala';
const InfoPanel: FunctionComponent<{
game: Game,
game: MancalaGame,
crashMessage: string,
userKey: string,
userKeyWhoLeave: string,
@ -40,10 +40,11 @@ const InfoPanel: FunctionComponent<{
)
}
if (game) {
if (game.state == "ended") {
const wonPlayer = game.getWonPlayer()
let whoWon = game.getWonPlayer() == userKey ? context.texts.YouWon : context.texts.YouLost
const wonPlayer = game.getWonPlayerId();
let whoWon = game.getWonPlayerId() === userKey ? context.texts.YouWon : context.texts.YouLost
if(!wonPlayer){
whoWon = context.texts.GameDraw
}
@ -54,7 +55,7 @@ const InfoPanel: FunctionComponent<{
)
} else {
return (
<h4>{game.checkGameTurn(userKey) ? context.texts.YourTurn : context.texts.OpponentTurn}</h4>
<h4>{game.checkIsPlayerTurn(userKey) ? context.texts.YourTurn : context.texts.OpponentTurn}</h4>
)
}
}

View File

@ -1,250 +0,0 @@
export class Game {
player1: string
player2: string
board: Board
turn: "player1" | "player2"
state: "playing" | "ended"
constructor(player1: string, player2: string, board: Board, turn: "player1" | "player2", state: "playing" | "ended") {
this.player1 = player1
this.player2 = player2
this.board = board
this.turn = turn
this.state = state
}
public moveByIndex(holeIndex: number, player: "player1" | "player2") {
let hole = this.board.player1Holes[holeIndex]
if (player == "player2") {
hole = this.board.player2Holes[holeIndex]
}
return this.move(hole, player)
}
public move(hole: Hole, player: "player1" | "player2") {
if (this.turn != player) return
if (hole.ballCount == 0) return
let holeIndex = -1
let circle: Array<Hole>
if (player == "player1") {
holeIndex = this.board.player1Holes.indexOf(hole)
circle = this.board.player1Circle()
} else {
holeIndex = this.board.player2Holes.indexOf(hole)
circle = this.board.player2Circle()
}
// if can't find hole in own list
if (holeIndex < 0) {
return
}
const circleSize = circle.length
const stepCount = hole.ballCount
let startIndex = holeIndex
let holeEndBallCount = 1
if (hole.ballCount == 1) {
startIndex = holeIndex + 1
holeEndBallCount = 0
}
let stopIndex = startIndex + stepCount - 1
stopIndex += (stopIndex / circleSize) | 0 // add the number of jump over opponent store
const stopHole = circle[stopIndex % circle.length]
iterateHoles(circle, startIndex, stopIndex, (eachHole: Hole, index: number) => {
if (!checkIsOpponentStore(index, circleSize)) {
eachHole.ballCount++
}
})
hole.ballCount = holeEndBallCount
console.log((stopIndex));
console.log(checkIsOwnHole(stopIndex, circleSize));
if (checkIsOwnHole(stopIndex, circleSize)) {
//check if it was 0 before
if (stopHole.ballCount == 1) {
const ownStore = getOwnStore(circle)
const opponentHole = getOpponentHoleByIndex(stopIndex%16, circle)
if (opponentHole.ballCount > 0) {
ownStore.ballCount++
stopHole.ballCount = 0;
ownStore.ballCount += opponentHole.ballCount
opponentHole.ballCount = 0
}
}
}
if (!checkIsOwnStore(stopIndex, circleSize)) {
this.changeTurn()
}
const ownHoles = circle.slice(0, circle.length / 2 - 1)
let sumBallCount = 0;
for (const hole of ownHoles) sumBallCount += hole.ballCount
if (sumBallCount == 0) {
const opppentHoles = circle.slice(circle.length / 2, circle.length - 1)
let sumOppenentBallCount = 0;
for (const hole of opppentHoles) {
sumOppenentBallCount += hole.ballCount
hole.ballCount = 0
}
getOwnStore(circle).ballCount += sumOppenentBallCount
this.state = "ended"
}
}
public changeTurn() {
if (this.turn == "player1") {
this.turn = "player2"
} else {
this.turn = "player1"
}
}
public clone() { return new Game(this.player1, this.player2, this.board, this.turn, this.state) }
//todo throw expection
public getPlayerNameByKey(key: string): "player1" | "player2" {
if (this.player1 == key) {
return "player1"
} else {
return "player2"
}
}
//todo throw expection
public getPlayerKeyByName(key: "player1" | "player2"): string {
if (key == "player1") {
return this.player1
} else {
return this.player2
}
}
public checkGameTurn(user: string): boolean {
return this.getPlayerNameByKey(user) == this.turn
}
public getWonPlayer() : string | undefined {
const player1BallCount = this.board.player1Store.ballCount
const player2BallCount = this.board.player2Store.ballCount
if(player1BallCount < player2BallCount){
return this.getPlayerKeyByName("player2")
}else if(player1BallCount > player2BallCount) {
return this.getPlayerKeyByName("player1")
}else{
return undefined
}
}
}
export function createGame(player1: string, player2: string) {
// const board = new Board(
// [new Hole(0), new Hole(1), new Hole(2), new Hole(3), new Hole(4), new Hole(5)],
// [new Hole(0), new Hole(1), new Hole(2), new Hole(3), new Hole(4), new Hole(5)],
// new Store(0), new Store(0))
const board = new Board(
[new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4)],
[new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4)],
new Store(0), new Store(0))
// const board = new Board(
// [new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(4), new Hole(1)],
// [new Hole(1), new Hole(0), new Hole(0), new Hole(0), new Hole(1), new Hole(0)],
// new Store(0), new Store(0))
return new Game(player1, player2, board, "player1", "playing")
}
export class Hole {
public ballCount: number
constructor(ballCount: number) {
this.ballCount = ballCount
}
}
export class Store extends Hole {
constructor(ballCount: number) {
super(ballCount)
}
}
export class Board {
public player1Holes: Array<Hole>
public player2Holes: Array<Hole>
public player1Store: Store
public player2Store: Store
constructor(player1Holes: Array<Hole>, player2Holes: Array<Hole>, player1Store: Store, player2Store: Store) {
this.player1Holes = player1Holes
this.player2Holes = player2Holes
this.player1Store = player1Store
this.player2Store = player2Store
}
// array.reverse didn't work
public player1Circle(): Array<Hole> {
return [...this.player1Holes, this.player1Store, ...this.player2Holes, this.player2Store]
}
// array.reverse didn't work
public player2Circle(): Array<Hole> {
return [...this.player2Holes, this.player2Store, ...this.player1Holes, this.player1Store]
}
public getBallCount(holes : Array<Hole> ) : number {
let ballCount = 0
for (let hole of holes) {
ballCount += hole.ballCount;
}
return ballCount
}
}
function iterateHoles(holes: Array<Hole>, start: number, stop: number, callback: (hole: Hole, index: number) => void) {
for (let index = start; index <= stop; index++) {
callback(holes[index % holes.length], index)
}
}
function reverse(holes: Array<Hole>) {
const array = new Array<Hole>()
for (let index = holes.length - 1; index > -1; index--) {
array.push(holes[index])
}
return array
}
function checkIsOpponentStore(index: number, size: number) { return (index % size) === size - 1 }
function checkIsOpponentHole(index: number, size: number) { return (index % size) >= size / 2 }
function checkIsOwnHole(index: number, size: number) { return (index % size) < size / 2 - 1 }
function checkIsOwnStore(index: number, size: number) { return (index % size) == size / 2 - 1 }
function getOwnStore(circle: Array<Hole>) {
return circle[circle.length / 2 - 1]
}
function getOpponentHoleByIndex(index: number, circle: Array<Hole>) {
return circle[circle.length - 2 - index]
}
export interface GameMove {
index: number,
}

3
src/models/GameMove.ts Normal file
View File

@ -0,0 +1,3 @@
export interface GameMove {
index: number;
}

View File

@ -1,69 +1,70 @@
import { decode, encode } from "./encode_decode_message"
import { Bytes, OnMessage, RTMT } from "./rtmt"
import { context } from '../context';
import { decode, encode } from "./encode_decode_message";
import { Bytes, OnMessage, RTMT } from "./rtmt";
import { server } from "../service/http_service";
export class RTMTWS implements RTMT {
private messageChannels: Map<String, OnMessage>
private ws: WebSocket
private messageChannels: Map<String, OnMessage>;
private ws: WebSocket;
constructor() {
this.messageChannels = new Map<String, OnMessage>()
this.messageChannels = new Map<String, OnMessage>();
}
initWebSocket(userKey: string, onopen: () => any, onClose: () => any, onError: (event: Event) => any) {
const url = server.wsServerAdress + '?userKey=' + userKey
const ws = new WebSocket(url)
initWebSocket(
userKey: string,
onopen: () => any,
onClose: () => any,
onError: (event: Event) => any
) {
const url = server.wsServerAdress + "?userKey=" + userKey;
const ws = new WebSocket(url);
ws.binaryType = "arraybuffer"; //for firefox
ws.onopen = () => {
console.log('(RTMT) ws has opened')
this.ws = ws
onopen()
}
console.info("(RTMT) ws has opened");
this.ws = ws;
onopen();
};
ws.onclose = () => {
console.log('(RTMT) ws has closed')
console.info("(RTMT) ws has closed");
//this.ws = undefined
onClose()
}
onClose();
};
ws.onmessage = (event: MessageEvent) => {
this.onWebSocketMessage(this, event)
}
this.onWebSocketMessage(this, event);
};
ws.addEventListener("error", ev => {
console.log({ ws_error: ev });
onError(ev)
})
ws.addEventListener("error", (ev) => {
console.error({ ws_error: ev });
onError(ev);
});
}
sendMessage(channel: string, message: Object) {
console.log("(RTMT) Sending message to channel " + channel);
if (this.ws === undefined) {
console.log('(RTMT) ws is undefined')
return
console.error("(RTMT) ws is undefined");
return;
}
const data = encode(channel, message)
this.ws.send(data)
const data = encode(channel, message);
this.ws.send(data);
}
listenMessage(channel: string, callback: OnMessage) {
this.messageChannels.set(channel, callback)
this.messageChannels.set(channel, callback);
}
onWebSocketMessage(rtmt: RTMTWS, event: MessageEvent) {
const { channel, message } = decode(event.data)
console.log("(RTMT) " + { channel, message });
rtmt.onMessage(channel, message)
const { channel, message } = decode(event.data);
rtmt.onMessage(channel, message);
}
onMessage(channel: string, message: Bytes) {
const callback = this.messageChannels.get(channel)
const callback = this.messageChannels.get(channel);
if (callback) {
callback(message)
callback(message);
} else {
console.log("(RTMT) Channel callback not found!" + channel);
console.warn("(RTMT) Channel callback not found!" + channel);
}
}
}

View File

@ -1,33 +1,30 @@
export type Server = {
serverAdress: string
wsServerAdress: string
}
serverAdress: string;
wsServerAdress: string;
};
export const server: Server = {
serverAdress: "https://segin.one/mancala-backend",
wsServerAdress: "wss://segin.one/mancala-backend/",
}
serverAdress: "https://segin.one/mancala-backend-beta",
wsServerAdress: "wss://segin.one/mancala-backend-beta/",
};
const useLocal = false
const useLocal = false;
if (useLocal) {
server.serverAdress = "http://localhost:5000"
server.wsServerAdress = "ws://localhost:5000"
server.serverAdress = "http://localhost:5000";
server.wsServerAdress = "ws://localhost:5000";
}
interface HttpService {
get: (route: string, succes: () => any, error: () => any) => any
get: (route: string, succes: () => any, error: () => any) => any;
}
class HttpServiceImpl implements HttpService {
public serverAdress: string
public serverAdress: string;
constructor(serverAdress: string) {
this.serverAdress = serverAdress
this.serverAdress = serverAdress;
}
public get(route: string, succes: () => any, error: () => any): any {
}
public get(route: string, succes: () => any, error: () => any): any {}
}

8976
yarn.lock

File diff suppressed because it is too large Load Diff