DEV Community

Cover image for Rock, Paper, Scissors on 1 Tweet
Juan Carlos
Juan Carlos

Posted on • Edited on

Rock, Paper, Scissors on 1 Tweet

This is my "Rock, Paper and Scissors" Game on 1 Tweet.

import random

randomize()
echo "Rock r\nPaper p\nScissor s"

let
  o = ["rock", "paper", "scissor"]
  pc = rand 0 .. 2
  us = case stdin.readLine[0]
    of 'r': 0
    of 'p': 1
    else:   2

echo "\nPC\tYou\tWinner\n", o[pc], '\t', o[us], '\t', case (3 + pc.ord - us.ord) mod 3
  of 1: "PC"
  of 2: "You"
  else: "No"

Enter fullscreen mode Exit fullscreen mode

How to run the code:

$ nim r file.nim

Rock    r
Paper   p
Scissor s

p

PC      You     Winner
paper   paper   No

$
Enter fullscreen mode Exit fullscreen mode

Keys:

  • Rock = r
  • Paper = p
  • Scissors = s

It is not even too code-golfed, because we can remove the line import random by compiling with --import:random.

We can remove the randomize() but then we need to recompile to make the PC choose another option, so is not a good idea.

It uses the random module from standard library:
https://nim-lang.github.io/Nim/random.html

case switch from from standard library:
https://nim-lang.github.io/Nim/manual.html#statements-and-expressions-case-statement

readLine to read a line from standard input:
https://nim-lang.github.io/Nim/io.html#readLine%2CFile

  • How your Rock, Paper and Scissors game looks like?

Thank you for reading

Come learn programming with us...
👑

Top comments (0)