restart:
rdtime t3 # Get the time the program was started at

li a7,11 # Print character
li a0,0xa # \n
ecall
li t0,0 # Number of guesses

# Get a random number for the player to guess
li a7,128 # Get random integer
li a0,1 # Lower bound = 1
li a1,99 # Upper bound = 99
ecall
mv t1,a0 # Put the result in t1 where it's expected

loop:
# Increment number of guesses
addi t0,t0,1

# Prompt player to enter their guess
li a7,4 # Write string
la a0,prompt # 'Enter your guess' prompt address
ecall

# Read the player's guess
li a7,5 # Read integer
ecall
mv t2,a0 # Store it in t2

# Print it back out
li a7,1 # Write integer
ecall
li a7,11 # Write character
li a0,0xa # \n
ecall

# Replace it with a random number
li a0,0 # Lower bound = 0
li a1,100 # Upper bound = 100
li a7,128 # Get random integer
ecall
mv t2,a0

# Too low?
blt t2,t1,toolow

# Too high?
blt t1,t2,toohigh

# Otherwise it must be right
j correct

toolow:
# Show too low message
li a7,4 # Write string
la a0,toolowmsg
ecall
j loop # Go back for the next guess

toohigh:
# Show too high message
li a7,4 # Write string
la a0,toohighmsg
ecall
j loop # Go back for the next guess

correct:
# Show congratulations message
li a7,4 # Write string
la a0,correctmsg
ecall

# Show number of guesses
mv a0,t0 # Get the number of guesses
li a7,1 # Write integer
ecall

# Add proper suffix depending on whether it should be plural or not
li a7,4 # Write string
la a0,guessesmsg # "guess"
ecall
li t2,1
beq t0,t2,playagain # Leave it singular if it was 1
la a0,guessespluralize # "es"
ecall

playagain:
li a7,11 # Write character
li a0,0xa # \n
ecall
# Show the number of seconds the player took
rdtime t4 # Get the current time
sub a0,t4,t3 # Subtract the start time
li a7,1 # Write integer
ecall
li a7,4 # Write string
la a0,seconds
ecall

li a7,11 # Print character
li a0,0xa # \n
ecall

# Ask the user if they want to play again
li a7,4 # Write string
la a0,playagainmsg
ecall
li a7,12 # Read character
ecall
li a7,11 # Write character
ecall
li t0,0x6e # n
bne a0,t0,restart

li a7,10 # Exit program
ecall


prompt: .asciz "Enter your guess:\n> "
toolowmsg: .asciz "Too low! Try again\n"
toohighmsg: .asciz "Too high! Try again\n"
correctmsg: .asciz "Correct!\nYou got it in:\n"
guessesmsg: .asciz " guess"
guessespluralize: .asciz "es"
seconds: .asciz " seconds"
playagainmsg: .asciz "Play again? [Y/n]"
