1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
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]"
|