Mix.install([
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"},
{:tested_cell, github: "brooklinjazz/tested_cell"},
{:utils, path: "#{__DIR__}/../utils"}
])
Ensure you type the ea
keyboard shortcut to evaluate all Elixir cells before starting. Alternatively you can evaluate the Elixir cells as you read.
You're going to create the perfect AI for rock paper scissors that will always win.
flowchart LR
scissors --beats--> paper --beats--> rock --beats--> scissors
Generate a random player choice of :rock
,:paper
, or :scissors
or manually enter :rock
, :paper
, and :scissors
to determine your program works correctly.
player_choice = Enum.random([:rock, :paper, :scissors])
Then, return the winning choice of either :rock
, :paper
, or :scissors
that beats the player's choice.
Example solution
player_choice = :scissors
case player_choice do
:rock -> :paper
:paper -> :scissors
:scissors -> :rock
end
Enter your solution below.
Now that you know how to create a rock paper scissors AI, you're going to create a two player game of rock paper scissors.
Bind a player1_choice
and player2_choice
variable to :rock
, :paper
, or :scissors
.
- If
player1_choice
beatsplayer2_choice
, return"Player 1 wins!"
. - If
player2_choice
beatsplayer1_choice
, return"Player 2 wins!"
. - If both players have the same choice, then return
"Draw"
.
Example solution
player1 = :rock
player2 = :scissors
case {player1, player2} do
{:rock, :scissors} -> "Player 1 Wins!"
{:paper, :rock} -> "Player 1 Wins!"
{:scissors, :paper} -> "Player 1 Wins!"
{:rock, :paper} -> "Player 2 Wins!"
{:paper, :scissors} -> "Player 2 Wins!"
{:scissors, :rock} -> "Player 2 Wins!"
{_same, _same} -> "Draw"
end
You can also reduce code repetition using functions and the in
keyword to check if the value exists in a list.
player1 = :rock
player2 = :scissors
beats? = fn choice1, choice2 ->
{choice1, choice2} in [{:rock, :scissors}, {:paper, :rock}, {:scissors, :paper}]
end
cond do
beats?(player1, player2) -> "Player1"
beats?(player2, player1) -> "Player2"
player1 == player2 -> "Draw"
end
Enter your solution below.
Run the following in your command line from the beta_curriculum folder to track and save your progress in a Git commit.
$ git add .
$ git commit -m "finish rock paper scissors exercise"
Previous | Next |
---|---|
Naming Numbers | Modules |