简体   繁体   中英

Mars Mips creating a dice which shows 3 possible outcomes

im doing an assigment in school to make a program that shows three possible outcomes for a dice, used an array for this but i can only make it loop through the array and print all values rather than choosing a single when where all three outccomes have different probabilties.

.data

dragon: .asciiz "Dragon"
orc: .asciiz "Orc"
sword: .asciiz "sword"

dice: .word dragon, dragon, dragon, dragon, dragon, orc, orc, orc,
sword, sword, sword, sword

iterator: .word 0
size: .word 11

.text
main:

la $t0, dice
lw $t1, iterator
lw $t2, size     

beginLoop: bgt $t1, $t2, exitLoop     
sll $t3, $t1, 2     
addu $t3, $t3, $t0     
addi $t1, $t1, 1           
li $v0, 4
lw $a0, 0($t3)
syscall    
j beginLoop

exitLoop: li $v0, 10
syscall

https://courses.missouristate.edu/KenVollmar/MARS/Help/SyscallHelp.html shows that MARS does have some RNG system calls. Use that to index your array. Using a random number generator in MIPS?

You don't even have to map a random 32-bit integer to your range; MARS does that for you if you use syscall 42 instead of 41. The syscall takes the ID # of a RNG as an input, but it seems you don't need to initialize it, just use 0

.data
dragon: .asciiz "Dragon\n"
orc: .asciiz "Orc\n"
sword: .asciiz "Sword\n"

# this can't be line-wrapped, unless you use another .word directive
dice: .word dragon, dragon, dragon, dragon, dragon, orc, orc, orc, sword, sword, sword, sword
#.equ die_size, (. - dice)/4
#die_size = (. - dice)/4
.eqv die_size, 12        # 11 + 1
 # MARS built-in assembler is crap and can't calculate the size for us at assemble time.


.text
main:
    li $v0, 42             # Service 42, random int range
    li $a0, 0              # Select random generator 0
    li $a1, die_size      # upper bound of range (non-inclusive)
    syscall                # invoke the system call, returns in $a0
# $a0 is in the range [0..12), i.e. 0..11

    sll  $a0, $a0, 2        # scale by size of word, $a0 is a byte index into pointer array

    lw $a0, dice($a0)
    li $v0, 4            # print string
    syscall

    li  $v0, 17
    li  $a0, 0
    syscall       # exit(0) because MARS doesn't support returning from main!?!
    #    jr $ra

I have my MARS configured to put the data section in the low 16kiB of address space so I can use dice($reg) to index the array. If you don't do that, you can use addu to do address math.

MARS's built-in assembler really sucks, and seems to force you to hard-code the size of the array as a literal number. In a real assembler like GAS, you'd use .equ die_size, (. - dice)/4 + 1 to calculate it at assemble time from the number of elements in the pointer array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM