Mars Mips 创建一个显示 3 种可能结果的骰子

Mars Mips creating a dice which shows 3 possible outcomes

我在学校做一个作业来制作一个显示骰子三种可能结果的程序,为此使用了一个数组,但我只能让它遍历数组并打印所有值,而不是选择一个 when when where这三种结果都有不同的概率。

.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?

您甚至不必将随机的 32 位整数映射到您的范围;如果您使用系统调用 42 而不是 41,MARS 会为您执行此操作。系统调用将 RNG 的 ID # 作为输入,但您似乎不需要初始化它,只需使用 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

我将我的 MARS 配置为将数据部分放在地址 space 的低 16kiB 中,因此我可以使用 dice($reg) 来索引数组。如果你不这样做,你可以使用 addu 来计算地址。

MARS 的内置 assembler 真的很糟糕,似乎迫使您将数组的大小硬编码为文字数字。在像 GAS 这样的真实 assembler 中,您将使用 .equ die_size, (. - dice)/4 + 1 根据指针数组中元素的数量在 assemble 时间计算它。