簡體   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