目标:

做一个机器和用户猜拳的应用

用户有积分,获胜+1,失败-1

样式:

代码:

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
// ContentView.swift
// challenge2-mora
//
// Created by 张洪Heo on 2020/8/12.
// Copyright © 2020 张洪Hoo. All rights reserved.
//

import SwiftUI

struct ContentView: View {
let mora = ["✌🏻","✊🏻","🤚🏻"]
@State private var robot = 4
@State private var result = 0
@State private var resulttxt = ["还未开始","你获胜了","你输了","打平了"]
@State private var score = 0

var body: some View {
GeometryReader { geo in
VStack {
Text("猜拳")
.font(.largeTitle)
.fontWeight(.black)

Text(self.resulttxt[self.result])

Text("当前分数为 \(self.score)")

ZStack {
Circle()
.frame(width: geo.size.width / 2, height: geo.size.width / 2)
.foregroundColor(.blue)

Text(self.robot == 4 ? "?" : self.mora[self.robot])
//如果机器值为4显示问号
.foregroundColor(.white)
.font(.system(size: 60, weight: .bold, design: .default))

}

HStack {
ForEach(0 ..< self.mora.count) { item in
choiceBtn(geo: geo, item: self.mora[item])
.onTapGesture {
self.play(user: item)
}
}
}

}
}

}

//开始运行
func play(user: Int) {
let robot = Int.random(in: 0 ... 2)
self.robot = robot

//判断猜拳胜负
if robot == user {
self.result = 3
}else if (robot - user == 1 || robot - user == -2) {
self.result = 2
self.score += -1
}else {
self.result = 1
self.score += 1
}

}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

struct choiceBtn: View {
let geo: GeometryProxy
let item: String

var body: some View {
ZStack {
Circle()
.frame(width: geo.size.width / 4, height: geo.size.width / 4)
Text(item)
.font(.system(size: 30))
}
}
}