Intro App Dev 21 Final Project
Rock, Paper, Sissors 코드는 아래와 같습니다.
var current_status:GameState = .start 라 해 놓고
initiateElement() 에서
current_status = .start
gameStateLabel.text = current_status.description
라고 관리하고
func play() 안에서는 gameResult 를 이용해서 state 관리하는게 좋은 코드 같지 않습니다.
State 관리 어떻게 하는 게 좋은 코드인가요?
Swift의 특징을 잘 살리는 법?
//
// ViewController.swift
// RPS
//
// Created by sel2 on 2021/03/14.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var robotsDecisionLabel: UILabel!
@IBOutlet weak var gameStateLabel: UILabel!
@IBOutlet weak var rockBtn: UIButton!
@IBOutlet weak var sissorsBtn: UIButton!
@IBOutlet weak var paperBtn: UIButton!
@IBOutlet weak var playAgainBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
initiateElement()
}
var current_status:GameState = .start
func initiateElement() {
robotsDecisionLabel.text = "🤖"
current_status = .start
gameStateLabel.text = current_status.description //디버깅 중...
rockBtn.isHidden = false
sissorsBtn.isHidden = false
paperBtn.isHidden = false
rockBtn.isEnabled = true
sissorsBtn.isEnabled = true
paperBtn.isEnabled = true
playAgainBtn.isHidden = true
}
func play(_ userTurn: Sign) {
rockBtn.isEnabled = false
sissorsBtn.isEnabled = false
paperBtn.isEnabled = false
let opponent_value = randomSign()
robotsDecisionLabel.text = opponent_value.emoji
let gameResult = userTurn.match(opponent_value)
gameStateLabel.text = gameResult.description
playAgainBtn.isHidden = false
switch userTurn {
case .rock:
rockBtn.isHidden = false
sissorsBtn.isHidden = true
paperBtn.isHidden = true
case .sissors:
rockBtn.isHidden = true
sissorsBtn.isHidden = false
paperBtn.isHidden = true
case .paper:
rockBtn.isHidden = true
sissorsBtn.isHidden = true
paperBtn.isHidden = false
}
}
@IBAction func rockSelected(_ sender: Any) {
play(Sign.rock)
}
@IBAction func sissorsSelected(_ sender: Any) {
play(Sign.sissors)
}
@IBAction func paperSelected(_ sender: Any) {
play(Sign.paper)
}
@IBAction func playAgain(_ sender: Any) {
initiateElement()
}
}