Home Java How I Created Squid Game in Java: Red/Green Light

How I Created Squid Game in Java: Red/Green Light

Published: Last Updated on 3 comments

Hey Tea lovers! Before talking about Squid Game in Java, let me ask you What do you do on a bored Sunday afternoon? Go out, have fun, or do Netflix and Chill right? Well, I did Netflix and chill. Well, not chill, but experienced a rollercoaster of emotions with the sensational Korean Drama Squid Game on Netflix. Oh Boy! What a massive hit it is. One of the best series I have seen. It has all the things and the story is gripping. Oh sorry, I am off on a different tangent. I know it’s not a movie review blog, but I can’t help but be amazed.

Anyway, the thing I wanted to talk about is the games played in Squid Game. The games are very fun (Not like in the series but in real life). So I tried to replicate the same in Java. So I started with the Red Light and Green Light.

I just jumped on to the IDE with enthusiasm and the result was this boring code which I will shamelessly show and probably explain to you. The game is fun and I enjoyed playing it. I build it so I had to 😢.

I pushed the code on GitHub in hope that everybody will contribute to making it even more fun and adding more games along the way. So feel free to clone, fork, and contribute.


I would be happy to connect with you guys on social media. It’s @coderstea on TwitterLinkedinFacebook, Instagram, and YouTube.

Please Subscribe to the newsletter to know about the latest posts from CodersTea.


The Game Play of Squid Game in Java

The game is simple and terminal-based. The game start options for the games, as to which games you want to play. Currently, I only added GreenLight and Red Light. After you select your game. Red Light Green Light shows the message related to the game.

The game message shows up. Starting the Squid Game #1: Red Light / Green Light. When Green Light, Please press Enter button continuously. Stop once you see the Red light And that’s the only thing you have to do, Keep on Pressing Enter. But as soon as the Red Light message pops up, you have to immediately stop pressing. If you press it after Red Light, you will lose 😨🔫 . Don’t worry mine just shows a Game over message. And in the end, it shows your score, which is the number of times you have pressed it. The cycle continues for 1 minute.

via GIPHY

You can play with your friend and see who can make a greater score within a single play. We will soon add a web version in our tools section of the website. For that please follow us for notifications.

Requirement for Squid Game in Java

Well, it’s a simple java application. You don’t even need too many things. You just need to have Java installed on your machine, any version. In the future, if we decide to make it more like GTA V, Fortnite, or PUBG, then you will need more things. But for now, Java suffices. However, the project on GitHub is a maven project. As long as you are only running the code shown at the end of this post, here, you only need Java.

Yes One more thing, I am a great programmer so I tried the most advanced thing I know of in Java, Thread :D. Just kidding, I used thread to make the input and the actual red light and green light code run in parallel. But better solutions are welcome.

If you want to refresh your mind on Thread, you can read my posts on Thread. How Multi-Threading Lets You do Things Simultaneously and Thread Pool in Java Multi-Threading Explained

The Code for Squid Game in Java

As I said I have used Thread to run the Players and Doll’s code parallelly. I have created two threads named squidGameDoll and player. They share some common static variables for seeing the values and movement of each other.

private static final String RED_LIGHT = "Red Light 🔴 👧";
private static final String GREEN_LIGHT = "Green Light 🟢 👧";
private static final String GAME_OVER = "Game Over 🤯🔫 (press Enter)";

private static final int TIME_LIMIT = 1000 * 60; //  1 Minute
private static final int BREATHER = 500;
private static final int GREEN_LIGHT_MAX_TIME = 4000;Code language: PHP (php)

The player thread is simple but squidGameDoll is a little complex. But I will try to explain it my best. Of course, there may be better ways of doing it, but I could think of this approach only.

The Doll of Squid Game in Java

You must remember the doll of the game.

Squid game Doll in Java
Squid Game Doll

So for our Squid Game in Java, the doll has like 80% of the code. As it is the one to decide who lives. We have a TIME_LIMIT variable containing the 1-minute time to play the whole game. We start with calculating the time for the next Green Light 🟢 interval. This is the time when the doll is not seeing you and you will keep on pressing the Enter button. Also, we will subtract this time from our TIME_LIMIT with the help of time remaining a variable. Then SquidGameDoll the thread goes to sleep.

Once sleep time is over, it shows the Red Light 🔴 message. This is the time you should stop pressing enter immediately. It again sleeps for a BREATHER + some random time to observe players’ movement. And stores the last button pressed count to compare. If they don’t match it means you have pressed the button in Red Light 🔴 and the game is over for you and it sets the gameOver flag to true. So the player thread knows and stops accepting the inputs.

Otherwise, the game continues until the timeRemain is 0. Here is the code for SquidGameDoll the thread.

int timeRemain = TIME_LIMIT;
Random random = new Random();
do {
  // calculate time for "Mugunghwa Kkoci Pieot Seumnida"
  int dollCountingTime = random.nextInt(Math.min(timeRemain, GREEN_LIGHT_MAX_TIME)) + 1000;
  System.out.printf("%s Time remain: %d seconds (current score %d ): %n", GREEN_LIGHT, timeRemain / 1000, pressCount);
  System.out.println();

  // countdown the timer
  timeRemain -= dollCountingTime;

  // doll 👧 is now chanting "Mugunghwa Kkoci Pieot Seumnida"
  sleep(dollCountingTime);

  // Stop pressing enter now
  System.out.println(RED_LIGHT);

  // The Doll is now scanning for players' movement, Don't Move

  int lastPressedInGreenLight = pressCount;
  int scanningForMovements = random.nextInt(2000) + BREATHER;
  sleep(scanningForMovements); // Scanning for any movement
  timeRemain -= scanningForMovements;

  // IF player has moved (pressed enter in Red light time) game is over
  if (pressCount != lastPressedInGreenLight) {
    gameOver = true;
    pressCount = lastPressedInGreenLight;
    break;
  }
} while (timeRemain >= 0);

System.out.printf("%s: Your score is %d", GAME_OVER, pressCount);Code language: PHP (php)

The Players / You

The player that is you, will keep on pressing Enter Button until Red Light Message shows up. The code for it is pretty straightforward. it simply loops until the gameOver flag is false. It reads the Enter key press and increased the pressCount value.

// keep on reading Enter until game is over
while (!gameOver) {
  scanner.nextLine();
  pressCount++;
}Code language: JavaScript (javascript)

Consultation, Your Contributions and the Future of CodersTea Games PVT LTD

That’s it for this post. I hope you liked it. And will play the game in your free time as I do now. It’s pretty simple. However, I would like to make it better. Like Green and Red lights showing in a corner and you see your key pressed. Or I would say more interactive. If you have any idea about how we can do it, please let me know in the comments. Or you can do a pull request on GitHub.

The Full Code for Squid Game in Java: Red Light / Green Light

This is the single Java file that you can run right off the bat. I want a complete project and want to customize it, I would suggest pulling this GitHub project.

import java.util.Random;
import java.util.Scanner;

public class RedLightGreenLight {

  // Windows User may not be able to see actual Red Emoji
  private static final String RED_LIGHT = "Red Light 🔴 👧";
  private static final String GREEN_LIGHT = "Green Light 🟢 👧";
  private static final String GAME_OVER = "Game Over 🤯🔫 (press Enter)";

  private static final int TIME_LIMIT = 1000 * 60; //  1 Minute
  private static final int BREATHER = 500;
  private static final int GREEN_LIGHT_MAX_TIME = 4000;

  // game variables
  private static int pressCount = 0;
  private static boolean gameOver = false;

  private static Scanner scanner;

  public static void main(String[] args) throws InterruptedException {
    scanner = new Scanner(System.in);
    boolean continuePlaying = false;
    do {
      // resetting varibales
      pressCount = 0;
      gameOver = false;
      System.out.println("\n =============================");
      System.out.printf("Starting the Squid Game #1: %s / %s", RED_LIGHT, GREEN_LIGHT);
      System.out.println();
      System.out.println("When Green Light, Please press the Enter button continuously.");
      System.out.println("Stop pressing once you see Red light");

      Thread frontMan = new Thread(RedLightGreenLight::frontMan);
      Thread player = new Thread(RedLightGreenLight::player);

      // Starting the threads
      frontMan.start();
      player.start();

      // waiting threads to finish
      frontMan.join();
      player.join();

      System.out.println("============================");
      System.out.println("Do you want to continue?: [Y/N] : ");
      String next = scanner.next();
      continuePlaying = next.equalsIgnoreCase("Y");
    } while (continuePlaying); // if pressed Y, restart the game
  }

  private static void frontMan() {
    int timeRemain = TIME_LIMIT;
    Random random = new Random();
    do {
      // calculate time for "Mugunghwa Kkoci Pieot Seumnida"
      int dollCountingTime = random.nextInt(Math.min(timeRemain, GREEN_LIGHT_MAX_TIME)) + 1000;
      System.out.printf("%s Time remain: %d seconds (current score %d ): %n", GREEN_LIGHT, timeRemain / 1000, pressCount);
      System.out.println();

      // countdown the timer
      timeRemain -= dollCountingTime;

      // doll 👧 is now chanting "Mugunghwa Kkoci Pieot Seumnida"
      sleep(dollCountingTime);

      // Stop pressing enter now
      System.out.println(RED_LIGHT);

      // The Doll is now scanning for players' movement, Don't Move

      int lastPressedInGreenLight = pressCount;
      int scanningForMovements = random.nextInt(2000) + BREATHER;
      sleep(scanningForMovements); // Scanning for any movement
      timeRemain -= scanningForMovements;

      // IF player has moved (pressed enter in Red light time) game is over
      if (pressCount != lastPressedInGreenLight) {
        gameOver = true;
        pressCount = lastPressedInGreenLight;
        break;
      }
    } while (timeRemain >= 0);

    System.out.printf("%s: Your score is %d", GAME_OVER, pressCount);
  }

  private static void player() {
    // keep on reading Enter until game is over
    while (!gameOver) {
      scanner.nextLine();
      pressCount++;
    }
  }

  public static void sleep(int time) {
    try {
      Thread.sleep(time);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}Code language: PHP (php)

See you in the next post. HAKUNA MATATA!!!


I would be happy to connect with you guys on social media. It’s @coderstea on TwitterLinkedinFacebook, Instagram, and YouTube.

Please Subscribe to the newsletter to know about the latest posts from CodersTea.


Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ads
Ads
Ads

@2023 All Right Reserved. Designed and Developed by CodersTea

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More