Saturday, April 2, 2016

Swiftly Learning: Mini Combat Part 2: My, what a mess I've made

I finally got everything in Mini Combat working the way I wanted. The text updates, the buttons are disabled for a moment after you attack so you can't just spam the other guy to death, and there's an X WINS! label that updates when someone wins. Kinda cool for what it is, and how noob I am :)

Invisible reader, you may recall in Part 1 where I mentioned that I was breaking rules about repeating myself and filling up my ViewController with all of the things. Well, tonight I started correcting those mistakes.

The biggest challenge for me has been thinking differently. I started with this code that lived in the ViewController and totally worked GREAT:
    @IBAction func onPlayerButtonPressed(sender: UIButton) {
       let d20 = Int(arc4random_uniform(19) + 1)
       let d6 = Int(arc4random_uniform(5) + 1)
            
       player.tryAttack(monster, attackStrength: d6, hitRoll: d20)
       blueLabelText.text = player.combatStatus
        
       brownButton.enabled = false
       brownButtonTimer()
       isThereAWinner()
So yeah - worked great, you'd press the button and things would happen. Problems here, though, were:
a) I had to repeat the dice stuff for each button because doing it once in the beginning was not working, the number wouldn't change.
b) I had to repeat the brownButton stuff for each button but with different names - in my onMonsterButtonPressed, I have the same shit but with 'blackButton' instead. It's just bad mmakay, even a noob like me knows that's messy.
c) it looks sloppy and confused. Almost like.. someone just tossed it in there and didn't know what they were doing. Oh wait... ;)

To fix this, I created a class (in its own file) and called it Game. I don't know if that's the right way to do it but it seemed pretty legit at the time.  I added the dice as private vars and tried to recreate the method in a more generic way. Here's what I have so far. I'm not done but I'm tired and it's time to stop!
    func performAttack(attacker: Character, target: Character, button: UIButton) {
        attacker.tryAttack(target, attackStrength: attacker.attackPower, hitRoll: d20)
        button.enabled = false
    }
This... might work. It should work. I think. We'll see. I got this far and realized it might be really silly having both tryAttack and performAttack so I am going to try and combine them tomorrow. Problem there is that I'm not sure where the resulting creature should reside - maybe under Game? It seems controllery to me so it is not going back into the ViewController. I don't know, I'm still a noob. I need to read more before I can state any of this with any sort of confidence!

I am, however, entirely confident that I'm exhausted and will have better results tomorrow.

No comments:

Post a Comment