作业说明
循环 LOOP
Mult
The program assumes that R0>=0, R1>=0, and R0*R1<32768. Your program need not test these conditions, but rather assume that they hold.
本题在课程网站的作业说明中,明确给出了两个输入寄存器的值非负,简化了许多。
乘法就是多次加法,根据给的LOOP代码进行修改即可。
测试时需要先进行汇编,生成hack文件
提交时需要修改文件名,首字母大写
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/04/Mult.asm
// Multiplies R0 and R1 and stores the result in R2.
// (R0, R1, R2 refer to RAM[0], RAM[1], and RAM[2], respectively.)
// Put your code here.
@R0
D=M
@n
M=D // n = [R0]
@i
M=0 // i = 0 for(i=0; i < n; ++ i)
@sum
M=0 // sum = 0
(LOOP)
@i
D=M
@n
D=D-M
@STOP
D;JEQ // if i > n goto STOP
@sum
D=M
@R1
D=D+M
@sum
M=D // sum = sum + [R1]
@i
M=M+1 // i = i + 1
@LOOP
0;JMP
(STOP)
@sum
D=M
@R2
M=D // RAM[1] = sum
(END)
@END
0;JMP
Fill
伪代码:外循环永真,根据键盘是否输入遍历一遍屏幕,输出颜色。
int start = screen.start, end = screen.end;
while(true) {
if(keyborad is not pressed) {
for(int i = start; i < end; ++ i) {
//print white
}
} else {
for(int i = start; i < end; ++ i) {
//print black
}
}
}
测试前仍旧需要先汇编为hack文件,导入FillAutomatic.tst进行测试。
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/04/Fill.asm
// Runs an infinite loop that listens to the keyboard input.
// When a key is pressed (any key), the program blackens the screen,
// i.e. writes "black" in every pixel;
// the screen should remain fully black as long as the key is pressed.
// When no key is pressed, the program clears the screen, i.e. writes
// "white" in every pixel;
// the screen should remain fully clear as long as no key is pressed.
// Put your code here.
//note: write 2-layer loops
//the first loop is while(true) to chack if any key is push
//the second loop is for(int i=0; i < screen.size(); ++ i)
//this loop print white or black on screen.
//8192, 8K, the screen size
@8192
D=A
@end
M=D
(LOOP)
@SCREEN
D=A
@addr //base address
M=D
@i
M=0
@KBD
D=M //cheack the keyboard
@WHITE
D; JEQ
@BLACK
D; JNE
(WHITE)
@end
D=M
@i
D=D-M //if(end-i == 0) break into first loop
@LOOP
D;JEQ
@addr
A=M
M=0 //print 0
@i
M=M+1 //i++
@addr
M=M+1
@WHITE
0;JMP
(BLACK)
@end
D=M
@i
D=D-M //if(end-i == 0) break into first loop
@LOOP
D;JEQ
@addr
A=M
M=-1 //print -1
@i
M=M+1 //i++
@addr
M=M+1
@BLACK
0;JMP
作业提交
总结
本周作业更接近平时写的高级语言程序设计,相对上一周来说简单些。但需要直接操作寄存器,有些感觉应该一下子写好的东西,费了好久才能写出来。DEBUG也不是很容易。
视频有些长,看了一半就忘了一些,写的时候也就不熟练,难构思。也因此懈怠了,希望能保持每天学一点的节奏,更充实。