Как хранить и получать значения с помощью Ruby? - PullRequest
1 голос
/ 18 августа 2011

Я пытаюсь создать "игру в поезде", основанную на старой видеоигре "Войны с наркотиками". В настоящее время я прорабатываю LRTHW и считаю, что мне следует использовать ООП, но я еще не до этого урока.

Предпосылка состоит в том, что в вашем поезде установлено определенное количество вагонов, и вы можете видеть, какие товары продаются в других городах (нет ограничений по сумме, которую вы можете купить или продать, при условии, что вы можете разместить их в своем поезде). Этот код не завершен, но мне интересно, подхожу ли я хотя бы на полпути к этому вопросу в отношении создания и доступа к ценам на продукты разумным образом.

#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

1 Ответ

4 голосов
/ 18 августа 2011

eval - неприятный способ доступа к данным ( Когда оправдано `eval` в Ruby? ). Вы должны рассмотреть возможность перемещения вещей в объект.

Я немного улучшил код, храня города в хэше, что избавляет от уловок. Я заглушил логику generate_costs, но вы можете назначить ее, выполнив:

cities[:new_york][0] = rand(10)

В идеале код должен быть переписан в объектно-ориентированном синтаксисе. Если у меня будет время, я приведу для вас пример.

Вот код:

#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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...