A little game I wrote

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

A little game I wrote

eXtc_be
This post was updated on .
After 9 attempts to optimize my VMTranslator (I got the complete OS down to 31.592 lines (from 42.495 without optimizations), and, although there is plenty of space to be gained by other optimizations as described in other threads on this forum, I feel like that is not the goal of the book, so I left it at that) and a hiatus of several years I finally decided to continue my journey with Nand2Tetris.

After rereading chapters 1-8 as a refresher, I have now finished reading chapter 9. The project section of this chapter encourages the reader to adopt or invent an application idea like a simple computer game or some other interactive program and to implement this application in Jack.

My little game isn't nearly as sophisticated as some others I've seen on here, but the goal of the chapter was to familiarize oneself with the Jack language and standard library, not to become an expert Jack programmer.
It is small enough to not need a repository, so here it is:

// Main.jack -- Number guessing game
// Copyright (C) 2023, eXtc_be.

class Main {
    function void main() {
        var int g;
        var int r;
        var int i;
        var int j;
        var int c;
        var LFSR32Rand lfsr;

        let i=0;
        do Output.printString("Press any key to start.");
        //wait for a keypress
        while(Keyboard.keyPressed()=0){
            let i=i+1;
        }
        //wait for a key release
        let j=0;
        while(~(Keyboard.keyPressed()=0)){
            let j=j+1;
        }
        do Output.println();
        do Output.println();
        
        let lfsr = LFSR32Rand.new();
        do lfsr.seed(i,j);
        let r=lfsr.randRange(1,100);
        
        do Output.printString("Guess my number (1-100).");
        do Output.println();
        do Output.println();

        let g=-1;
        let i=0;
        
        while(~(g=r)){
            let g=Keyboard.readInt("Enter your guess: ");
            if(g>r){
                do Output.printString("Too big.");
                do Output.println();
            }
            if(g<r){
                do Output.printString("Too small.");
                do Output.println();
            }
            let i=i+1;
        }
        
        do Output.printString("You got it!");
        do Output.println();
        do Output.printString("It took you only ");
        do Output.printInt(i);
        do Output.printString(" tries!");
        do Output.println();

        return;
    }
}

The aim of the game is to guess, in as few attempts as possible, a number between 1 and 100.
Besides the OS files you will also need LFSR32Rand by Rowan Limb, which can be found on this forum.