includelib libcmt.lib
includelib libvcruntime.lib
includelib libucrt.lib
includelib legacy_stdio_definitions.lib

.386
.MODEL flat,stdcall 
.STACK 4096
STD_INPUT_HANDLE EQU -10 ;https://docs.microsoft.com/en-us/windows/console/getstdhandle
STD_OUTPUT_HANDLE EQU -11
GetStdHandle PROTO nStdHandle:DWORD
WriteConsoleA PROTO hConsoleOutput:DWORD, ;https://docs.microsoft.com/en-us/windows/console/writeconsole
					lpBuffer:PTR BYTE, 
					nNumberOfCharsToWrite:DWORD, 
					lpNumberOfCharsWritten:PTR DWORD, 
					lpReserved:DWORD 
ReadConsoleA PROTO hConsoleInput:DWORD, ;https://docs.microsoft.com/en-us/windows/console/readconsole
				   lpBuffer2:PTR BYTE,
				   nNumberOfCharsToRead:DWORD,
				   lpNumberOfCharsRead:PTR DWORD,
				   pInputControl:PTR BYTE

ExitProcess PROTO dwExitCode:DWORD 

extern rand:NEAR
extern time:NEAR
extern srand:NEAR
extern _getch:NEAR

.data
game_randomNumber dd ?
charsWritten dd ? 
msg_enternumber db "Guess a number between 0 and 9: ",0;33
msg_win db "Congratulations, your number matches the random!",13,10 ;50
msg_lose db "Sorry, your number doesn't match the random!",13,10 ;46
;lpBufferStorage db BUFFER_SIZE dup(?)
consoleHandleOutput dd ?
consoleHandleInput dd ?

.code
main PROC C
	LOCAL buffer[128]:BYTE	              

	push STD_OUTPUT_HANDLE
	call GetStdHandle
	mov consoleHandleOutput, eax

	push STD_INPUT_HANDLE
	call GetStdHandle
	mov consoleHandleInput, eax	

	main_game:
	push 0
	call time
	push eax
	call srand                       ;srand(time(NULL))
	call rand
	xor edx, edx                     ;clear edx
	mov ebx, 10
	div ebx                          ;remainder is stored in edx, result in eax
	mov game_randomNumber, edx       ;rand() % 10

	retry_label:
	INVOKE WriteConsoleA, consoleHandleOutput, offset msg_enterNumber, 33, offset charsWritten, 0
	INVOKE ReadConsoleA, consoleHandleInput, ADDR buffer, 128, offset charsWritten, 0		
		
	cmp charsWritten, 3				 ;1 character + /r/n
	jne retry_label

	lea edx, buffer					;load the address of the buffer into edx	
	xor eax, eax					;clear eax
	mov al, [edx]					;dereference value at edx, move it into the lower 8 bit section of eax
									;this ensures we only move over one byte
	sub eax, 48
	cmp eax, 0
	jb retry_label
	cmp eax, 9
	ja retry_label

	cmp eax, game_randomNumber
	je win_label

	INVOKE WriteConsoleA, consoleHandleOutput, offset msg_lose, 46, offset charsWritten, 0
	jmp main_game

	win_label:
	INVOKE WriteConsoleA, consoleHandleOutput, offset msg_win, 50, offset charsWritten, 0
	call _getch
	INVOKE ExitProcess, 0 

main ENDP
END