SwiftUI卡牌游戏:如何添加胜负判定弹窗?附实现代码
SwiftUI卡牌游戏添加胜负弹窗实现指南
需求说明
我跟着教程制作了一个简单的卡牌游戏,现在需要添加弹窗功能:
- 当玩家分数达到15分时,弹出提示"You win"
- 当CPU分数先达到15分时,弹出提示"You lose"
希望得到实现指导,同时想要相关学习资源自行研究,而非直接复制代码。
当前代码如下:
import SwiftUI struct ContentView: View { @State private var playCard = "card5" @State private var cpuCard = "card9" @State private var playerScore = 0 @State private var cpuScore = 0 var body: some View { ZStack { Image("background-plain") .resizable() .ignoresSafeArea() VStack{ Spacer() Image("logo") HStack{ Spacer() Image(playCard) Spacer() Image(cpuCard) Spacer() } Button(action: { //reset playerScore = 0 cpuScore = 0 }, label: { Image(systemName: "clock.arrow.circlepath") .font(.system(size: 60)) .foregroundColor(Color(.systemRed)) }) Button(action: { //gen. random betw. 2 and 14 let playerRand = Int.random(in: 2...14) let cpuRand = Int.random(in: 2...14) //Update the cards playCard = "card" + String(playerRand) cpuCard = "card" + String(cpuRand) //Update the score if playerRand > cpuRand { playerScore += 1 } else if cpuRand > playerRand { cpuScore += 1 } }, label: { Image("button") }) HStack{ Spacer() VStack{ Text("Player") .font(.headline) .padding(.bottom, 10.0) Text(String(playerScore)) .font(.largeTitle) } Spacer() VStack{ Text("CPU") .font(.headline) .padding(.bottom, 10.0) Text(String(cpuScore)) .font(.largeTitle) } Spacer() } .foregroundColor(.white) Spacer() } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
实现步骤
1. 添加弹窗相关状态变量
在ContentView的@State变量中添加以下内容,用来控制弹窗的显示状态和提示内容:
@State private var showAlert = false @State private var alertTitle = ""
2. 分数更新后检查胜负条件
在发牌按钮的action闭包中,更新分数之后添加胜负判断逻辑,触发对应弹窗:
//Update the score if playerRand > cpuRand { playerScore += 1 } else if cpuRand > playerRand { cpuScore += 1 } // 检查胜负条件 if playerScore >= 15 { alertTitle = "You win" showAlert = true } else if cpuScore >= 15 { alertTitle = "You lose" showAlert = true }
3. 添加弹窗修饰符
给ZStack(或外层容器视图)添加.alert()修饰符,根据状态显示弹窗,并添加重置按钮:
ZStack { // 原有视图内容... } .alert(alertTitle, isPresented: $showAlert) { Button("Play Again") { // 重置游戏状态 playerScore = 0 cpuScore = 0 playCard = "card5" cpuCard = "card9" } }
学习资源推荐
- 研究SwiftUI官方文档中的
Alert组件章节,了解弹窗的基础用法和自定义配置 - 学习SwiftUI的状态管理机制(@State、@Binding等),理解状态如何驱动视图更新
- 尝试实现不同样式的弹窗(比如带文本输入、多个按钮的弹窗),加深对互动组件的理解
内容的提问来源于stack exchange,提问作者CharlieMalibu
相关产品推荐
相关产品推荐

