Swift で数あてゲーム
import Foundation
class GuessNumber {
lazy var correctNumber: Int = self.randomNumber()
var answerNumber: Int = 0
var answerCount: Int = 1
init() {
// Initialize and start game
printGameGuide()
startGameLoop()
}
func printGameGuide() {
print("0から999までの範囲にある数字を1つ用意しました。これを当ててください")
print("(入力に対して、大きな・小さな数字かヒントが出ます)\n")
}
func randomNumber() -> Int {
return {
// extract 3 digits from random number
let digit = 1_000
let num = Double(arc4random()) / Double(digit)
let cutBeforeDot = Int(num)
return Int((num - Double(cutBeforeDot)) * Double(digit))
}()
}
func askAnswer() -> Int {
print("> 数字を入力してください:")
return Int(readLine(strippingNewline: true)!)!
}
func printHint(answerNumber: Int, correctNumber: Int) {
let difference: Int = answerNumber - correctNumber
if difference == 0 {
print("正解!!")
} else if difference < 0 {
print(" ?:入力より大きな値です\n")
} else {
print(" ?:入力より小さな値です\n")
}
}
func startGameLoop() {
repeat {
answerNumber = askAnswer() // Update value
printHint(answerNumber: answerNumber, correctNumber: correctNumber)
print("---------------------------")
if answerNumber != correctNumber { answerCount += 1 }
} while answerNumber != correctNumber
print("(", answerCount, "回で正解しました!)")
}
}
let guessNumber = GuessNumber()