I've recently started programming (learning Ruby) and wrote a small game. Now I've started reading about MVC and am trying to refracture my code to follow that architecture. The only classes with big changes so far are the intended controller and view (which is completely temporary.
# This file will handle the Demigod class, which is the player controlled class # # ============================================================================= require_relative 'UiHandler' require_relative 'GameData' require_relative 'World' class Demigod attr_reader :resources @world # Starts a new game - each demigod has one world to rule # accepts different starting resources as a parameter def initialize (world, resources = GameData::STARTING_RESOURCES) @world = world @resources = resources end # Handles a turn, main function of the game def turn # calculates new amount of resources using the production function # world.production accepts a resources hash and returns a newly # calculated resource hash based on production @resources = @world.production(@resources) p @resources #do_event # ========= TODO ========= # # part 2 of every turn UiHandler.print_world(@world) UiHandler.print_turn_message # Asks the user for a tile to do his action on decision = UiHandler.get_decision() until (@world.valid?(decision) || decision == '') UiHandler.print_error(UiHandler::NO_TILE) UiHandler.print_turn_message decision = UiHandler.get_decision() end unless decision == '' tile = @world.get_tile decision # returns the tile at decision # checks for legality of move on tiles using tile.accepts? and tile.check_cost until tile.accepts?(decision) break if decision == '' UiHandler.print_tile_options(tile) decision = UiHandler.get_decision() if (!tile.accepts?(decision)) UiHandler.print_error(UiHandler::INVALID) elsif (!tile.check_cost(decision, @resources)) decision = nil UiHandler.print_error(UiHandler::RESOURCES) end end if decision != '' price = GameData.get_price(decision) @resources = reduce(price) @world.advance(tile, decision) end end # Clears the screen UiHandler.clear_messages() end private # calls an new event # === TODO === # def do_event end # Reduces resources TOBEMOVED to world def reduce(amount) amount.each do |name, value| @resources[name] -= value end @resources end end
Stuff I realized while writing this question:
resourcesreally shouldn't be here, though I'm not sure if they deserve their own class or should just be in the world (the main model).
- I think that the loop dealing with incorrect input should be part of the view, since it interacts directly with the user for input, but I'm not sure how to do it.
I would appreciate a review of how the entire code fits MVC, but I don't expect it.