Tamagotchi and Giga Pets were small electronic devices which simulated a little virtual pet. This pet had several stats, like health, hunger, etc.
I recently wrote this example:

import msvcrt,os,sys;d=m=100;h=s=t=p=0;f=10
while 1:
 os.system('cls'if os.name=='nt'else'clear');print("health:",d,"\nhunger:",h,"\nsleep:",s,"\nfood:",f,"\npotions:",p,"\nmoney:",m);t+=1
 if msvcrt.kbhit():
  if k==102 and h>8 and f:f-=1;h-=9
  if k==115:s=0
  if k==112 and p:p-=1;d+=9
  if k==98 and m>8:m-=9;p+=1
  if k==116 and m>8:m-=9;f+=1
 if t>99:
  if s>80:s=0;h+=9
  if h>80:d-=1
  if d<1:sys.exit(0)
  if d>79:m+=1

This is a bare-bones virtual pet in 467 bytes! I then wondered how well the code golf pros could do, so now, the challenge.

The Challenge

Make a program that tracks 6 stats of a virtual pet, and updates them over time and in response to user input. The stats are: health and money (starting at 100), food (starting at 10), and hunger, sleep, and potions (starting at 0).

The program should update the values in response to the following events:

  • While the program is receiving no input, it should perform updates at regular intervals (the interval between updates should not be shorter than half a second nor longer than one second). Each update does the following:

    • Hunger and Sleep each increase by 1.
    • If Hunger is 80 or above, Health decreases by 1.
    • If Sleep is 80 or above, it is reset to 0, and Hunger increases by an additional 9.
    • If Health is 80 or above, Money increases by 1.
    • If Health is 0, the program exits.
  • The program must also respond immediately upon the following keypresses by the user (this means that you will need to use a language feature or library that can detect a key being pressed and respond to it immediately, rather than just reading from standard input), performing the following actions:

    • f: If Hunger is greater than 8 and Food is nonzero, then Food is decreased by 1 and Hunger is decreased by 9.
    • s: Sleep is reset to 0.
    • p: If Potions is greater than zero, Potions is decreased by 1 and Health is increased by 9.
    • b: If Money is greater than 8, then Money is decreased by 9 and Potions are increased by 1.
    • t: If Money is greater than 8, then Money is decreased by 9, and Food is increased by by 1.

Whenever the values of the stats change, they must be displayed on screen in the form Stat: value. All six stats must be displayed whenever any of them changes; and the stats within a display must be separated either by commas or by newlines.

This challenge follows normal rules: the shortest program complying with the specification above wins. (Note that as usual, if the language is newer than the competition, the submission must be marked as non-competing.)

  • \$\begingroup\$ You don't say what the starting stats are \$\endgroup\$
    – Blue
    Nov 23, 2016 at 21:02
  • 1
    \$\begingroup\$ Outputs must be in a "easy to read manner" is ambiguous, and so it "once per-second ish". You should submit challenges to the sandbox to get feedback and improve them before you post to main... \$\endgroup\$
    – FlipTack
    Nov 23, 2016 at 21:07
  • 1
    \$\begingroup\$ How is this unclear? I wish unclear had more details, because itself is unclear. \$\endgroup\$ Nov 24, 2016 at 2:53
  • 2
    \$\begingroup\$ Sandbox doesn't help anymore, as there are answers already. The people who've marked this as unclear should say why it's unclear, instead of being unclear themselves. \$\endgroup\$ Nov 24, 2016 at 15:40
  • 1
    \$\begingroup\$ @BlueEyedBeast (and other close voters) I'm also curious as to what is unclear. The original version had some significant issues, but it seems like the edits fixed that. At the very least, it was clear enough for Carcigenicate and I to provide submissions. Share some details about what you find unclear so ender_scythe can improve it. \$\endgroup\$
    – Ray
    Nov 26, 2016 at 7:19

5 Answers 5


C, 424 406 386 357 bytes

#define x(a,b,c)if(*#a==C){if(b>8){c-=9;}Z=0;}
L,M=100,H,S=-1,F=10,P,Z,C;t(){H++;S++;L-=H>79;if(S>79)S=0,H+=9;Z=1/L/2;alarm(1);}main(){nodelay(initscr(),L=M);signal(14,t);for(t(H=S);C=getch();Z=Z||printf("\rhealth: %d,hunger: %d,sleep: %d,food: %d,potions: %d,money: %d\n",L,H,S,F,P,M)){x(s,9,S=9;S)x(p,P+8,P--;L+=18;L)x(f,H,F--;H)x(b,M,P++;M)x(t,M,F++;M)}}

I appreciate the need for raw input and asynchronous updates in the problem spec. Even though that required some overhead from the ncurses setup and signal handlers, it's nice to have the occasional challenge that (hopefully) won't be automatically won by one of the dedicated golfing languages.

You didn't specify exactly how game over is indicated, so this one perishes with the traditional Tamagotchi death cry of "Floating point exception (core dumped)".


/* Playing a bit fast and loose with the prototyping rules by omitting these;
 * none of the functions I'm using from them *exactly* match the default
 * prototype of `int f();`
//#include <curses.h>
//#include <stdio.h>
//#include <signal.h>
//#include <unistd.h>

#define x(a,b,c)if(*#a==C){if(b>8){c-=9;}Z=0;}

t() {
    Z=1/L/2;//0 if L>0. otherwise the pet dies of a floating point error

    for(t(H=S); C=getch(); Z=Z||printf("\rhealth: %d,hunger: %d,sleep: %d,food: %d,potions: %d,money: %d\n",L,H,S,F,P,M)){

PHP, 396 413 bytes

(Dang, my first code golf entry that I had to edit up in byte count. Edited to remove sleep() call, as it wasn't really complying with rules-as-intended.)

Requires a unix-ish OS for the non-blocking STDIN. Oddly, using switch/case versus cascading if/else produced shorter source code, but the subsequent compressed version was longer.



shell_exec('stty -icanon');
stream_set_blocking(STDIN, 0);
$u = $s = $p =0;
$f = 10;
$h = $m = 100;
while(1) {
        if (($k = fgetc(STDIN)) || time() > $t)
    if ($k == 'f'){
        if ($u > 8 && $f) --$f | $u -= 9;
    } elseif ($k == 's')
        $s = 0;
    elseif ($k == 'p') {
        if ($p) --$p | $h += 9;
    } elseif ($k == 'b') {
        if ($m > 8) $m -= 9 | ++$p;
    } elseif ($k == 't') {
        if ($m > 8) $m -= 9 | ++$f;
    } else {
        if (++$u > 79) --$h;
        if (++$s > 79) $s = 0 | $u += 9;
        if ($h > 79) ++$m;
        if ($h < 1) exit;
  • \$\begingroup\$ This doesn't "respond immediately upon the following keypresses by the user". It waits until the call to sleep(1) returns before processing input. Although it does process any queued commands before doing the next update, so it might be fine. \$\endgroup\$
    – Ray
    Nov 28, 2016 at 21:31
  • \$\begingroup\$ Yeah, noted. The wording there was a big vague so I took some liberty on the interpretation because this way was shorter. :) If I have time today, I'll code up the alternative solution with a timed loop and present both for consideration. \$\endgroup\$ Nov 29, 2016 at 15:07

Mathematica, 374 bytes

Health: ",h,"
Money: ",m,"
Food: ",f,"
Hunger: ",g,"
Sleep: ",s,"
Potions: ",p}]

The line breaks are important because they are newline characters in the string so I could use Row instead of Column. If you evaluate this in a Mathematica notebook you should see something like this:

Tamagotchi simulation

You have to click in the input field and quickly (less than a second) type your character before Dynamic causes the input field to update. This headache could be avoided entirely if the EventHandler was in its own cell rather than being an element of Row, but that would require saving the program as a .nb file which would greatly increase the byte count.

  • \$\begingroup\$ Nice work! I was going to use a structure like CurrentValue[EvaluationNotebook[], NotebookEventActions] = {"KeyDown" :> Switch[CurrentValue@"EventKey", "f", If[g > 8 && f > 0, f--; g -= 9], "s", s = 0, "p", If[p > 0, p--; h += 9], "b", If[m > 8, m -= 9; p++], "t", If[m > 8, m -= 9; f++]]}; ... this should let you avoid the need to click in an input field. Adding the option , PassEventsDown -> True to the end of that code will let you continue to edit the notebook, but can be removed at the very end for byte savings :) \$\endgroup\$ Nov 29, 2016 at 23:19
  • \$\begingroup\$ Thanks, that's exactly the functionality I was looking for initially! Unfortunately it seems it's longer than what I currently have. \$\endgroup\$
    – user61980
    Nov 29, 2016 at 23:31

C#6, 567 563 bytes

using System;using System.Threading;class T{int L,M,F=10,H,S,P;static void Main(){T t=new T();}T(){M=L=100;var W=new Thread(new ThreadStart(Q));W.Start();while(1>0){var r=Console.Read();bool B=0>1,K=1>0;if(r=='f'&H>8&F>0){F--;H-=9;B=K;}if(r=='s'){S=0;B=K;}if(r=='p'&P>0){P--;L+=9;B=K;}if(r=='b'&M>8){M-=9;P++;B=K;}if(r=='t'&M>8){M-=9;F++;B=K;}if(B)p();}}void Q(){while(1>0){H++;S++;if(H>79)L--;if(S>79){S=0;H+=9;}if(L>79)M++;L*=L/L;p();Thread.Sleep(500);}}void p(){Console.Write($"\nhealth: {L}\nhunger: {H}\nsleep: {S}\nfood: {F}\nmoney: {M}\npotions: {P}\n");}}


using System;
using System.Threading;
class T
    int L,M,F=10,H,S,P;
    static void Main()
        T t=new T();
        var W=new Thread(new ThreadStart(Q));
            var r=Console.Read();
            var B=0>1;
    void Q()
    void p()
        Console.Write($"\nhealth: {L}\nhunger: {H}\nsleep: {S}\nfood: {F}\nmoney: {M}\npotions: {P}\n");

Clojure, 1224 702 bytes


Made all the atoms loose variables instead of being inside a state object. That alone got rid of a lot of code. I also created the shortcut functions a! and s! to add and subtract from the atoms easier (basically acting as += and -=, since Clojure doesn't have those operators).

I realized that I could probably do away with atoms if I manage to integrate key input into a loop. I'll have to see.

(ns bits.golf.pet.v2.petms)(def h(atom 100))(def j(atom 0))(def s(atom 0))(def f(atom 10))(def p(atom 0))(def m(atom 100))(defn a[sa n](swap! sa #(+ % n)))(defn v[sa n](swap! sa #(- % n)))(defn c[](a j 1)(a s 1)(if(>=@j 80)(v h 1))(if (>=@s 80)(do(reset! s 0)(a j 9)))(if(>= @h 80)(a m 1)))(defn l[k](case k\f(if(> @j 8)(do(v f 1)(v j 9)))\s(reset! s 0) \p(if(>@p 0)(do(v p 1)(a h 9)))\b(if(> @m 8)(do(v m 9)(a p 1)))\t(if(>@m 8)(do(v m 9)(a f 1)))nil))(defn b[](.start(Thread.^Runnable(fn[](while(>@h 0)(l(first (read-line))))))))(defn -main[](b)(while(>@h 0)(Thread/sleep 500)(c)(println(str"Health: "@h"\nHunger: " @j"\nSleep: "@s"\nFood: "@f"\nPotions: "@p"\nMoney:"@m"\n")))(println"You died!\n"))


(ns bits.golf.pet.v2.pet)

; 100 0 0 10 0 100
(def he (atom 100))
(def hu (atom 0))
(def sl (atom 0))
(def fo (atom 10))
(def po (atom 0))
(def mo (atom 100))

(defn a! [sa n]
  (swap! sa #(+ % n)))

(defn s! [sa n]
  (swap! sa #(- % n)))

(defn apply-rules []
    (a! hu 1)
    (a! sl 1)
    (if (>= @hu 80)
      (s! he 1))
    (if (>= @sl 80)
        (reset! sl 0)
        (a! hu 9)))
    (if (>= @he 80)
      (a! mo 1)))

(defn handle-keypress [k]
    (case k
      \f (if (> @hu 8)
             (s! fo 1)
             (s! hu 9)))
      \s (reset! sl 0)
      \p (if (> @po 0)
             (s! po 1)
             (a! he 9)))
      \b (if (> @mo 8)
             (s! mo 9)
             (a! po 1)))
      \t (if (> @mo 8)
             (s! mo  9)
             (a! fo 1)))

(defn start-listener []
    (Thread. ^Runnable
      (fn []
        (while (> @he 0)
            (handle-keypress (first (read-line))))))))

(defn -main []
  (while (> @he 0)
    (Thread/sleep 500)


    (println (str
               "Health: " @he "\n"
               "Hunger: " @hu "\n"
               "Sleep: " @sl "\n"
               "Food: " @fo "\n"
               "Potions: " @po "\n"
               "Money:" @mo "\n")))

  (println "You died!\n"))


Ohdeargod. Definitely room for improvement here. This kind of problem is easiest to do with side effects, and Clojure is functional, so I'm trying to abuse atoms to lessen the amount of code needed. Unfortunately, I didn't go in with a plan, so it's kind of haphazard right now. I've already gotten a few ideas to shrink I though.

It's a full program. It can be run by running -main.

(ns bits.golf.pet)(defrecord S[he hu sl fo po mo])(def new-state(->S 100 0 0 10 0 100))(def state(atom new-state))(defn update![sa k f](swap! sa #(update % k f)))(defn apply-rules[s](let [s' (atom s)u! #(update! s' %1 %2)g #(get @s' %)](u! :hu inc)(u! :sl inc)(if(>=(g :hu)80)(u! :he dec))(if(>= (g :sl)80)(do(u! :sl (fn[_]0))(u! :hu #(+ % 9))))(if(>=(g :he)80)(u! :mo inc))@s'))(defn get-input [](let [raw (read-line)](first raw)))(defn handle-keypress[s k](let [s'(atom s)u! #(update! s' %1 %2)g #(get @s' %)](case k\f(if (> (g :hu)8)(do(u! :fo dec)(u! :hu #(- % 9))))\s(u! :sl (fn [_] 0))\p(if(> (g :po)0)(do(u! :po dec)(u! :he #(+ % 9))))\b(if(>(g :mo))(do(u! :mo #(- % 9))(u! :po inc)))\t(if(>(g :mo)8)(do(u! :mo #(- % 9))(u! :fo inc)))nil@s')))(defn start-listener[](.start(Thread.^Runnable(fn[](while true(let[k(get-input)](swap! state #(handle-keypress % k))))))))(defn -main[](start-listener)(let[g #(get @%1 %2)](while true(Thread/sleep 500)(swap! state #(apply-rules %))(println(str"Health: "(g state :he)"\nHunger: "(g state :hu)"\n""Sleep: " (g state :sl)"\nFood: "(g state :fo)"\nPotions: "(g state :po)"\n""Money:"(g state :mo)"\n"))(if(<=(g state :he)0)(do(println"You died!\n")(reset! state new-state))))))


(ns bits.golf.pet)

(defrecord State [he hu sl fo po mo])

(def new-state (->State 100 0 0 10 0 100))

(def state (atom new-state))

(defn update! [sa k f]
  (swap! sa #(update % k f)))

(defn apply-rules [s]
  (let [s' (atom s)
        u! #(update! s' %1 %2)
        g #(get @s' %)]
    (u! :hu inc)
    (u! :sl inc)
    (if (>= (g :hu) 80)
      (u! :he dec))
    (if (>= (g :sl) 80)
        (u! :sl (fn [_] 0))
        (u! :hu #(+ % 9))))
    (if (>= (g :he) 80)
      (u! :mo inc))

(defn get-input []
  (let [raw (read-line)]
    (first raw)))

(defn handle-keypress [s k]
  (let [s' (atom s)
        u! #(update! s' %1 %2)
        g #(get @s' %)]
    (case k
      \f (if (> (g :hu) 8)
             (u! :fo dec)
             (u! :hu #(- % 9))))
      \s (u! :sl (fn [_] 0))
      \p (if (> (g :po) 0)
             (u! :po dec)
             (u! :he #(+ % 9))))
      \b (if (> (g :mo))
             (u! :mo #(- % 9))
             (u! :po inc)))
      \t (if (> (g :mo) 8)
             (u! :mo #(- % 9))
             (u! :fo inc)))

(defn start-listener []
    (Thread. ^Runnable
      (fn []
        (while true
          (let [k (get-input)]
            (swap! state #(handle-keypress % k))))))))

(defn -main []
  (let [g #(get @%1 %2)]
    (while true
      (Thread/sleep 500)

      (swap! state #(apply-rules %))

      (println (str
                 "Health: " (g state :he) "\n"
                 "Hunger: " (g state :hu) "\n"
                 "Sleep: " (g state :sl) "\n"
                 "Food: " (g state :fo) "\n"
                 "Potions: " (g state :po) "\n"
                 "Money:" (g state :mo) "\n"))

      (if (<= (g state :he) 0)
          (println "You died!\n\n\n\n\n")
          (reset! state new-state))))))
  • \$\begingroup\$ That's a nice amount of code there. \$\endgroup\$ Nov 23, 2016 at 23:51
  • \$\begingroup\$ @ender_scythe Ya. I was trying to adhere to half-decent coding practices in some places, like making applying-rules and handle-keypress pure. I'm writing a "screw-it" version right now. \$\endgroup\$ Nov 23, 2016 at 23:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.