Created: 2023-03-15 07:47
I asked ChatGPT (GPT4) to implement a simple (in memory data), match-making algorithm in JS, after a few iterations it got to this:
// Define a set of players with their ratings
const players = Array.from({ length: 20 }, (_, i) => ({
id: i + 1,
name: `Player ${i + 1}`,
rating: Math.floor(Math.random() * 1000) + 1000,
}));
// Define a function to calculate the expected win rate of a player against another
function expectedWinRate(player, opponent) {
return 1 / (1 + 10 ** ((opponent.rating - player.rating) / 400));
}
// Define a function to calculate the match quality score between two players
function matchQuality(player1, player2) {
const rate1 = expectedWinRate(player1, player2);
const rate2 = expectedWinRate(player2, player1);
return Math.abs(rate1 - rate2);
}
// Define a function to find the best match for a given player
function findBestMatch(player, pool) {
let bestMatch = null;
let bestScore = Infinity;
for (const opponent of pool) {
const score = matchQuality(player, opponent);
if (score < bestScore) {
bestMatch = opponent;
bestScore = score;
}
}
return bestMatch;
}
// Define a function to perform matchmaking for a given pool of players
function matchmaking(pool) {
const pairs = [];
const remaining = [...pool];
while (remaining.length > 1) {
const player = remaining.shift();
const opponent = findBestMatch(player, remaining);
pairs.push([player, opponent]);
remaining.splice(remaining.indexOf(opponent), 1);
}
return pairs;
}
// Define a function to enter the queue
function enterQueue(queue, player) {
queue.push(player);
}
// Define a function to exit the queue
function exitQueue(queue, player) {
const index = queue.findIndex(p => p.id === player.id);
if (index !== -1) {
queue.splice(index, 1);
}
}
// Define a function to manage the matchmaking queue and active matches
function gameManager(players) {
const queue = [];
const activeMatches = [];
// Players enter the queue
for (const player of players) {
enterQueue(queue, player);
}
while (queue.length > 1) {
const pairs = matchmaking(queue);
activeMatches.push(...pairs);
// Remove paired players from the queue
for (const pair of pairs) {
exitQueue(queue, pair[0]);
exitQueue(queue, pair[1]);
}
}
return activeMatches;
}
// Example usage:
const activeMatches = gameManager(players);
console.log(activeMatches);