#13 猜拳 App
Published in
2 min readMay 28, 2024
成品:
code:
import SwiftUI
struct ContentView: View {
// 狀態變數,用來存儲遊戲結果、電腦的選擇和玩家的選擇
@State var gameResult = "開始"
@State var pcPlayer: String = ""
@State var player: String = ""
@State var index: Int = 0
// 可選擇的選項
let moves = ["scissors", "stone", "paper"]
// 遊戲邏輯函數
func play() {
// 隨機生成電腦的選擇
index = Int.random(in: 0...2)
pcPlayer = moves[index]
// 判斷勝負
if player == pcPlayer {
gameResult = "平手!"
} else if player == "stone" && pcPlayer == "scissors" ||
player == "paper" && pcPlayer == "stone" ||
player == "scissors" && pcPlayer == "paper" {
gameResult = "你贏了!"
} else {
gameResult = "你輸了!"
}
}
var body: some View {
ZStack{
// 設置背景顏色為黃色,並且忽略安全區域
Color.yellow
.ignoresSafeArea()
VStack {
// 顯示電腦的選擇圖像
Image(pcPlayer)
.resizable()
.frame(width: 200, height: 200)
.scaledToFill()
.rotationEffect(.degrees(180)) // 旋轉圖像
// 顯示電腦的選擇文本
Text("pcPlayer: \(pcPlayer)")
.font(.headline)
.padding()
Spacer()
// 顯示遊戲結果
Text(gameResult)
.font(.title)
.bold()
.foregroundColor(.red)
Spacer()
// 玩家選擇按鈕
HStack {
Button(action: {
player = "scissors"
play() // 每次按鈕點擊後執行遊戲邏輯
}) {
MoveImage(name: "scissors", isSelected: player == "scissors")
}
Button(action: {
player = "stone"
play()
}) {
MoveImage(name: "stone", isSelected: player == "stone")
}
Button(action: {
player = "paper"
play()
}) {
MoveImage(name: "paper", isSelected: player == "paper")
}
}
}
.padding()
}
}
}
#Preview {
ContentView()
}
struct MoveImage: View {
let name: String
let isSelected: Bool
var body: some View {
Image(name)
.resizable()
.scaledToFit()
.frame(width: 100, height: 200)
.background(isSelected ? Color.blue : Color.clear) // 根據選擇狀態改變背景顏色
}
}
Github: