Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created September 7, 2014 00:53
Show Gist options
  • Save mayfer/8abee37b2ae7af7183b8 to your computer and use it in GitHub Desktop.
Save mayfer/8abee37b2ae7af7183b8 to your computer and use it in GitHub Desktop.
veronika's math game
#future update: count time, after 1 min, swith the user - 1 life
# Assignment created as a new Github repository
# require pry
# binbinding.pry
@players = [{
life: 3,
score: 0,
level: 1,
name: "Player 1"
}, {
life: 3,
score: 0,
level: 1,
name: "Player 2"
}]
@current_player_index = 0
@current_player = @players[@current_player_index]
# Action of the game
def game_action
welcome
if wants_to_play?
while can_keep_playing?
wasCorrect = ask_question?
update_level(wasCorrect)
switch_player
# puts "Debug: #{@player1.inspect} #{@player2.inspect}"
end
congratulate
end
goodbuy
end
def can_keep_playing?
@current_player[:level] < 10 && @current_player[:life] > 0
end
def welcome
puts ""
puts "Welcome to the very quick math game!"
puts "Nice to meet both of you!" # can ask for names and keep track of them during the game
puts "Here is a game instruction: "
puts ""
puts "You will be given an equation, solve it as fast as you can"
puts "If you evaluate it wrong, you loose 1 life"
puts "You have only 3 lives, so be careful!"
puts "The dead player is deadly dead, and it ends the game."
puts "Player 1 starts"
puts ""
puts "Are you ready to play?"
end
def wants_to_play?
get_input == "yes"
end
def goodbuy
puts "See you later!"
end
def get_input
gets.chomp.downcase
end
# Generates the math question
# Future update: create different questions
def ask_question?
number1 = generate_random_number
number2 = generate_random_number
result = calculate_result(number1, number2)
puts "Hey #{@current_player[:name]}, what does #{number1} plus #{number2} equal?"
answer = get_input
puts "Your answer is #{answer}"
puts "The correct answer is #{result}"
answer == result
end
# Return result of equation
def calculate_result(number1, number2)
number1 + number2
end
# Generates the random number from 1-20
def generate_random_number
rand(20)
end
def update_level(wasCorrect)
if wasCorrect
@current_player[:score] +=1
else
@current_player[:score] -=1
@current_player[:life] -=1
end
@current_player[:level] +=1
end
def switch_player
@current_player_index = (@current_player_index + 1) % @players.length
@current_player == @players[@current_player_index]
end
def congratulate
puts "Congradulations! won!" #{get_winner}
puts "Score of the #{@player1[:name]} is #{@player1[:score]}"
puts "Score of the #{@player2[:name]} is #{@player2[:score]}"
end
def get_winner
if @player1[:score] > @player2[:score]
return @player1
elsif @player1[:score] < @player2[:score]
return @player2
else
check_lives
end
end
def check_lives
if @player1[:life] > @player2[:life]
return @player1
end
return @player2
end
game_action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment