无故事王国
5 天以前 510991a68acc59e22602d95582e3b1cabdd093c2
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//
//  HomeListenGame_1_VC.swift
//  DolphinEnglishLearnStudent
//
//  Created by 无故事王国 on 2024/5/28.
//
 
import UIKit
 
let Games_1_Refresh_Noti = Notification.Name.init("Games_1_Refresh_Noti")
 
class HomeListenGame_1_VC: BaseVC {
 
    private var viewModel = FightAnswerViewModel()
    private var listen1Model:Listen1Model!
 
    var rootViewModel:HomeListenFightViewModel!
 
    private var totalCount:Int = 1 //游戏的总数量
 
    private lazy var label_class:UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.text = "1"
        label.textAlignment = .center
        label.font = UIFont.init(name: "Impact", size: 21)
        return label
 
    }()
 
    private let view_class_title = UIView()
 
    private lazy var label_hint:UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexStr: "#EE1111")
        label.text = "请在10s内选择答案!"
        label.textAlignment = .center
        label.isHidden = true
        label.font = .systemFont(ofSize: 14, weight: .medium)
        return label
    }()
 
    private lazy var view_studyHandleView:VoiceHandleView = {
        let studyHandleView = VoiceHandleView()
        return studyHandleView
    }()
 
    private lazy var collectionView:UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumInteritemSpacing = 3
        flowLayout.minimumLineSpacing = 3
        flowLayout.scrollDirection = .vertical
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.contentInset = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 35)
        collection.register(UINib(nibName: "ListenFight_Game_CCell", bundle: nil), forCellWithReuseIdentifier: "_ListenFight_Game_CCell")
        collection.isScrollEnabled = false
        return collection
    }()
 
    private var timer:Timer?
    private var times:Int = 10
    private var voicePlayer = VoicePlayer.share()
 
    private var answerSet = Set<Listen1SubModel>()
    private var currentAnswer:Listen1SubModel?{
        didSet{
            if let v = currentAnswer{
                view_studyHandleView.playUrl = v.correct
                voicePlayer.playerAt(url: v.correct)
                viewModel.answerType.accept(.none)
            }
        }
    }
 
    required init(listen1Model:Listen1Model){
        super.init(nibName: nil, bundle: nil)
        self.listen1Model = listen1Model
    }
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        voicePlayer.delegate = self
    }
 
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        timer?.invalidate()
        timer = nil
        voicePlayer.delegate = nil
        voicePlayer.playerInterrupt()
    }
 
    override func viewDidLoad() {
        super.viewDidLoad()
 
        if  listen1Model != nil{
            times = (listen1Model?.data?.time ?? 10) + 1
            collectionView.reloadData()
            label_hint.isHidden = false
            label_hint.text = "准备听题"
 
            for v in listen1Model?.subjectList ?? []{
                answerSet.insert(v)
            }
 
            print("--->开始答题:剩余:\(answerSet.count)")
 
            if listen1Model.data?.playNow  == true{
                self.currentAnswer = self.answerSet.randomElement() //随机
                if self.timer == nil{self.startTimer()}
            }else{
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    self.currentAnswer = self.answerSet.randomElement() //随机
                    if self.timer == nil{self.startTimer()}
                }
            }
        }
    }
 
    override func setUI() {
        super.setUI()
 
 
        view_class_title.jq_cornerRadius = 16
        view_class_title.backgroundColor = UIColor(hexStr: "#FBCF0F")
        view.addSubview(view_class_title)
        view_class_title.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(40)
            make.left.equalToSuperview().offset(40)
            make.height.equalTo(32)
            make.width.greaterThanOrEqualTo(32)
        }
 
        view_class_title.addSubview(label_class)
        label_class.text = "\(totalCount)"
        label_class.snp.makeConstraints { make in
            make.left.equalTo(11)
            make.right.equalTo(-12)
            make.centerY.equalToSuperview()
        }
 
 
        view.addSubview(view_studyHandleView)
        view_studyHandleView.snp.makeConstraints { make in
            make.left.equalTo(view_class_title.snp.right).offset(12)
            make.centerY.equalTo(view_class_title)
            make.width.equalTo(159)
            make.height.equalTo(52)
        }
 
        view.addSubview(label_hint)
        label_hint.snp.makeConstraints { make in
            make.left.equalTo(view_studyHandleView.snp.right).offset(23)
            make.centerY.equalTo(view_class_title)
            make.height.equalTo(20)
        }
 
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.jq_addShadows(shadowColor: UIColor.black.withAlphaComponent(0.1), corner: 8, radius: 10, offset: CGSize(width: 0, height: 2), opacity: 1)
        collectionView.backgroundColor = .clear
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(99)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
 
        view.layoutIfNeeded()
    }
 
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if let res = Array<Any>.CalmulateCell(listen1Model.subjectList.count){
            let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
            let w = (JQ_ScreenW - (collectionView.contentInset.left * 2) - (CGFloat(res.0) - 1.0) * layout.minimumInteritemSpacing) / Double(res.0)
            let h = (collectionView.frame.height - (layout.minimumLineSpacing * (Double(res.1) - 1.0))) / Double(res.1)
 
            if layout.itemSize != CGSize(width: w, height: h){
                layout.itemSize = CGSize(width: w, height: h)
                collectionView.reloadData()
            }
        }
    }
 
    func startTimer(){
        if timer == nil{
            timer = Timer(timeInterval: 1.0, target: self, selector: #selector(runloopTime), userInfo: nil, repeats: true)
        }
        timer?.fire()
        RunLoop.current.add(timer!, forMode: .common)
    }
 
    @objc private func runloopTime(){
        print("进入。。。")
        times -= 1
        label_hint.text = "请在\(max(times,1))s内选择答案!"
 
        if times == 0{
            timer?.fireDate = .distantFuture
            if let c = currentAnswer{
                answerSet.remove(c)
            }
            currentAnswer = answerSet.randomElement() //随机
            times = (listen1Model?.data?.time ?? 0) + 1
            timer?.fireDate = .distantPast
            totalCount += 1
            rootViewModel.errorNum += 1
            label_class.text = "\(totalCount)"
        }
        //答题完成
        if self.answerSet.count == 0{
            timer?.invalidate()
            completeQuestion()
        }
    }
 
    private func answerQuestion(){
        view.layoutIfNeeded()
        view.isUserInteractionEnabled = false
        guard let row = viewModel.selectIndex.value?.row else { alertError(msg: "请选择");return  }
 
        var answerType:Fight_lessonType = .none
 
        if currentAnswer?.id == listen1Model?.subjectList[row].id{
            answerType = .success
            voicePlayer.playSuccessVoice()
        }else{
            answerType = .fail
            voicePlayer.playFailVoice()
        }
        switch answerType {
        case .success:
            timer?.fireDate = .distantFuture
            viewModel.answerType.accept(.success)
            collectionView.reloadData()
            if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_ListenFight_Game_CCell", for: viewModel.selectIndex.value!) as? ListenFight_Game_CCell{
                let newRect = cell.contentView.convert(cell.bounds, from: self.collectionView)
                let x = abs(newRect.origin.x) + self.collectionView.contentInset.left + 5
                let y = abs(newRect.origin.y) + 99 + 5
                let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
                let copyView = view_studyHandleView.copyView()
                copyView.playBtn.isEnabled = false
                view.addSubview(copyView)
 
                UIView.animate(withDuration: 0.5) {
                    copyView.frame = CGRect(x: x, y: y, width: layout.itemSize.width - 10, height: 40)
                } completion: { _ in
                    //                                                                                                DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
                    //                                                                                                                self.voicePlayer.playerAt(url: self.currentAnswer?.correct)
                    //                                                                                                }
 
                    if self.viewModel.answerType.value == .success{
                        self.timer?.fireDate = .distantFuture
                        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                            self.times = (self.listen1Model?.data?.time ?? 10) + 1
                            self.totalCount += 1
                            self.rootViewModel.correctNum += 1
                            self.label_class.text = "\(self.totalCount)"
 
                            if let currentA = self.currentAnswer{
                                self.answerSet.remove(currentA)
                            }
 
                            self.currentAnswer = self.answerSet.randomElement()
                            self.viewModel.answerType.accept(.none)
                            print("--->下一题:\(self.currentAnswer?.id ?? 0) 剩余\(self.answerSet.count)  计数:\(self.totalCount)")
                            self.timer?.fireDate = .distantPast
                        }
                    }
                }
            }
 
        case .fail:
            rootViewModel.errorNum += 1
            totalCount += 1
            label_class.text = "\(totalCount)"
            viewModel.answerType.accept(.fail)
            timer?.fireDate = .distantFuture
            label_hint.text = "准备听题"
            //移除当前题目
            if let c = currentAnswer{
                answerSet.remove(c)
            }
            collectionView.reloadData()
            DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                self.timer?.fireDate = .distantPast
                self.times = (self.listen1Model?.data?.time ?? 10) + 1
                self.currentAnswer = self.answerSet.randomElement()
            }
        case .none:
            break
        }
    }
 
    private func completeQuestion(){
        print("答题完成")
        self.label_hint.text = "已完成全部答题"
        self.label_hint.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(view_class_title)
            make.height.equalTo(20)
        }
 
        view_class_title.isHidden = true
        view_studyHandleView.isHidden = true
 
        self.timer?.invalidate()
        self.rootViewModel.answerItems[0] = self.listen1Model
        NotificationCenter.default.post(name: NextLession_Noti, object: ["gameId":listen1Model.data!.id,"gameIntegral":listen1Model.data!.integral,"complete":true])
    }
}
 
extension HomeListenGame_1_VC:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //                                _ = listen1Model!.subjectList[indexPath.row]
        viewModel.selectIndex.accept(indexPath)
        answerQuestion()
    }
}
 
extension HomeListenGame_1_VC:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = listen1Model!.subjectList[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_ListenFight_Game_CCell", for: indexPath) as! ListenFight_Game_CCell
        if viewModel.selectIndex.value == indexPath{
            cell.setState(state: viewModel.answerType.value)
        }else{
            cell.setState(state: .none)
        }
 
        cell.setModel(model)
        return cell
    }
 
 
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return listen1Model?.subjectList.count ?? 0
    }
}
 
extension HomeListenGame_1_VC:VoicePlayerDelegate{
    func playComplete() {
 
        //防止再次播放时,误操作计算了正确率
        if viewModel.answerType.value == .none{
            view.isUserInteractionEnabled = true
        }
 
        timer?.fireDate = .distantPast ////播放中,恢复计时
 
        view_studyHandleView.resetView()
 
        self.label_hint.text = "准备听题"
 
        //                                if viewModel.answerType.value == .success{
        //                                                timer?.fireDate = .distantFuture
        //                                                DispatchQueue.main.asyncAfter(deadline: .now()+1) {
        //                                                                self.times = (self.listen1Model?.data?.time ?? 10) + 1
        //                                                                self.totalCount += 1
        //                                                                self.rootViewModel.correctNum += 1
        //                                                                self.label_class.text = "\(self.totalCount)"
        //
        //                                                                if let currentA = self.currentAnswer{
        //                                                                                self.answerSet.remove(currentA)
        //                                                                }
        //
        //                                                                self.currentAnswer = self.answerSet.randomElement()
        //                                                                self.viewModel.answerType.accept(.none)
        //                                                                print("--->下一题:\(self.currentAnswer?.id ?? 0) 剩余\(self.answerSet.count)  计数:\(self.totalCount)")
        //                                                                self.timer?.fireDate = .distantPast
        //                                                }
        //                                }
 
 
        //答题完成
        if self.answerSet.count == 0{completeQuestion()}
    }
 
    func playing() {
        view.isUserInteractionEnabled = false
        view_studyHandleView.playing()
        timer?.fireDate = .distantFuture //播放中,暂停计时
        //                                label_hint.text = "播放中"
        //                                label_hint.text = ""
        label_hint.text = "请在\(times)s内选择答案!"
    }
 
}