3

I'm trying to make a number guessing game in assembly code that starts out with a range of 1 to 1, then increments by 1 each time you get the answer right.

For some reason though when I run the program the number that is output for range is incredibly high instead of 1, and when I type in 1 which is the answer for the first round it says I lose instead of continuing. So if anyone could help me with those problems that would be great!

 include \masm32\include\masm32rt.inc

.data

formatString BYTE  "guess a number from 1 to %d , if you get it right you continue", 0ah, 0dh, 0 
guessstr BYTE  11 DUP (0)
guess DWORD ?
range DWORD 0
answer DWORD 1
prompt BYTE  "You lose!", 0

.code
main proc
    call seedrand

nextlevel:
    move eax, 0
    mov range, ebx
    add ebx, 1
    pushd ecx
    call randnum
    invoke crt_printf, ADDR formatString, ebx
    invoke StdIn, ADDR guessstr, 10
    invoke atodw, ADDR guessstr
    mov guess, edx
    add ecx, 1

    cmp eax, ebx
    je nextlevel

    invoke StdOut, ADDR prompt
    jnz skip

seedrand proc
    ; seeds the random number generator
    ; _stdcall
    invoke GetTickCount ; result goes in eax
    invoke nseed, eax

    ret
seedrand endp

randomnum proc
    ; generate a random number
    ; _stdcall
    mov eax, [esp+4]
    invoke nrandom, eax

    ret 4
randomnum endp


skip:

    ; return 0
    mov eax, 0
    ret

main endp
end main
Sep Roland
  • 33,889
  • 7
  • 43
  • 76
student
  • 57
  • 1
  • 5
  • These all sounds like good plans. Unfortunately, you have failed to actually ask a question. – David Hoelzer Apr 11 '16 at 19:36
  • I edited it, i guess i mentioned the problems, but didn't actually ask for help with them – student Apr 11 '16 at 19:45
  • 2
    So what do you see when you single-step in a debugger? At what point is there a taken branch that you expected not to be taken, or a register with a value that isn't what you expected? Learning to use a debugger for asm is absolutely essential. – Peter Cordes Apr 11 '16 at 20:13

1 Answers1

2
move eax, 0

This is not a valid instruction. Could it be that you meant to initialize the upper limit? Because that's something you forgot! Replace it by xor ebx, ebx

cmp eax, ebx
je nextlevel

You just moved the user's guess from the EDX register to the guess variable. Here you should be comparing with one of these, certainly not with the upper limit.

invoke StdOut, ADDR prompt
jnz skip
;
seedrand proc

After displaying "You lose!" you fall through in the seedrand procedure. Better use jmp skip.

Sep Roland
  • 33,889
  • 7
  • 43
  • 76