Skip to content

Instantly share code, notes, and snippets.

@joshuastr
Created April 29, 2016 22:43
Show Gist options
  • Save joshuastr/01c73c5a2f741769fbac653c1d99b468 to your computer and use it in GitHub Desktop.
Save joshuastr/01c73c5a2f741769fbac653c1d99b468 to your computer and use it in GitHub Desktop.
Two Player Game
# Create a 2-player guessing game where players take turns to answer simple addition problems.
#The math questions are automatically generated.
#It should do this by picking two numbers between 1 and 20.
# Example prompt: "Player 1: What does 5 plus 3 equal?"
# Both players start with 3 lives. They lose a life if they mis-answer a question.
#If a player gets a question wrong, the game should output the new scores for both players, so players know where they stand.
# The game doesn’t end until one of the players loses all their lives.
#At this point, the game should announce who won and what the other player’s score is.
# As before, you can use gets.chomp to get input from users and puts for output.
require 'pry'
@player1_lives = 3
@player2_lives = 3
@current_player = 1
puts "Lets play a Two Player Math Game!"
def input_answer(operator, x, y)
if operator == 1
operator = ' + '
elsif operator == 2
operator = ' - '
else
operator = ' x '
end
puts "Player #{@current_player} What is #{x} #{operator} #{y}?"
gets.chomp.to_i
end
def switch_player
if @current_player == 1
@current_player = 2
puts "You have #{@player1_lives} lives left"
else
@current_player = 1
puts "You have #{@player2_lives} lives left"
end
end
def player_lives
return ((@player1_lives > 0) && (@player2_lives > 0)) ? true : false
end
def calc_answer(op, x, y)
if op == 1
return x + y
elsif op == 2
return x - y
else
return x * y
end
end
def winner
if @player1_lives == 0
'Player 2 Wins!'
else
'Player 1 Wins!'
end
end
def check_answer(answer, correct_answer)
if answer == correct_answer
puts "That's Right!"
else
if @current_player == 1
@player1_lives -= 1
puts "Incorrect #{@player1_lives}"
else
@player2_lives -= 1
puts "Incorrect #{@player2_lives}"
end
end
end
loop do
x = rand(20) + 1
y = rand(20) + 1
op = rand(1..3)
right_answer = calc_answer(op, x, y)
answer = input_answer(op, x, y)
check_answer(answer, right_answer)
switch_player
break if player_lives == false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment