繁体   English   中英

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

[英]Mars Mips creating a dice which shows 3 possible outcomes

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

.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显示 MARS 确实有一些 RNG 系统调用。 用它来索引你的数组。 在 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 配置为将数据部分放在地址空间的低 16kiB 中,因此我可以使用dice($reg)来索引数组。 如果你不这样做,你可以使用addu来做地址数学。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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