How to resolve the algorithm Guess the number step by step in the X86 Assembly programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Guess the number step by step in the X86 Assembly programming language
Table of Contents
Problem Statement
Write a program where the program chooses a number between 1 and 10. A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits. A conditional loop may be used to repeat the guessing until the user is correct.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Guess the number step by step in the X86 Assembly programming language
Source code in the x86 programming language
segment .data
random dd 0 ; Where the random number will be stored
guess dd 0 ; Where the user input will be stored
instructions db 10, "Welcome user! The game is simple: Guess a random number (1-10)!", 10, 10
len1 equ $ - instructions ; 1 \n before and 2 \n after instructions for better appearance
wrong db "Not the number :(", 10
len2 equ $ - wrong
correct db "You guessed right, congratulations :D", 10
len3 equ $ - correct
segment .bss
segment .text
global main
main:
push rbp
mov rbp, rsp
; ********** CODE STARTS HERE **********
;;;;; Random number generator ;;;;;
mov eax, 13
mov ebx, random
int 80h
mov eax, [ebx]
mov ebx, 10
xor edx, edx
div ebx
inc edx
mov [random], edx
;;;;; Print the instructions ;;;;;
mov eax, 4
mov ebx, 1
mov ecx, instructions
mov edx, len1
int 80h
userInput:
;;;;; Ask user for input ;;;;;
mov eax, 3
xor ebx, ebx
mov ecx, instructions
mov edx, 1
int 80h
mov al, [ecx]
cmp al, 48
jl valCheck
cmp al, 57
jg valCheck
;;;;; If number ;;;;;
sub al, 48
xchg eax, [guess]
mov ebx, 10
mul ebx
add [guess], eax
jmp userInput
valCheck:
;;;;; Else check number ;;;;;
mov eax, 4
inc ebx
mov ecx, [guess]
cmp ecx, [random]
je correctResult
;;;;; If not equal, "not the number :(" ;;;;;
mov ecx, wrong
mov edx, len2
mov DWORD [guess], 0
int 80h
jmp userInput
correctResult:
;;;;; If equal, "congratulations :D" ;;;;;
mov ecx, correct
mov edx, len3
int 80h
;;;;; EXIT ;;;;;
mov rax, 0
mov rsp, rbp
pop rbp
ret
; "Guess my number" program by Randomboi (8/8/2021)
You may also check:How to resolve the algorithm First-class functions/Use numbers analogously step by step in the Oforth programming language
You may also check:How to resolve the algorithm Sum of a series step by step in the Red programming language
You may also check:How to resolve the algorithm Permutations step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Word wrap step by step in the OCaml programming language
You may also check:How to resolve the algorithm Hello world/Newbie step by step in the Ultimate++ programming language