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

byes in leaderboard, only allow byes if required, refactor #41

Merged
merged 2 commits into from
Nov 12, 2024
Merged
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
103 changes: 81 additions & 22 deletions src/stackr/transitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export enum LogAction {
export type LeaderboardEntry = {
won: number;
lost: number;
byes: number;
points: number;
id: number;
name: string;
Expand Down Expand Up @@ -45,22 +46,21 @@ export const getLeaderboard = (state: LeagueState): LeaderboardEntry[] => {
const { teams, matches, meta } = state;
const completedMatches = matches.filter((m) => m.endTime);

const leaderboard = teams.map((team) => {
return {
...team,
won: 0,
lost: 0,
points: 0,
};
const leaderboard = teams.map((team) => ({
...team,
won: 0,
lost: 0,
byes: 0,
points: 0,
}));

// a bye is given 1 point
meta.byes.forEach((bye) => {
const teamIndex = leaderboard.findIndex((l) => l.id === bye.teamId);
leaderboard[teamIndex].byes += 1;
leaderboard[teamIndex].points += 1;
});

if (meta.byes.length) {
meta.byes.forEach((bye) => {
const teamIndex = leaderboard.findIndex((l) => l.id === bye.teamId);
leaderboard[teamIndex].points += 1;
});
}

completedMatches.forEach((match) => {
const { winnerTeamId, scores } = match;
const loserTeamId = Object.keys(scores).find((k) => +k !== winnerTeamId);
Expand All @@ -79,9 +79,12 @@ export const getLeaderboard = (state: LeagueState): LeaderboardEntry[] => {

return leaderboard.sort((a, b) => {
if (a.points === b.points) {
return a.won - b.won;
if (a.won === b.won) {
return a.byes - b.byes; // Sort by most byes last
}
return b.won - a.won; // Sort by most wins first
}
return b.points - a.points;
return b.points - a.points; // Sort by most points first
});
};

Expand All @@ -94,20 +97,63 @@ const getTopNTeams = (state: LeagueState, n?: number) => {
return leaderboard.slice(0, n);
};

const getTeamsInCurrentRound = (state: LeagueState) => {
const { meta, teams } = state;
const totalTeams = teams.length;
// Calculate the number of teams in the current round by halving the teams each round
const numTeamsInCurrentRound = Math.ceil(
totalTeams / Math.pow(2, meta.round)
);
const topTeams = getTopNTeams(state, numTeamsInCurrentRound);
return topTeams;
};

const isByeRequiredInCurrentRound = (state: LeagueState): boolean => {
const { meta } = state;

// If the tournament has ended or not all matches are complete, return false
if (!areAllMatchesComplete(state) || !!meta.endTime) {
return false;
}

const teamsInCurrentRound = getTeamsInCurrentRound(state);

// If only one team is left, return false
if (teamsInCurrentRound.length === 1) {
return false;
}

// If the number of remaining teams is odd, check if a bye is required
if (teamsInCurrentRound.length % 2 !== 0) {
const allTeamsHaveSamePoints = teamsInCurrentRound.every(
(t, _, arr) => t.points === arr[0].points
);

// If all teams have the same points, return true
if (allTeamsHaveSamePoints) {
return true;
}
}

return false;
};

const computeMatchFixtures = (state: LeagueState, blockTime: number) => {
const { meta, teams } = state;
// If the tournament has ended, return without scheduling matches
if (!areAllMatchesComplete(state) || !!meta.endTime) {
return;
}

const totalTeams = teams.length;
// Calculate the number of teams in the current round by halving the teams each round
const teamsInCurrentRound = Math.ceil(totalTeams / Math.pow(2, meta.round));

// this is assuming that the bye will be given to the team with lower score, and they'll get a chance to play with the top 3 teams
const shouldIncludeOneBye =
teamsInCurrentRound !== 1 &&
teamsInCurrentRound % 2 === 1 &&
meta.byes.length === 1
teamsInCurrentRound % 2 === 1 &&
meta.byes.filter(({ round }) => round === meta.round).length === 1
? 1
: 0;

Expand All @@ -116,31 +162,38 @@ const computeMatchFixtures = (state: LeagueState, blockTime: number) => {
teamsInCurrentRound + shouldIncludeOneBye
);

// If only one team is left, declare it the winner and end the tournament
if (topTeams.length === 1) {
state.meta.winnerTeamId = topTeams[0].id;
state.meta.endTime = blockTime;
return;
}

// If the number of top teams is odd, handle the odd team out
if (topTeams.length % 2 !== 0) {
const allTeamsHaveSamePoints =
topTeams[0].points === topTeams[teamsInCurrentRound - 1].points;

// If all teams have the same points, return without scheduling matches
// This situation requires a bye to be given in current round
if (allTeamsHaveSamePoints) {
return;
}

const oneTeamHasHigherPoints =
topTeams[0].points > topTeams[1].points &&
topTeams[0].points > topTeams[2].points;
// plan the match the rest of even teams

// Remove the team with the highest points to ensure competitive balance
// Otherwise, remove the team with the lowest points
if (oneTeamHasHigherPoints) {
topTeams.shift();
} else {
topTeams.pop();
}
}

// Generate match fixtures for the remaining teams
for (let i = 0; i < topTeams.length; i += 2) {
const team1 = topTeams[i];
const team2 = topTeams[i + 1];
Expand Down Expand Up @@ -296,9 +349,6 @@ const logGoal = League.STF({
},
handler: ({ state, inputs, block }) => {
const { matchId, playerId } = inputs;
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ENDED");
}

const { match, teamId } = getValidMatchAndTeam(state, matchId, playerId);

Expand Down Expand Up @@ -486,6 +536,15 @@ const logByes = League.STF({
},
handler: ({ state, inputs, block }) => {
const { teamId } = inputs;
if (hasTournamentEnded(state)) {
throw new Error("TOURNAMENT_ENDED");
}

// Is Bye required in the current round?
if (!isByeRequiredInCurrentRound(state)) {
throw new Error("BYE_NOT_REQUIRED_IN_THIS_ROUND");
}

state.meta.byes.push({ teamId, round: state.meta.round });
computeMatchFixtures(state, block.timestamp);
return state;
Expand Down
25 changes: 18 additions & 7 deletions tests/mru.4-teams.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,16 @@ describe("League with 4 teams", async () => {
};
const domain = mru.config.domain;
const types = mru.getStfSchemaMap()[name];
const {msgSender, signature} = await signByOperator(domain, types, { name, inputs });
const { msgSender, signature } = await signByOperator(domain, types, {
name,
inputs,
});
const actionParams = {
name,
inputs,
msgSender,
signature,
}
};
const ack = await mru.submitAction(actionParams);
const action = await ack.waitFor(ActionConfirmationStatus.C1);
return action;
Expand Down Expand Up @@ -152,7 +155,7 @@ describe("League with 4 teams", async () => {
expect(machine.state.meta.round).to.equal(2);
expect(machine.state.matches.length).to.equal(3);

// should have 1 incomplete match at round 2
// should have 1 new (incomplete) match at round 2
const incompleteMatches = machine.state.matches.filter((m) => !m.endTime);
expect(incompleteMatches.length).to.equal(1);
});
Expand All @@ -179,7 +182,9 @@ describe("League with 4 teams", async () => {
// check error for "MATCH_NOT_STARTED"
assert.typeOf(errors, "array");
expect(errors.length).to.equal(1);
expect(errors[0].message).to.equal("Transition logGoal failed to execute: MATCH_NOT_STARTED");
expect(errors[0].message).to.equal(
"Transition logGoal failed to execute: MATCH_NOT_STARTED"
);
});

it("should be able complete a round 2 (final)", async () => {
Expand Down Expand Up @@ -244,7 +249,9 @@ describe("League with 4 teams", async () => {
// check error for "PLAYER_NOT_FOUND"
assert.typeOf(errors1, "array");
expect(errors1.length).to.equal(1);
expect(errors1[0].message).to.equal("Transition logGoal failed to execute: INVALID_TEAM");
expect(errors1[0].message).to.equal(
"Transition logGoal failed to execute: INVALID_TEAM"
);

// remove a goal when not scored
const { logs: logs2, errors: errors2 } = await performAction(
Expand All @@ -261,7 +268,9 @@ describe("League with 4 teams", async () => {
// check error for "PLAYER_NOT_FOUND"
assert.typeOf(errors2, "array");
expect(errors2?.length).to.equal(1);
expect(errors2[0].message).to.equal("Transition removeGoal failed to execute: NO_GOALS_TO_REMOVE");
expect(errors2[0].message).to.equal(
"Transition removeGoal failed to execute: NO_GOALS_TO_REMOVE"
);

// second team score a goal
await performAction("logGoal", {
Expand Down Expand Up @@ -346,7 +355,9 @@ describe("League with 4 teams", async () => {
// check error for "TOURNAMENT_ENDED"
assert.typeOf(errors, "array");
expect(errors.length).to.equal(1);
expect(errors[0].message).to.equal("Transition logGoal failed to execute: TOURNAMENT_ENDED");
expect(errors[0].message).to.equal(
"Transition logGoal failed to execute: TOURNAMENT_ENDED"
);
});

it("should end the tournament", async () => {
Expand Down
Loading