This is an ongoing school project that I would like to improve. The point is to make the code as efficient (or short) as possible. I would like to reduce it by finding an al
Quite late to the party, but here's a slightly different way to the other answers in here. I've included the answer in TypeScript, but you can obviously remove the types if you like.
type Weapon = "Rock" | "Paper" | "Scissors";
type Result = "Player" | "Computer" | "Draw";
type GameLogic = Record>;
// Map that tracks what each weapon beats.
const outcomes: GameLogic = {
Rock: ["Scissors"],
Paper: ["Rock"],
Scissors: ["Paper"]
};
const determineWinner = (playerOneWeapon: Weapon, playerTwoWeapon: Weapon): Result => {
if (playerOneWeapon === playerTwoWeapon) {
return "Draw";
}
return outcomes[playerOneWeapon].includes(playerTwoWeapon)
? "Player One"
: "Player Two";
}
This implementation has the ability to scale nicely, too. As you can add extra weapons into the mix and the implementation of determineWinner
doesn't change - by adding to the Weapon
type and the outcomes
map:
type Weapon = "Rock" | "Paper" | "Scissors" | "Lizard" | "Spock";
const outcomes: GameLogic = {
Rock: ["Scissors", "Lizard"],
Paper: ["Rock", "Spock"],
Scissors: ["Paper", "Lizard"],
Lizard: ["Spock", "Paper"],
Spock: ["Rock", "Scissors"]
};
We can now support a game where each weapon beats each weapon exactly twice and each weapon loses to a weapon exactly twice (as opposed to the classic variation where everything beats one weapon and loses to one weapon).