【发布时间】:2016-09-11 18:04:49
【问题描述】:
我正在尝试制作一个简单的石头剪刀布游戏。为此,我使用了 switch 语句,但由于某种原因它无法正常工作。
这是我制作这个小游戏时想到的结构:
Rock、Scissors、Paper 共有三个按钮,你必须选择一个。 有一个标签告诉对手(计算机)选择了什么,我将其命名为对手标签。 有一个标签告诉结果是什么(例如“你赢了”),我将它命名为 resultLabel
它是这样工作的(这就是它的结构):
var a = Int()
if the player chooses Rock ---> a = 0
if the player chooses Paper ---> a = 1
if the player chooses Scissors ---> a = 2
For the opponent (computer, not a person) there is a randomNumber which
could be 0,1,2, and same here, if 0->opponent chose rock, if
1->opponent chose paper, if 2-> opponent chose scissors
然后我写了一个 switch 语句将它们放在一起。 问题是,由于某种原因,当我运行应用程序时,如果我选择岩石一切正常,但当我选择纸张或剪刀时,结果是错误的。
例如,如果我选择纸 (a = 1),而对手有纸(这意味着随机数恰好是 randomNumber = 1),则 resultLabel 不是应该的“DRAW”,而是这是“你迷路了”:纸和剪刀不起作用!我究竟做错了什么? 完整代码如下:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var opponentLabel: UILabel!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var rockButton: UIButton!
@IBOutlet weak var paperButton: UIButton!
@IBOutlet weak var scissorsButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func Hide() {
opponentLabel.hidden = true
resultLabel.hidden = true
}
func unHide() {
opponentLabel.hidden = false
resultLabel.hidden = false
}
var a = Int()
var randomNumber = Int()
func randomChoice() {
randomNumber = Int(arc4random() % 3)
NSLog("randomNumber%ld", randomNumber)
}
func gameOn() {
switch(randomNumber) {
case 0:
opponentLabel.text = "The opponent chose : ROCK"
if a == 0 {
resultLabel.text = "DRAW"
} else {
if a == 1 {
resultLabel.text = "YOU WON!"
}
if a == 2 {
resultLabel.text = "YOU LOST!"
}
}
unHide()
break
case 1:
opponentLabel.text = "The opponent chose: PAPER"
if a == 0 {
resultLabel.text = "YOU LOST!"
} else {
if a == 1 {
resultLabel.text = "DRAW"
}
if a == 2 {
resultLabel.text = "YOU WON!"
}
}
unHide()
break
case 2:
opponentLabel.text = "The opponent chose: SCISSORS"
if a == 0 {
resultLabel.text = "YOU WON!"
} else {
if a == 1 {
resultLabel.text = "YOU LOST!"
}
if a == 2 {
resultLabel.text = "DRAW"
}
}
unHide()
break
default:
break
}
}
@IBAction func rockButton(sender: AnyObject) {
a == 0
randomChoice()
gameOn()
}
@IBAction func paperButton(sender: AnyObject) {
a == 1
randomChoice()
gameOn()
}
@IBAction func scissorsButton(sender: AnyObject) {
a == 2
randomChoice()
gameOn()
}
}
【问题讨论】:
-
并且你应该避免使用break语句,除了默认情况(因为里面没有任何动作)