time travel, strategy and code

image

Rock, Paper, Scissors is a simple but very popular gestural game that has been played for centuries by people all over the world. Because the rules are simple and the gestures are universally understood, it is widely used to settle disputes, make decisions, or just pass the time. In this article, we will explore the rich history of Rock, Paper, Scissors, talk about how to play it, write the game itself and analyze its code structure, and also learn how to improve your programming skills using this game.

History of the game “Rock, Paper, Scissors”

Rock, Paper, Scissors originated in ancient China, where there was a similar game called Shushilin that was already known around the 2nd century BC. An early version of this game used three gestures representing animals: a tiger, a chicken, and a worm. In this case, the chicken is afraid of the tiger, the worm is afraid of the chicken, and the tiger is afraid of getting worms. A circular relationship is created, similar to what we know from Rock, Paper, Scissors.

The game gradually made its way to Japan, where it became known as “yan-ken-pon” and became especially popular during the Edo period (1603–1868). In the Japanese version, the original Chinese trinity of animals was replaced by the familiar rock, paper, and scissors, and the gestures we know today were invented. Over time, the game spread to European countries, where it remains a popular pastime to this day.

Development of the game “Rock, Paper, Scissors”

Developing a computer version of Rock, Paper, Scissors is a great exercise for programmers who want to practice and hone their skills. The game can be written in HTML, CSS, and JavaScript, which is enough to provide the user interface and program the game logic.

Structurally, the code for the Rock, Paper, Scissors game can be broken down into several key components:

  1. HTML Structure: The HTML file defines the structure and content of the game, including the buttons the user can use to select a move. The HTML also displays the areas for displaying results and scores.
  2. CSS styles: The CSS file provides the style for the game, including the page layout, colors, fonts, and other visual elements (though in this example we won't go into styling too much and will focus on the functionality)
  3. JavaScript Logic: The JavaScript file contains the game logic, including functions for handling user input, determining what move the computer made, comparing moves to determine the winner, keeping score, and displaying results.

Now let's take a closer look at the code structure and explore how all the components work together. Our goal is to create a fully functional Rock, Paper, Scissors game.

HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rock, Paper, Scissors</title>
  <link rel="stylesheet" href="https://habr.com/ru/companies/piter/articles/841080/styles.css">
</head>
<body>
  <h1>Rock, Paper, Scissors</h1>
  <p>Choose your move:</p>
  <button id="rock" onclick="handleClick('rock')">Rock</button>
  <button id="paper" onclick="handleClick('paper')">Paper</button>
  <button id="scissors" onclick="handleClick('scissors')">Scissors</button>
  
  <div id="result"></div>
  <div>
    <span>User Score:</span>
    <span id="user-score">0</span>
  </div>
  <div>
    <span>Computer Score:</span>
    <span id="computer-score">0</span>
  </div>

  <script src="script.js"></script>
</body>
</html>

The HTML structure serves as the foundation of the game. The markup defines what elements will be visible to the user. Here are the main HTML elements that make up this structure:

[…]

  1. <body>

    This element contains all the content that will be displayed on the page, such as headings, paragraphs, buttons, and other user interface elements.

  2. <h1>

  3. <p>

    This is an element that contains a paragraph (paragraph). It contains instructions, i.e., hints for the user on how to choose a move.

  4. <button>

    These elements represent the move options that the user can choose (rock, paper, or scissors). Each button has an id attribute, which makes it easy to select in the JavaScript file, and an onclick attribute, which triggers the handleClick() function. This function takes a move as an argument.

  5. <div id=”result”>

    This div element is a container that displays the result of each round. The id attribute allows you to select and update this element in JavaScript.

  6. Очки пользователя и компьютера

    These div elements contain the scores earned by the user and the computer. Each score value is enclosed in a span element with a unique id attribute. This makes these elements easy to select and update using JavaScript.

  7. <script src=”script.js”></script>

    This element contains a script that links a JavaScript file to an HTML document. It is placed at the very end of the body element and thus ensures that the HTML document content is fully loaded first, and only then the JavaScript code is executed.

JavaScript file structure:

let userScore = 0;
let computerScore = 0;
let roundsPlayed = 0;

const getUserChoice = userInput => {
  return userInput.toLowerCase();
};

const getComputerChoice = () => {
  const number = Math.floor(Math.random() * 3);
  return ["rock", "paper", "scissors"][number];
};

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return "It's a tie!";
  }
  const winConditions = {
    rock: "scissors",
    paper: "rock",
    scissors: "paper",
  };

  return winConditions[userChoice] === computerChoice
    ? "User wins!"
    : "Computer wins!";
};

const checkGameOver = () => {
  if (userScore >= 3) {
    alert("User wins the game!");
    resetGame();
  } else if (computerScore >= 3) {
    alert("Computer wins the game!");
    resetGame();
  }
};

const resetGame = () => {
  userScore = 0;
  computerScore = 0;
  roundsPlayed = 0;
  document.getElementById("user-score").textContent = userScore;
  document.getElementById("computer-score").textContent = computerScore;
  document.getElementById("result").innerHTML = "";
};

const handleClick = choice => {
  if (roundsPlayed >= 5) {
    alert("Game over! Please start a new game.");
    resetGame();
    return;
  }

  const userChoice = getUserChoice(choice);
  const computerChoice = getComputerChoice();
  const result = determineWinner(userChoice, computerChoice);
  const resultDiv = document.getElementById("result");
  resultDiv.innerHTML = `User: ${userChoice} vs. Computer: ${computerChoice} - ${result}`;

  if (result === "User wins!") {
    userScore++;
  } else if (result === "Computer wins!") {
    computerScore++;
  }

  document.getElementById("user-score").textContent = userScore;
  document.getElementById("computer-score").textContent = computerScore;
  roundsPlayed++;
  checkGameOver();
};

The JavaScript file contains the game logic. Specifically, it contains functions for handling user input, determining the computer's move, comparing moves to determine the winner, and updating the score and output.

By developing the logic of the Rock, Paper, Scissors game in JavaScript, you can master various aspects of programming, in particular, working with functions, conditional operators, and event handling.

  1. Declaring and initializing global variables: userScor, computerScore, roundsPlayedThey store the user's points, the computer's points and the total number of rounds played.
  2. Function getUserChoice(): it takes user input (a string) and returns it in lowercase. This is done so that all entries in the game are case-invariant.
  3. Function getComputerChoice(): it creates a random option that will be the computer's move. This function generates a random number between 0 and 2 and matches it with the appropriate option (rock, paper or scissors).
  4. Function determineWinner(): it takes the choices made by the computer and the choices made by the user, compares them and determines the winner of the round. It checks if the options are equal (in which case it is a draw) or finds a winner depending on the conditions of which object wins. These conditions are defined in the object winConditions.
  5. Function checkGameOver(): checks whether the game is over, depending on which side has won after 5 rounds. If the user or the computer has won 3 or more rounds, the game is considered over and a notification window is displayed indicating the winner. After such a notification is displayed, the function is called resetGame()resetting the game state to its original state.
  6. Function resetGame(): This function resets the game state, setting the user's score, the computer's score, and the number of rounds played to 0. It also updates the leaderboard and clears the text describing the result.
  7. Function handleClick(): Function `handleClick()` is called as soon as the user clicks on one of the buttons – rock, paper or scissors. First, the function checks whether the game is not over yet (if 5 rounds have passed) and, if necessary, displays a notification about the start of a new game. After that, the function extracts the value selected by the user (passed as an argument) and receives the value selected by the computer (it is randomly generated). Then it determines the winner using the function determineWinner() and updates the text with the results. Depending on who won the round – the user or the computer – the score of that player increases, which is reflected on the screen accordingly. The value of the variable also increases roundsPlayed and the function is called checkGameOver()checking if the game is over.

What advanced programming skills can you learn by working on the game Rock, Paper, Scissors?

  1. Understand and manipulate the Document Object Model (DOM). By programming Rock, Paper, Scissors, you can learn to select, create, and modify HTML elements using JavaScript.
  2. Event handling: The game requires event listeners to detect and respond to user input. This provides valuable experience in working with events in JavaScript.
  3. Implementing Game Logic: When developing game logic, the programmer always practices writing functions, using conditional statements, and working with variables.
  4. Working with CSS styles: While developing the look of the game, the developer learns how to work with CSS properties and selectors. In the process, one can gain a better understanding of web design principles.
  5. Code Organization and Best Practices: When developing a rock-paper-scissors game, we learn to write clean and organized code, follow best practices, think about scalability and maintainability of code across projects.

In the future, this project can serve as a basis for further research and creativity. The developer may well implement additional features in this game – for example, sound effects, animation, high score tables and alternative game modes.

You can play Rock, Paper, Scissors Here.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *