Category: JavaScript

  • Rock, Paper, Scissors JavaScript Game

    This Node.js script lets you challenge the computer in a classic match of Rock, Paper, Scissors. Simply enter your move, and the computer will randomly choose its move, with the game determining the winner based on standard rules.

    Click to view script…
    /*
     * Rock, Paper, Scissors Game
     *
     * Instructions:
     *   1. Enter your move: "rock", "paper", or "scissors".
     *   2. The computer will randomly choose its move.
     *   3. The game will then announce the winner:
     *      - Rock crushes scissors.
     *      - Scissors cuts paper.
     *      - Paper covers rock.
     *
     * Enjoy the game!
     */
    
    const readline = require('readline');
    
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    const choices = ["rock", "paper", "scissors"];
    
    // Function to randomly select the computer's choice
    function getComputerChoice() {
      const randomIndex = Math.floor(Math.random() * choices.length);
      return choices[randomIndex];
    }
    
    // Function to determine the result of the game
    function getResult(userChoice, computerChoice) {
      if (userChoice === computerChoice) {
        return "It's a tie!";
      }
      if (userChoice === "rock") {
        return computerChoice === "scissors" ? "You win! Rock crushes scissors." : "You lose! Paper covers rock.";
      }
      if (userChoice === "paper") {
        return computerChoice === "rock" ? "You win! Paper covers rock." : "You lose! Scissors cuts paper.";
      }
      if (userChoice === "scissors") {
        return computerChoice === "paper" ? "You win! Scissors cuts paper." : "You lose! Rock crushes scissors.";
      }
    }
    
    // Main game loop
    function playGame() {
      rl.question("Enter your move (rock, paper, or scissors): ", (answer) => {
        let userChoice = answer.trim().toLowerCase();
        if (!choices.includes(userChoice)) {
          console.log("Invalid move. Please choose rock, paper, or scissors.");
          return playGame();
        }
        const computerChoice = getComputerChoice();
        console.log(`Computer chose: ${computerChoice}`);
        const result = getResult(userChoice, computerChoice);
        console.log(result);
        rl.question("Play again? (yes/no): ", (response) => {
          if (response.trim().toLowerCase().startsWith("y")) {
            playGame();
          } else {
            console.log("Thanks for playing!");
            rl.close();
          }
        });
      });
    }
    
    console.log("=== Rock, Paper, Scissors Game ===");
    playGame();
  • Reverse Word Puzzle JavaScript Game

    This script randomly selects a word from a list, reverses it, and challenges the player to guess the original word. It demonstrates basic Node.js functionality, including using the readline module for handling terminal input.

    Click to view script…
    // reverseWordPuzzle.js
    
    // List of words for the puzzle
    const words = ['apple', 'banana', 'orange', 'strawberry', 'grape', 'pineapple', 'kiwi'];
    
    // Function to reverse a given word
    function reverseWord(word) {
      return word.split('').reverse().join('');
    }
    
    // Function to pick a random word from the array
    function getRandomWord() {
      return words[Math.floor(Math.random() * words.length)];
    }
    
    // Main function to run the game
    function playGame() {
      const originalWord = getRandomWord();
      const reversedWord = reverseWord(originalWord);
      
      console.log("=== Reverse Word Puzzle ===");
      console.log(`Unscramble this reversed word: ${reversedWord}`);
    
      // Create an interface for user input
      const readline = require('readline');
      const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
      });
    
      // Ask the user for their guess
      rl.question("Your guess: ", (answer) => {
        if(answer.trim().toLowerCase() === originalWord.toLowerCase()){
          console.log("Correct! Well done.");
        } else {
          console.log(`Incorrect. The correct word was: ${originalWord}`);
        }
        rl.close();
      });
    }
    
    // Start the game
    playGame();
  • Google Apps Script Slide Creator

    This script logs a greeting, creates a new Google Slide with a timestamped title, and appends sample text to it while logging the document URL

    Click to view script…
    function myTestSlideScript() {
      // Log a simple greeting message
      Logger.log("Hello, Google Apps Script!");
    
      // Get and log the active user's email address
      var userEmail = Session.getActiveUser().getEmail();
      Logger.log("Active user: " + userEmail);
    
      // Create a new Google Slides presentation with a unique name based on the current date and time
      var presentation = SlidesApp.create("Test Presentation " + new Date());
    
      // Get the first (default) slide of the presentation
      var slide = presentation.getSlides()[0];
    
      // Try to set the title and subtitle placeholders on the default title slide, if they exist
      var titlePlaceholder = slide.getPlaceholder(SlidesApp.PlaceholderType.CENTERED_TITLE);
      if (titlePlaceholder) {
        titlePlaceholder.asShape().getText().setText("Test Presentation");
      }
      
      var subtitlePlaceholder = slide.getPlaceholder(SlidesApp.PlaceholderType.SUBTITLE);
      if (subtitlePlaceholder) {
        subtitlePlaceholder.asShape().getText().setText("Created by: " + userEmail);
      }
    
      // Optionally, append another slide with additional details
      var additionalSlide = presentation.appendSlide(SlidesApp.PredefinedLayout.TITLE_AND_BODY);
      
      // Set the title of the additional slide
      var titleShape = additionalSlide.getShapes()[0];
      titleShape.getText().setText("Additional Slide");
    
      // Set the body text of the additional slide
      var bodyShape = additionalSlide.getShapes()[1];
      bodyShape.getText().setText("This slide was added by the script.\nActive user email: " + userEmail);
    
      // Log the URL of the created presentation so you can easily open it
      Logger.log("Presentation created: " + presentation.getUrl());
    }

  • Google Apps Script Sheet Creator

    This script logs a greeting, creates a new Google Sheet with a timestamped title, and appends sample text to it while logging the document URL

    Click to view script…
    function myTestScript() {
      // Log a simple greeting message
      Logger.log("Hello, Google Apps Script!");
    
      // Get and log the active user's email address
      var userEmail = Session.getActiveUser().getEmail();
      Logger.log("Active user: " + userEmail);
    
      // Create a new Google Sheet with a unique name based on the current date and time
      var spreadsheet = SpreadsheetApp.create("Test Spreadsheet " + new Date());
      var sheet = spreadsheet.getActiveSheet();
    
      // Append some rows to the sheet
      sheet.appendRow(["This spreadsheet was created by a test script in Google Apps Script."]);
      sheet.appendRow(["Active user email:", userEmail]);
    
      // Log the URL of the created spreadsheet so you can easily open it
      Logger.log("Spreadsheet created: " + spreadsheet.getUrl());
    }
  • Google Apps Script Document Creator

    This script logs a greeting, creates a new Google Document with a timestamped title, and appends sample text to it while logging the document URL

    Click to view script…
    function myTestScript() {
      // Log a simple greeting message
      Logger.log("Hello, Google Apps Script!");
    
      // Get and log the active user's email address
      var userEmail = Session.getActiveUser().getEmail();
      Logger.log("Active user: " + userEmail);
    
      // Create a new Google Document with a unique name based on the current date and time
      var doc = DocumentApp.create("Test Document " + new Date());
      var body = doc.getBody();
    
      // Append some paragraphs to the document
      body.appendParagraph("This document was created by a test script in Google Apps Script.");
      body.appendParagraph("Active user email: " + userEmail);
    
      // Log the URL of the created document so you can easily open it
      Logger.log("Document created: " + doc.getUrl());
    }