TITLE Drunkard's Walk (Walk.asm)
; Drunkard's walk program. The professor starts at
; coordinates 25,25 and wanders around the immediate area.
INCLUDE Irvine32.inc
WalkMax = 50
StartX = 25
StartY = 25
StartWalk = 0
DrunkardWalk STRUCT
path COORD WalkMax DUP(<0,0>)
pathsUsed WORD 0
huo word WalkMax dup (0)
DrunkardWalk ENDS
DisplayPosition PROTO currX:WORD, currY:WORD , losephone:WORD
.data
aWalk DrunkardWalk <>
.code
main PROC
mov esi,OFFSET aWalk
call TakeDrunkenWalk
exit
main ENDP
;-------------------------------------------------------
TakeDrunkenWalk PROC
LOCAL currX:WORD, currY:WORD, losephone:WORD, RM1:dword, RM2:dword, cool:dword
;
; Take a walk in random directions (north, south, east,
; west).
; Receives: ESI points to a DrunkardWalk structure
; Returns: the structure is initialized with random values
;-------------------------------------------------------
pushad
; Use the OFFSET operator to obtain the address of
; path, the array of COORD objects, and copy it to EDI.
mov edi,esi
add edi,OFFSET DrunkardWalk.path
mov ecx,WalkMax ; loop counter
mov currX,StartX ; current X-location
mov currY,StartY ; current Y-location
call Randomize
mov eax,WalkMax
call RandomRange
mov ebx,eax
mov edx,esi
add edx,OFFSET DrunkardWalk.huo
Again:
; Insert current location in array.
mov ax,currX
mov (COORD PTR [edi]).X,ax
mov ax,currY
mov (COORD PTR [edi]).Y,ax
dec ebx
cmp ebx,0
jne L1
mov (DrunkardWalk PTR [edx]).huo,1
jmp L2
L1:
mov (DrunkardWalk PTR [edx]).huo,0
L2:
mov ax,(DrunkardWalk PTR [edx]).huo
mov losephone,ax
INVOKE DisplayPosition, currX, currY, losephone
call Randomize
mov eax, 2 ; choose a direction (0-1)
call RandomRange
mov RM1, eax
call Randomize
mov eax, 4 ;在(0-4)间生成随机数
call RandomRange
mov RM2, eax
mov cool,0
cmp RM1, 0
je L7 ;50%的概率重复上一步,RM1为零则重复,为一则可能不重复
L9:
cmp RM2, 0
jne L10 ;RM2为零则向东前进 ,以此类推
L3:
mov cool,0 ;向方向计数器放入代表方向的数字
inc currX
jmp L8
L10:
cmp RM2, 1 ;
jne L12
L4:
mov cool,1
dec currX
jmp L8
L12:
cmp RM2, 2
jne L11
L5:
inc currY
mov cool,2
jmp L8
L11:
cmp RM2, 3
jne L13
L6:
mov cool,3
dec currY
jmp L8
L13:
cmp cool,0 ;RM2为4则根据方向计数器的指示向反方向行走
je L4
cmp cool,1
je L3
cmp cool,2
je L6
cmp cool,3
je L5
L7:
cmp cool, 0 ;RM1为0则根据方向计数器向相同方向前进
je L3
cmp cool, 1
je L4
cmp cool, 2
je L5
cmp cool, 3
je L6
L8:
add edi,TYPE COORD ; point to next COORD
add edx,type DrunkardWalk.huo
dec ecx
cmp ecx,0
je Finish
jmp Again
Finish:
mov (DrunkardWalk PTR [esi]).pathsUsed, WalkMax
popad
ret
TakeDrunkenWalk ENDP
;-------------------------------------------------------
DisplayPosition PROC currX:WORD, currY:WORD, losephone:WORD
; Display the current X and Y positions.
;-------------------------------------------------------
.data
commaStr BYTE ",",0
.code
pushad
movzx eax,currX ; current X position
call WriteDec
mov edx,OFFSET commaStr ; "," string
call WriteString
movzx eax,currY ; current Y position
call WriteDec
mov edx,offset commaStr
call WriteString
movzx eax,losephone
call WriteDec
call Crlf
popad
ret
DisplayPosition ENDP
END main