Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attempt at seperating round + turn machines #106

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/@types/entities.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type Player = {
};

type Question = {
answer: string[];
answer: Colour[];
number: number;
question: string;
};
Expand Down
129 changes: 76 additions & 53 deletions server/machines/round.ts
Original file line number Diff line number Diff line change
@@ -1,71 +1,94 @@
import { assign, createMachine } from "xstate";
import type { Answer } from "../@types/entities";
import type { Socket } from "socket.io";
import { assign, setup } from "xstate";
import type { Answer, Question } from "../@types/entities";
import questions from "../data/questions.json";

type Question = {
answer: string[];
number: number;
question: string;
};

const context = {
answers: [] as Answer[],
questions: questions as Question[],
selectedQuestion: {} as Question | undefined,
scores: {} as Record<Socket["id"], number>,
};

type Context = typeof context;

type Event = {
type: "playerSubmitsAnswer";
answer: Answer;
type Events = {
type: "turnEnd";
answers: Answer[];
};

const roundMachine = createMachine(
{
context,
id: "round",
initial: "roundStart",
types: {
context: {} as Context,
events: {} as Event,
typegen: {} as import("./round.typegen").Typegen0,
},
states: {
roundStart: {
entry: ["setQuestion"],
on: {
playerSubmitsAnswer: { actions: "addAnswer", target: "countdown" },
},
},
countdown: {
on: {
playerSubmitsAnswer: { actions: "addAnswer" },
},
after: {
[15000]: { target: "finished" },
},
},
finished: {
type: "final",
const dynamicParamFuncs = {
setQuestion: ({ context }: { context: Context }) => {
return { questions: context.questions };
},
// TODO: updateScores
};
// players are awarded one point for each person who guesses wrong plus any points from the bonus round
// show what answers every gave
// there could be no correct answers - bonus points are then reset
// all players could be correct and no score would be awarded but 1 point is added to the next round
// first to 10

// count how many players have correct answers
// if 0 correct answers set bonus points to 0 -> check win conditions -> next question
// if all answers are correct ++bonus points -> check win conditions -> next question
// if there are some correct and some incorrect answers add the number of incorrect answers (+ any bonus points - then reset bonus points) to the scores of the players with correct answers -> check win conditions -> next question

const roundMachine = setup({
types: {} as {
context: Context;
events: Events;
},

actions: {
setQuestion: assign({
selectedQuestion: (
_,
params: ReturnType<typeof dynamicParamFuncs.setQuestion>,
) => {
const questionIndex = Math.floor(
Math.random() * (params.questions.length - 1),
);
// can we splice the selected question out of the questions array with params.questions.splice[questionIndex, 1]?
return params.questions[questionIndex];
},
}),
updateScores: assign({
// TODO
}),
},
guards: {
noClearWinner: {
// TODO - need to work out how to transition into a new turn either here or in the model
},
},
{
actions: {
addAnswer: assign({
answers: (args) => [...args.context.answers, args.event.answer],
}),
setQuestion: assign({
selectedQuestion: (args) => {
const questionIndex = Math.floor(
Math.random() * (args.context.questions.length - 1),
);
return args.context.questions[questionIndex];
}).createMachine({
context: context,
id: "round",
initial: "turn",
types: {
context: {} as Context,
events: {} as Event,
},
states: {
turn: {
entry: [{ type: "setQuestion", params: dynamicParamFuncs.setQuestion }], // keep track of which questions have been asked in round and/or entire game/lobby]
on: {
turnEnd: {
target: "finished",
actions: {
type: "updateScores",
params: dynamicParamFuncs.updateScores,
},
guard: {
Comment on lines +77 to +80
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Liz suggested that we calculate the points for the turn in the turn, then pass that up to the round which can update the ongoing score tracking with the new points. Not sure if this will help us unpick some of the complexity we need to work through with updateScores or noClearWinner, but it feels like a good idea?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, when you say it like that it makes sense

type: "noClearWinner",
params: dynamicParamFuncs.noClearWinner,
},
},
}),
},
},
finished: {
type: "final",
},
},
);
});

export { context, roundMachine };
24 changes: 0 additions & 24 deletions server/machines/round.typegen.ts

This file was deleted.

54 changes: 54 additions & 0 deletions server/machines/turn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { assign, createMachine } from "xstate";
import type { Answer, Question } from "../@types/entities";

const context = {
answers: [] as Answer[],
selectedQuestion: {} as Question | undefined,
};

type Context = typeof context;

type Event = {
type: "playerSubmitsAnswer";
answer: Answer;
};

const turnMachine = createMachine(
{
context: context,
id: "turn",
initial: "turnStart",
types: {
context: {} as Context,
events: {} as Event,
},
states: {
turnStart: {
on: {
playerSubmitsAnswer: { actions: "addAnswer", target: "countdown" },
},
},
countdown: {
on: {
playerSubmitsAnswer: { actions: "addAnswer" },
},
after: {
[15000]: { target: "finished" },
},
},
finished: {
type: "final",
// pass answers back to round machine
},
},
},
{
actions: {
addAnswer: assign({
answers: (args) => [...args.context.answers, args.event.answer],
}),
},
},
);

export { context, turnMachine };
32 changes: 28 additions & 4 deletions server/models/round.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { type Actor, createActor } from "xstate";
import { type Actor, type InspectionEvent, createActor } from "xstate";
import type { Answer, Question } from "../@types/entities";
import { context, roundMachine } from "../machines/round";
import { turnMachine } from "../machines/turn";
import type { SocketServer } from "../socketServer";
import { machineLogger } from "../utils/machineLogger";

class Round {
machine: Actor<typeof roundMachine>;
turnMachine?: Actor<typeof turnMachine>;
server: SocketServer;

constructor(server: SocketServer) {
this.server = server;
this.machine = createActor(roundMachine, { ...context });
this.machine = createActor(roundMachine, {
...context,
inspect: (inspectionEvent: InspectionEvent) => {
machineLogger(inspectionEvent, "round");
},
});
this.machine.subscribe((state) => {
console.info({
machine: "round",
Expand All @@ -18,10 +26,12 @@ class Round {
});

switch (state.value) {
case "roundStart": {
case "turn": {
this.server.onQuestionSet(
this.machine.getSnapshot().context.selectedQuestion as Question,
);

this.initialiseTurnMachine();
break;
}
default:
Expand All @@ -31,8 +41,22 @@ class Round {
this.machine.start();
}

initialiseTurnMachine() {
this.turnMachine = createActor(turnMachine, {
inspect: (inspectionEvent: InspectionEvent) => {
machineLogger(inspectionEvent, "turn");
},
});
this.turnMachine.subscribe((state) => {
if (state.value === "finished") {
this.machine.send({ type: "turnEnd", answers: state.context.answers });
}
});
this.turnMachine.start();
}

addAnswer(answer: Answer) {
this.machine.send({ type: "playerSubmitsAnswer", answer });
this.turnMachine?.send({ type: "playerSubmitsAnswer", answer });
}
}

Expand Down
13 changes: 13 additions & 0 deletions server/utils/machineLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { InspectionEvent } from "xstate";

export const machineLogger = (
inspectionEvent: InspectionEvent,
machine: "turn" | "round",
) => {
if (inspectionEvent.type === "@xstate.event") {
console.info(inspectionEvent.event, `machine: ${machine}`);
}
if (inspectionEvent.type === "@xstate.snapshot") {
console.info(inspectionEvent.snapshot, `machine: ${machine}`);
}
};
Loading