Skip to content

Instantly share code, notes, and snippets.

@tremblerz
Forked from charlesrubach/guess.asm
Created February 11, 2016 19:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tremblerz/ab041ef0055ec0c91736 to your computer and use it in GitHub Desktop.
Save tremblerz/ab041ef0055ec0c91736 to your computer and use it in GitHub Desktop.
Guessing game in MIPS
.include "macros.asm"
.data
# arrays
variables: .space 16 # [random number][low][high][guesses]
range: .byte 100 # Set the range [0 t0 range]
# Constant strings
guess1: .asciiz "Guess a number between "
guess2: .asciiz " and "
guess3: .asciiz ": "
newline: .asciiz "\n"
success_message: .asciiz "You guessed it! Total guesses: "
error_message: .asciiz "The range is too narrow\n"
.text
j main # Jump to main
# Initialize the variables array / struct
init:
# Generate random number to guess
lb $s0, range # load range into temp register
blt $s0, 3, error # if the range is less than 3 then exit
subi $s0, $s0, 2 # Subtract 2 to shift range
la $a1, ($s0)
li $v0, 42
syscall
addi $a0, $a0, 1 # Add 1 to shift the range 1 to [range - 1]
# variables[0] = random number
addi $t0, $zero, 0
sw $a0, variables($t0)
# variables[1] = low number
addi $t0, $t0, 4
li $s0, 0
sw $s0, variables($t0)
# variables[2] = range (high number)
addi $t0, $t0, 4
lb $s0, range
sw $s0, variables($t0)
# variables[3] = guesses
addi $t0, $t0, 4
li $s0, 0
sw $s0, variables($t0)
jr $ra
print_prompt:
li $v0, 4
la $a0, guess1
syscall
addi $t0, $zero, 4
lw $t1, variables($t0)
li $v0, 1
la $a0, ($t1)
syscall
li $v0, 4
la $a0, guess2
syscall
addi $t0, $t0, 4
lw $t1, variables($t0)
li $v0, 1
la $a0, ($t1)
syscall
li $v0, 4
la $a0, guess3
syscall
jr $ra
success:
li $v0, 4
la $a0, success_message
syscall
# Print guess count
addi $t0, $zero, 12
li $v0, 1
lw $a0, variables($t0)
syscall
j exit
main:
jal init
while:
jal print_prompt # Print prompt
# Get the user's age
li $v0, 5 # system code to get input from the user (5)
syscall
# Store the result in $t2
la $t2, ($v0)
addi $t0, $zero, 0
lw $t1, variables($t0)
# If input equals the number to guess go to success
beq $t1, $t2, success
# If input is less than number to guess set low to input
blt $t1, $t2, input_high
addi $t0, $zero, 4
sw $t2, variables($t0)
j increment_guess_count
# Else set high to input
input_high:
addi $t0, $zero, 8
sw $t2, variables($t0)
increment_guess_count:
addi $t0, $zero, 12
lw $t2, variables($t0)
addi $t2, $t2, 1
sw $t2, variables($t0)
# Continue while loop
j while
error:
li $v0, 4
la $a0, error_message
syscall
exit:
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment