Refactoring Pokemon type weekness

后端 未结 1 1408
南笙
南笙 2021-01-27 17:26

I made pokemon weekness finder by ruby. It takes a lot of words. Could you suggest bit nice and sophisticated to write this code?

The menu is as follows.



        
相关标签:
1条回答
  • 2021-01-27 18:04

    I think you can start from the structuring of game data:

    game_data = {
      1 => ["Normal", "Fighting" ],
      2 => ["Fire", "Ground, Rock, Water"],
      3 => ["Water", "Fire, Ground, Rock"],
      4 => ["Electric", "Ground"],
      5 => ["Grass", "Bug, Fire, Flying, Ice, Poison"],
      6 => ["Ice", "Fighting, Fire, Rock, Steel"],
      7 => ["Fighting", "Fairy, Flying, Psychic"],
      8 => ["Poison", "Ground, Psychic"],
      9 => ["Ground", "Grass, Ice, Water"],
      10 => ["Flying", "Electric, Ice, Rock"],
      11 => ["Psychic", "Bug, Dark, Ghost"],
      12 => ["Bug", "Fire, Flying, Rock"],
      13 => ["Rock", "Fighting, Grass, Ground, Steel, Water"],
      14 => ["Ghost", "Dark, Ghost"],
      15 => ["Dragon", "Dragon, Fairy, Ice" ],
      16 => ["Dark", "Bug, Fairy, Fighting"],
      17 => ["Steel", "Fighting, Fire, Ground"],
      18 => ["Fairy", "Poison, Steel" ]
    }
    

    Now you can work with it:

    puts "Which type of Pokemon do you want to know weaknesses?\nMenu"
    game_data.each { |point, data| puts "#{point} #{data.first}" }
    type = gets.to_i
    return "Error" unless game_data.has_key?(type)
    puts game_data[type].last
    

    Recommendation for future, if case statement becomes too big it's good point to think about to use Hash

    0 讨论(0)
提交回复
热议问题