I am trying to build a "train game" based loosely on the old video game "Drug Wars." I am currently working my way through LRTHW, and I believe that I should be using OOP, but I'm not to that lesson yet.
The premise is that you have a set number of cars on your train and you can see what products are for sale in other cities (no limit on the amount you can buy or sale presuming you can fit them in your train). This code isn't complete, but I'm wondering if I'm even approaching this half way sanely in regard to creating and accessing the product prices in a reasonable manner.
#Initializing variables. Current_location should be changed to random
#in the future.
current_location = 'omaha'
train = []
new_york = []
chicago = []
omaha = []
dallas = []
seattle = []
def prompt()
print "> "
end
#Here is the selection menu. It is possible to exploit this and
#buy, sell and move all within the same turn.
#There needs to be a "safe selection" so that once you have moved you
#can't move again, but you can get info, buy and sell
#as many times as you would like.
def selection()
puts "Do you want to travel, buy, sell or get info?"
prompt; selection = gets.chomp
if selection.include? "travel"
puts "Where would you like to travel?"
prompt; city = gets.chomp
return 'city', city
elsif selection.include? "buy"
puts "Current Prices Are:"
puts "What would you like to Buy?"
elsif selection.include? "sell"
puts "Current Prices Are:"
puts "What would you like to sell?"
elsif selection.include? "info"
puts "What city or train would you like info on?"
else
puts "Would you like to exit selection or start selection again?"
end
end
#This generates a new cost for each good at the start of each turn.
def generate_costs(new_york, chicago, omaha, dallas, seattle)
new_york[0] = rand(10)
new_york[1] = rand(10) + 25
new_york[2] = rand(5) + 10
omaha[0] = rand(10)
omaha[1] = rand(10) + 25
omaha[2] = rand(5) + 10
chicago[0] = rand(25) + 5
chicago[1] = rand(5) + 10
chicago[2] = rand(4)
dallas[0] = rand(6) + 11
dallas[1] = rand(3) + 10
dallas[2] = rand(8)
seattle[0] = rand(6)
seattle[1] = rand(10) + 24
seattle[2] = rand(14) + 13
return new_york, chicago, omaha, dallas, seattle
end
# This is my main() loop. It drives the game forward.
for i in (0..5)
new_york, chicago, omaha, dallas, seattle = generate_costs(new_york, chicago, omaha, dallas, seattle)
turns = 5 - i
puts "You are currently in #{current_location}. You have #{turns} remaining."
puts "{ ___________________________ }"
#Code Here evaluates and accesses pricing based on current_location.
#Is this the correct way to do this?
fish = eval("#{current_location}[0]")
coal = eval("#{current_location}[1]")
cattle = eval("#{current_location}[2]")
puts "Fish is worth #{fish}"
puts "Coal is worth #{coal}"
puts "Cattle is worth #{cattle}"
puts "{ ___________________________ }"
change, value = selection()
if change == 'city'
current_location = value
elsif change == 'buy'
puts 'So you want to buy?'
else
puts "I don't understand what you want to do"
end
end
eval is a nasty way of accessing data ( When is `eval` in Ruby justified? ). You should consider moving things into an object.
I have improved the code slightly, storing the cities in a hash, which gets rid of the evals. I have stubbed out the generate_costs logic but you can assign it by doing:
cities[:new_york][0] = rand(10)
Ideally, the code should be re-written in an object-oriented syntax. If I get some time then I'll knock up an example for you.
Here is the code:
#Initializing variables. Current_location should be changed to random
#in the future.
current_location = :omaha
train = []
cities = {
:new_york => [],
:chicago => [],
:omaha => [],
:dallas => [],
:seattle => []
}
def prompt()
print "> "
end
#Here is the selection menu. It is possible to exploit this and
#buy, sell and move all within the same turn.
#There needs to be a "safe selection" so that once you have moved you
#can't move again, but you can get info, buy and sell
#as many times as you would like.
def selection()
puts "Do you want to travel, buy, sell or get info?"
prompt; selection = gets.chomp
if selection.include? "travel"
puts "Where would you like to travel?"
prompt; city = gets.chomp
return 'city', city
elsif selection.include? "buy"
puts "Current Prices Are:"
puts "What would you like to Buy?"
elsif selection.include? "sell"
puts "Current Prices Are:"
puts "What would you like to sell?"
elsif selection.include? "info"
puts "What city or train would you like info on?"
else
puts "Would you like to exit selection or start selection again?"
end
end
#This generates a new cost for each good at the start of each turn.
def generate_costs(cities)
cities.each do |key,city|
0.upto(2) do |i|
city[i] = rand(10)
end
end
end
# This is my main() loop. It drives the game forward.
for i in (0..5)
generate_costs(cities)
turns = 5 - i
puts "You are currently in #{current_location}. You have #{turns} remaining."
p cities
puts "{ ___________________________ }"
fish = cities[current_location][0]
coal = cities[current_location][1]
cattle = cities[current_location][2]
puts "Fish is worth #{fish}"
puts "Coal is worth #{coal}"
puts "Cattle is worth #{cattle}"
puts "{ ___________________________ }"
change, value = selection()
if change == 'city'
current_location = value
elsif change == 'buy'
puts 'So you want to buy?'
else
puts "I don't understand what you want to do"
end
end
Related
I'm creating a tic tac toe game in the command line using Ruby. I have a method display_board that displays my array as a game board in the command line and when I play the game players can choose between 1-9 and populate the square with their "symbol". I created a method check_square to verify if one of the squares in the grid has already been taken but it's not working properly for me. I start up the game and everything works, up until it asks me to choose my first number on the grid. It immediately responds and tells me the number is already taken even though it's the first move of the game. It asks me to choose another number and on the second try it populates the grid. It does this on every player move. The logic seems to make sense to me and I've been trying to figure it out for an hour but I'm clearly overlooking something. Any pushes in the right direction would be helpful!
class Players
attr_accessor :name, :symbol
def initialize(name, symbol)
#name = name
#symbol = symbol
end
end
class Game
##board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
##count = 0
def initialize
puts "Tic Tac Toe!"
end
def display_board
puts " #{##board[0]} | #{##board[1]} | #{##board[2]}"
puts seperator = "-----+-----+-----"
puts " #{##board[3]} | #{##board[4]} | #{##board[5]}"
puts seperator
puts " #{##board[6]} | #{##board[7]} | #{##board[8]}"
puts "\n"
end
def game_start
puts "Time for some Tic Tac Toe! Enter your name player 1: \n"
player1 = gets.chomp
puts "Would you like to be X or O #{player1}?"
symbol1 = gets.chomp.upcase
player_one = Players.new(player1, symbol1)
puts "And a name for player 2: \n"
player2 = gets.chomp
symbol2 = player_one.symbol == "X" ? "O" : "X"
player_two = Players.new(player2, symbol2)
puts "\n"
puts "Okay #{player_one.name}, you're up. Make a move."
display_board
make_moves(player_one, player_two)
end
def make_moves(player_one, player_two)
until ##count == 9
puts "Pick a number from the grid above #{player_one.name}"
move = gets.chomp.to_i - 1
check_square(move, player_one, player_two)
##board[move] = player_one.symbol
##count += 1
display_board
puts "Pick a number from the grid above #{player_two.name}"
move = gets.chomp.to_i - 1
check_square(move, player_one, player_two)
##board[move] = player_two.symbol
##count += 1
display_board
end
end
def check_square(move, player_one, player_two)
if ##board[move] == "#{player_one.symbol}" || "#{player_two.symbol}"
puts "That number is taken, pick another!"
move = gets.chomp.to_i - 1
else
return
end
end
end
game = Game.new
game.game_start
The problem you're running into is the conditional logic in your check_square method.
##board[move] == "#{player_one.symbol}" || "#{player_two.symbol}"
This logic is suppose to check if either of the players' symbols is stored on the board at the selected position. However, what it is really doing is checking if player one's symbol is stored on the board at that position and if it's not then the string literal for player two's symbol is being evaluated as truthy. This results in check_square always returning true
Try this instead:
##board[move] == "#{player_one.symbol}" || ##board[move] == "#{player_two.symbol}"
For more idiomatic ruby you can remove the interpolation which isn't necessary since symbol is already a string.
##board[move] == player_one.symbol || ##board[move] == player_two.symbol
I created a calculator in ruby. I am wondering how to put this in a loop so I don't have to run it constantly. I am new to programming so please understand I am I just trying to learn. I would appreciate any help provided.
puts "Hello, My name is Calvin The Calculator and I am a calculator that can do basic functions such as Adding, Subtracting, Multiplying and Dividing"
puts "Press a and enter to enable my services"
enable = gets.chomp
if enable == "a"
puts "Choose which operation you want to do. + for adding, - for subtraction, * for multiplication and / for division"
else
"Puts Im Waiting..."
end
which_operation = gets.chomp
if which_operation == "+"
puts "What is the first number you want to add"
adding_first_number = gets.chomp.to_i
puts "What is the second number you want to add to #{adding_first_number}"
adding_second_number = gets.chomp.to_i
puts "#{adding_first_number} + #{adding_second_number} is #{adding_first_number + adding_second_number}"
else
end
if which_operation == "-"
puts "What is the first number you want to subtract"
subtracting_first_number = gets.chomp.to_i
puts "What is the number you want to subtract from #{subtracting_first_number}"
subtracting_second_number = gets.chomp.to_i
puts "#{subtracting_first_number} - #{subtracting_second_number} is #{subtracting_first_number - subtracting_second_number}"
else
end
if which_operation == "*"
puts "What is the first number you want to multiple"
multiplying_first_number = gets.chomp.to_i
puts "What is the number you want to multiple #{multiplying_first_number} by"
multiplying_second_number = gets.chomp.to_i
puts "#{multiplying_first_number} * by #{multiplying_second_number} is #{multiplying_first_number * multiplying_second_number}"
else
end
if which_operation == "/"
puts "What is the first number to your divison question?"
dividing_first_number = gets.chomp.to_i
puts "What is the divisor?"
dividing_second_number = gets.chomp.to_i
puts "#{dividing_first_number} divided by #{dividing_second_number} is #{dividing_first_number / dividing_second_number}"
else
end
For example:
until (which_operation = gets.chomp).empty?
if which_operation == "+"
...
end
if which_operation == "-"
...
end
if which_operation == "*"
...
end
if which_operation == "/"
...
end
end
This loop will work until you press Enter without entering any text before it.
P.S.: Better use case operator instead of multiple if.
P.P.S.: All your code, after loop addition and without case operator, will be:
puts "Hello, My name is Calvin The Calculator and I am a calculator that can do basic functions such as Adding, Subtracting, Multiplying and Dividing"
puts "Press a and enter to enable my services"
until gets.chomp == "a"
puts "I'm Waiting..."
end
puts "Choose which operation you want to do. + for adding, - for subtraction, * for multiplication and / for division"
until (which_operation = gets.chomp).empty?
if which_operation == "+"
puts "What is the first number you want to add"
adding_first_number = gets.chomp.to_i
puts "What is the second number you want to add to #{adding_first_number}"
adding_second_number = gets.chomp.to_i
puts "#{adding_first_number} + #{adding_second_number} is #{adding_first_number + adding_second_number}"
elsif which_operation == "-"
puts "What is the first number you want to subtract"
subtracting_first_number = gets.chomp.to_i
puts "What is the number you want to subtract from #{subtracting_first_number}"
subtracting_second_number = gets.chomp.to_i
puts "#{subtracting_first_number} - #{subtracting_second_number} is #{subtracting_first_number - subtracting_second_number}"
elsif which_operation == "*"
puts "What is the first number you want to multiple"
multiplying_first_number = gets.chomp.to_i
puts "What is the number you want to multiple #{multiplying_first_number} by"
multiplying_second_number = gets.chomp.to_i
puts "#{multiplying_first_number} * by #{multiplying_second_number} is #{multiplying_first_number * multiplying_second_number}"
elsif which_operation == "/"
puts "What is the first number to your divison question?"
dividing_first_number = gets.chomp.to_i
puts "What is the divisor?"
dividing_second_number = gets.chomp.to_i
puts "#{dividing_first_number} divided by #{dividing_second_number} is #{dividing_first_number / dividing_second_number}"
end
puts "\nLet's try again: "
end
Ok i seriously suck at passing method to methods whenever i want to return something from the method. Can you guys explain on how do i go about passing it.
Here's my hash
$choosen_gun = {}
$Weapon = {
:Bazoka => ["Bazoka",5],
:Machine_gun => ["Machine_gun",1000],
:Hand_gun => ["Hand_gun",24,2],
:Double_Hand_gun => ["Double_Hand_gun",24,4],
:Sniper => ["Sniper",12,1],
:Shot_gun => ["Shot_gun",8,2]
}
Here's my code for method Weapon
def Weapon
puts "Now it's time to select your weapon."
puts "Please choose a weapon that is good throughout the game."
puts "Whenever you are shortage of bullets, please reload it."
puts "Please avoid last minute of reloading of weapon."
puts "Now choose your weapon based on your own preferences."
print "\n"
puts "Type 1"
puts "Gun Name: Bazoka"
puts "Description: A powerful gun that is strong with only 5 bullets."
puts "Rating: ★ ★ ★ ★"
num = gets.chomp.to_i
case num
when 1
puts "Selection of Bazoka is chosen"
puts "Loaded 5 bullets only"
$choosen_gun[num] = $Weapon[:Bazoka]
end
return num
end
Upon calling the method. The user will choose his weapon and it will add it to the $choosen_gun hash with it's num, and it's return it's num what the user types
Here's my code for method ZombieRoom
def ZombieRoom(w)
zombie = {
:Construcied => [5],
:Invader => [5],
:Damned => [5],
:Steampunk => [5],
:Stoner => [5],
:Wasted => [5],
:Romero => [5]
}
puts "Welcome to the worst night mare of Zombie Room"
puts "You will be fighting with a random zombie"
while true
puts ".........."
puts "Selecting a random zombie"
puts "Selecting your prefered gun...."
case w
when 1
$choosen_gun[1]
puts "Your selected gun is #{$choosen_gun[1][0]}"
#values = zombie.values
#puts values[rand(values.size)]
#random_zombie = zombie.keys.sample(1)
#puts random_zombie[
random_zombie = zombie.to_a.sample(1).to_h
random_zombie.each do |key,value|
puts "Your random zombie is #{key}"
puts "With a health value of #{value[0]}"
puts "Time to take down that zombie now."
while true
puts "Type Shoot to knock it down or quit."
choice = gets.chomp
if $choosen_gun[1][1] >= 1
health = value[0] -= 1
$choosen_gun[1][1] -= 1
puts "#{key} health now is #{health}"
else
puts "Please reload your gun"
puts "Reloading......"
$choosen_gun[1][1] += 5
end
if health == 0
puts "You have defeated #{key}"
puts "Congrats!!!"
puts "We are happy for you"
puts "Lets begins to collect your prize"
CollectPrize()
else
puts "You did not defeat the #{key} yet"
end
end
end
end
end
end
Here's my code for method CollectPrize
def CollectPrize
puts "Congratulations on defeating"
puts "We would now like to give you some case prizes"
print "\n"
puts "Please choose only 1 prize for yourself"
print "\n"
puts "Type 1"
puts "$50,000"
print "\n"
puts "Type 2"
puts "$25,000"
print "\n"
puts "Type 3"
puts "$55,000"
hoho = gets.chomp.to_f
if hoho == 1
puts "hehe"
end
end
Here how i call my method
ZombieRoom(Weapon())
CollectPrize()
Now the problem is that whenever the CollectPrize method is called and i type my input to collect the prize example 1 then it print "$50,000". instead of the ending the problem, it went back to the ZombieRoom and continues to loop at the "Type Shoot to knock it down or quit." Can someone atleast tell me a proper way to solve this issue or also what other way to pass a method?
Your code is in a large while true loop. Since true is always true, it will never end, so after it calls CollectPrize() it just goes back to the while statement.
You could get out of it by inserting a break line after the CollectPrize() but there's another while true loop around this one.
I think you need to pay closer attention to how you want to exit the while loops.
puts "Time to take down that zombie now."
while true # <---------------- this is ALWAYS going to loop, without end
puts "Type Shoot to knock it down or quit."
choice = gets.chomp
if $choosen_gun[1][1] >= 1
health = value[0] -= 1
$choosen_gun[1][1] -= 1
puts "#{key} health now is #{health}"
else
puts "Please reload your gun"
puts "Reloading......"
$choosen_gun[1][1] += 5
end
if health == 0
puts "You have defeated #{key}"
puts "Congrats!!!"
puts "We are happy for you"
puts "Lets begins to collect your prize"
CollectPrize()
else
puts "You did not defeat the #{key} yet"
end
end
In ruby constants start with Capital letter.
Methods are always defined in lower case.
Try this in irb
irb(main):001:0> def Weapon
irb(main):002:1> end
=> :Weapon
irb(main):003:0> Weapon
NameError: uninitialized constant Weapon
To solve your problem name methods using ruby's naming conventions:
zombie_room, collect_prize etc.
Then this code will work:
zombie_room(weapon())
What you are doing there is not really passing method weapon to method zombie room.
What is really going on is that method weapon is executed, then it returns a value and result of that value is passed to method zombie_room.
I think that is what you wanted.
If you need to pass a method, check out documentation for proc and lambda or just use blocks.
I'm doing a game creation exercise from Learn Ruby the Hard Way. It's themed after Destiny since that's what I've got on the brain at the moment.
I wanted to have the player pick a character class, and then have that choice hand off some numbers as stats to be checked later in play. Below is the version that actually worked, but it involves creating a several global variables, which I keep reading is not a "best practice" in Ruby.
My question is, is there a way to do what I've got the code below doing without creating all of these global variables, or am I doing what needs to be done?
$might = 1
$agility = 1
$intellect = 1
def start
puts "Make all decisions by pressing the corresponding number."
puts "Choose your class:"
puts "1. Titan"
puts "2. Hunter"
puts "3. Warlock"
print "> "
choice = $stdin.gets.chomp
if choice == "1"
$might = 3
puts "You've chosen Titan!"
elsif choice == "2"
$agility = 3
puts "You've chosen Hunter!"
elsif choice == "3"
$intellect = 3
puts "You've chosen Warlock!"
else
puts "Try again."
start
end
end
puts start
puts "Might: #{$might}"
puts "Agility: #{$agility}"
puts "Intellect: #{$intellect}"
You can create a class and use instance variables:
class Game
def initialize
#might = 1
#agility = 1
#intellect = 1
end
attr_reader :might
attr_reader :agility
attr_reader :intellect
def start
puts "Make all decisions by pressing the corresponding number."
puts "Choose your class:"
puts "1. Titan"
puts "2. Hunter"
puts "3. Warlock"
print "> "
choice = $stdin.gets.chomp
case choice
when "1"
#might = 3
puts "You've chosen Titan!"
when "2"
#agility = 3
puts "You've chosen Hunter!"
when "3"
#intellect = 3
puts "You've chosen Warlock!"
else
puts "Try again."
start
end
end
end
game = Game.new
game.start
puts "Might: #{game.might}"
puts "Agility: #{game.agility}"
puts "Intellect: #{game.intellect}"
Remark:
I replaced your if-sequence with a case-statement
attr_reader defined the attribute accessor for the instance variables.
Maybe something like this. I prepare it for updates.
class Character
attr_accessor :might, :agility, :intelect, :type
def initialize(type, might = 1, agility = 1, intelect = 1)
#type = type
#might, #agility, #intelect = might, agility, intelect
end
def print_attributes
puts "Type: #{#type}"
puts "Might: #{#might}"
puts "Agility: #{#agility}"
puts "Intelect: #{#intelect}"
end
end
class Player
attr_reader :character
def initialize(character)
#character = character
end
end
class Game
CHARACTER_CLASSES = [
{:type => "Titan", :might => 3, :agility => 1, :intelect => 1},
{:type => "Hunter", :might => 1, :agility => 3, :intelect => 1},
{:type => "Warlock", :might => 1, :agility => 1, :intelect => 3}
]
attr_reader :player
def initialize
#player = nil
end
def start
puts "Make all decisions by pressing the corresponding number."
repeat = true
while repeat
puts "Choose your class:"
CHARACTER_CLASSES.each_with_index do |char_config, i|
puts "#{i+1}. #{char_config[:type]}"
end
choice = gets.chomp
choice_i = choice.to_i
unless choice_i == 0
if char_data = CHARACTER_CLASSES[choice_i - 1]
#player = Player.new( Character.new(char_data[:type], char_data[:might], char_data[:agility], char_data[:intelect]) )
repeat = false
end
end
end
end
end
game = Game.new
game.start
game.player.character.print_attributes
One option could be returning whatever you want from a method:
def start
puts "Make all decisions by pressing the corresponding number."
puts "Choose your class:"
puts "1. Titan"
puts "2. Hunter"
puts "3. Warlock"
print "> "
choice = $stdin.gets.chomp
case choice
when '1'
puts "You've chosen Titan!"
{agility: 1, might: 3, intellect: 1}
when '2'
puts "You've chosen Hunter!"
{agility: 3, might: 1, intellect: 1}
when '3'
puts "You've chosen Warlock!"
{agility: 1, might: 1, intellect: 3}
else
puts "Try again."
start
end
end
hero = start
puts "Might: #{hero[:might]}"
puts "Agility: #{hero[:agility]}"
puts "Intellect: #{hero[:intellect]}"
Hi Im getting an core error which is really standard I suppose in Ruby but dont know what to make of it. I have a program that I have written. Its purpose is to register guests at a camping. You have a menu with 5 different options. 1. Checkin. When i do this I get a undefined method generateParkingLot' for #<Camping:0x10030a768> (NoMethodError)
When I choose Checkout I get a undefined local variable or methoddeparture' for Menu:Class (NameError).
So please i someone has a clue to my problem it would be great. I will here paste all my code. The code is separated in different files and I have used require for the different files. Here though I will paste all the code in one trace. Thankful for all help.
-Sebastien
require 'guest'
require 'parking_lot'
class Camping
attr_accessor :current_guests, :parking_lots, :all_guests, :staticGuests
def initialize(current_guests, parking_lots, all_guests, staticGuests)
#current_guests = Array.new()
# initiera husvagnsplatserna
#parking_lots = Array.new(32)
32.times do |nr|
#parking_lots[nr] = Parking_Lot.new(nr)
#staticGuests = Array[
Guest.new("Logan Howlett", "Tokyo", "07484822",1, #parking_lots[0]),
Guest.new("Scott Summers", "Chicago", "8908332", 2, #parking_lots[1]),
Guest.new("Hank Moody", "Boston", "908490590", 3, #parking_lots[2]),
Guest.new("Jean Grey", "Detroit", "48058221", 4, #parking_lots[3]),
Guest.new("Charles Xavier","Washington DC", "019204822",5, #parking_lots[4])
]
end
#all_guests = []
#staticGuests.each do |guest|
#current_guests[guest.plot.nr] = guest
#all_guests.push(guest)
end
end
def to_s
# creates an empty string
list = " "
# loop from 1 to 32
(1..32).each do |n|
if (!#current_guests[n-1].nil?)
list += #current_guests[n-1].to_s
else
# else adds the text "Vacant"
list += n.to_s + ": Vacant!\n"
end
return list
end
def generateParkingLot
randomNr = 1+rand(32)
# exists a guest at the (0-based) position?
if (!#current_guests[randomNr-1].nil?)
# if so generate a new figure
generateEmpty(array)
else
# returns the generated number
return randomNr
end
end
end
end
class Guest
attr_accessor :firstname, :lastname, :address, :phone, :departure
attr_reader :arrived, :plot
def initialize (firstName, lastName, address, phone, plot)
#firstName = firstName
#lastName = lastName
#address = address
#phone = phone
#arrived = arrived
#plot = plot
end
def to_s
"Personal information:
(#{#firstName}, #{#lastName}, #{#address}, #{#phone}, #{#arrived}, #{#departure}, #{#plot})"
end
end
require 'ruby_camping'
require 'camping_guests'
class Main
if __FILE__ == $0
$camping = Camping.new(#current_guests, #all_guests, #parking_lots,#staticGuests)
puts "\n"
puts "Welcome to Ruby Camping!"
while (true)
Menu.menu
end
end
end
require 'date'
require 'camping_guests'
require 'guest'
class Menu
def initialize(guests = [])
#camping = Camping.new(guests)
end
def self.menu
puts "---------------------------"
puts " Menu"
puts " 1. Checkin"
puts " 2. Checkout"
puts " 3. List current guests"
puts " 4. List all guests"
puts " 5. Exit\n"
puts ""
puts " What do you want to do?"
puts "---------------------------"
print ": "
action = get_input
do_action(action)
end
# fetches menu choice and returns chosen alternativ
def self.get_input
input = gets.chomp.to_i
while (input > 5 || input < 1) do
puts "Ooups, please try again."
input = gets.chomp.to_i
end
return input
end
def self.do_action(action)
case action
when 1:
check_in
when 2:
check_out
when 3:
puts $camping.current_guests
when 4:
puts $camping.all_guests
when 5:
puts "You are now leaving the camping, welcome back!"
exit
end
end
def self.check_in
puts "Welcome to the checkin"
puts "Please state your first name: "
firstName = gets.chomp
puts "Please state your last name:"
lastName = gets.chomp
puts "Write your address: "
address = gets.chomp
puts "and your phone number: "
phone = gets.chomp
puts "finally, your arrival date!"
arrived = gets.chomp
newPLot = $camping.generateParkingLot
newGuest = Guest.new(firstName, lastName, address, phone,arrived,$camping.parking_lots[newPLot-1])
$camping.current_guests[newPLot-1] = newGuest
#all_guests.push(newGuest)
puts "The registration was a success!! You have received the " + newPLot.to_s + "."
end
def self.check_out
puts "Welcome to checkout!"
puts $camping.all_guests
puts "State plot of the person to checkout!"
plot = gets.chomp.to_i
puts "Ange utcheckningsdatum: "
departureDate = gets.chomp.to_i
guest = $camping.current_guests[plot-1]
#departure = departure
guest.departure = departureDate
guestStayedDays = departureDate - guest.arrived
guest.plot.increase(guestStayedDays)
puts guest
$camping.current_guests[plot-1] = nil
end
end
class Parking_Lot
attr_accessor :nr
attr_reader :electricity_meter
def initialize (nr)
#nr = nr
#electricity_meter = 4000-rand(2000)
end
def increase_meter(days)
generatedUse = (10+rand(70))*days
puts "Increases the meter with " + generatedUse.to_s + " kWh."
#electricity_meter += generatedUse
end
def to_s
"Plot #{#nr+1} Electricity meter: #{#electricity_meter} kWh"
end
end
It looks (although I haven't tried this out) like some of your your 'end's are wrong.
The one which is causing your first error (generateParkingLot undefined) is that generateParkingLot is actually defined inside to_s, so you need an extra 'end' at the end of your to_s method.
As for the second error (departure not recognised), the folowing line in self.check_out is at fault:
#departure = departure
because there is no 'departure' variable. (Perhaps you meant DepartureDate?). I suspect there may be a few other issues with this code, but I'm afraid I don't really have time to check now.
One I noticed was that when you have
32.times do |nr|
#parking_lots[nr] = Parking_Lot.new(nr)
I think you might want to end that, either with an 'end' or curly brackets, e.g.
32.times do |nr|
#parking_lots[nr] = Parking_Lot.new(nr)
end
Although that would make your other blocks not match.. In general, just try and make sure your blocks are all defined properly (e.g. everything has a matching end).