#12 選擇題 App

成品:

code:



import UIKit

class ViewController: UIViewController {

@IBOutlet weak var titleNumberLabel: UILabel! // 顯示題目編號的標籤
@IBOutlet weak var topicLabel: UILabel! // 顯示題目的標籤
@IBOutlet weak var scoreLabel: UILabel! // 顯示得分的標籤
@IBOutlet weak var answerResultLabel: UILabel! // 顯示答案結果的標籤
@IBOutlet weak var optionOneLabel: UIButton! // 選項一按鈕
@IBOutlet weak var optionTwoLabel: UIButton! // 選項二按鈕
@IBOutlet weak var optionThreeLabel: UIButton! // 選項三按鈕
@IBOutlet weak var restartButton: UIButton! // 重新開始按鈕

var questions = [MultipleChoiceQuestion]() // 儲存題目的陣列
var currentQuestions = [MultipleChoiceQuestion]() // 目前的題目陣列
var index = 0 // 目前題目的索引
var score = 0 // 目前得分
var answer = "" // 使用者的答案

// 初始化題目
func initQuestions() {
let question1 = MultipleChoiceQuestion(questionText: "世界上最高的山峰是?", option1: "珠穆朗玛峰", option2: "喜马拉雅山", option3: "阿尔卑斯山", correctAnswerText: "珠穆朗玛峰")
questions.append(question1)
// 其他題目初始化...
}

override func viewDidLoad() {
super.viewDidLoad()

initQuestions() // 初始化題目
questions.shuffle() // 將題目隨機排序
titleNumberLabel.text = "第\(index+1)/10題" // 顯示目前題目編號
topicLabel.text = questions[index].questionText // 顯示目前題目的內容
optionOneLabel.setTitle(questions[index].option1, for: .normal) // 設置選項一的文字
optionTwoLabel.setTitle(questions[index].option2, for: .normal) // 設置選項二的文字
optionThreeLabel.setTitle(questions[index].option3, for: .normal) // 設置選項三的文字
scoreLabel.text = "目前得分:\(score)" // 顯示目前得分
}

// 顯示下一題
func next() {
if index < 9 {
index += 1
titleNumberLabel.text = "第\(index+1)/10題"
topicLabel.text = questions[index].questionText
optionOneLabel.setTitle(questions[index].option1, for: .normal)
optionTwoLabel.setTitle(questions[index].option2, for: .normal)
optionThreeLabel.setTitle(questions[index].option3, for: .normal)
} else {
answerResultLabel.text = "答題已結束,可重新開始"
scoreLabel.text = "最終得分:\(score)"
topicLabel.text = ""
optionOneLabel.isHidden = true
optionTwoLabel.isHidden = true
optionThreeLabel.isHidden = true
}
}

// 更新顯示得分
func scoreText() {
scoreLabel.text = "目前得分:\(score)"
}

// 選擇答案的動作
@IBAction func choiceAnswer(_ sender: UIButton) {
if sender.currentTitle == questions[index].correctAnswerText {
score += 10
scoreText()
next()
} else {
scoreText()
next()
}
}

// 重新開始遊戲
@IBAction func restart(_ sender: Any) {
index = 0
score = 0
questions.shuffle()
titleNumberLabel.text = "第\(index+1)/10題"
topicLabel.text = questions[index].questionText
optionOneLabel.setTitle(questions[index].option1, for: .normal)
optionTwoLabel.setTitle(questions[index].option2, for: .normal)
optionThreeLabel.setTitle(questions[index].option3, for: .normal)
scoreLabel.text = "目前得分:\(score)"
answerResultLabel.text = ""
optionOneLabel.isHidden = false
optionTwoLabel.isHidden = false
optionThreeLabel.isHidden = false
}
}

Github:

--

--