What is rock-paper-scissors in the first place? ?? Goo, choki, and par are selected from each other to decide the outcome. This time we will fight with the player programmatically. Goo Rock Choki Paper Par Scissors Play in. (In the program, rand, which returns random numbers, plays an active role, but it will be later)
Substitution by input
p 'rock-paper-scissors'
player=gets
↑ Ask them to choose between rock, paper, and scissors It is also important to deal with misspellings by players
Determined by random numbers.
program_hand=rand(3)
↑ program_hand will return 0, 1, 2 as random numbers.
For humans, the character notation Rock-Paper-Scissors is easy to understand, but as with random numbers 0, 1, and 2, the numbers are easier to understand from the program (machine) than the characters.
Therefore, in the two players (player, program) playing rock-paper-scissors, the hands are represented by numbers and letters.
0 Goo Rock 1 Choki Paper 2 par Scissors
if program_hand==0
program="rock"
elsif program_hand==1
program="paper"
elsif program_hand==2
program="scissors"
end
if player=="rock"
player_hand=0
elsif player=="paper"
player_hand=1
elsif player=="scissors"
player_hand=2
end
Here comes the conditional branch Use if statement
if player_hand==program_hand
p 'draw'
elsif ((player_hand==0 and program_hand==2) or (player_hand==1 and program_hand==0) or (player_hand==2 or program_hand==0))and a==1
p 'you win'
elsif
p 'you lose'
end
When writing a conditional expression, logic may appear continuously. (And and or) There seems to be talk of the superiority of logic, but it is difficult. It's quick, easy, and easy to put the person you want to calculate first in parentheses.
You are supposed to choose rock, paper, scissors, How do you handle other inputs? ??
one more please To display
Make a variable called a appear. Initial value 0 Substitute a = 1 only when any of rock, paper, and scissors is entered.
Judgment using a
↓ Completion
p 'rock-paper-scissors'
player=gets
a=0
if player=="rock"
player_hand=0
a=1
elsif player=="paper"
player_hand=1
a=1
elsif player=="scissors"
player_hand=2
a=1
end
program_hand=rand(3)
if program_hand==0
program="rock"
elsif program_hand==1
program="paper"
elsif program_hand==2
program="scissors"
end
if a==0
p 'one more please'
elsif player_hand==program_hand
p 'draw'
elsif ((player_hand==0 and program_hand==2) or (player_hand==1 and program_hand==0) or (player_hand==2 or program_hand==0))and a==1
p 'you win'
elsif
p 'you lose'
end
p "player",player,"program",program
Recommended Posts