//
|
// HomeListenGame_2_VC.swift
|
// DolphinEnglishLearnStudent
|
//
|
// Created by 无故事王国 on 2024/5/28.
|
//
|
|
import UIKit
|
|
struct Game_2_SelectModel:Hashable{
|
var indexPath:IndexPath!
|
var model:SimpleListenDataModel!
|
}
|
|
class HomeListenGame_2_VC: BaseVC {
|
|
private var viewModel = FightAnswerViewModel()
|
var rootViewModel:HomeListenFightViewModel!
|
private var listen1Model:Listen1Model!
|
private var selectModels = [Game_2_SelectModel]()
|
|
private var datas = [SimpleListenDataModel]()
|
|
private var currentPayCellIndex:IndexPath?
|
|
private lazy var label_time:UILabel = {
|
let label = UILabel()
|
label.textColor = UIColor(hexStr: "#EE1111")
|
label.text = "0s"
|
label.font = UIFont.init(name: "Impact", size: 36)
|
return label
|
|
}()
|
|
private lazy var collectionView:UICollectionView = {
|
let flowLayout = UICollectionViewFlowLayout()
|
|
flowLayout.minimumInteritemSpacing = 10
|
flowLayout.minimumLineSpacing = 10
|
flowLayout.scrollDirection = .vertical
|
let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
|
collection.contentInset = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
|
collection.register(ListenFight_Game_Pocket_CCell.self, forCellWithReuseIdentifier: "_ListenFight_Game_Pocket_CCell")
|
collection.isScrollEnabled = false
|
collection.masksToBounds = false
|
return collection
|
}()
|
|
private var timer:Timer?
|
private var times:Int = 120
|
private var voicePlayer = VoicePlayer.share()
|
|
required init(listen1Model:Listen1Model){
|
super.init(nibName: nil, bundle: nil)
|
self.listen1Model = listen1Model
|
|
for v in listen1Model.photoList{
|
v.type = 1 // 图片标识
|
}
|
|
for v in listen1Model.voiceList{
|
v.type = 2 // 音频标识
|
}
|
times = (listen1Model.data?.answerTime ?? 120) + 1
|
|
datas.append(contentsOf: listen1Model.photoList)
|
datas.append(contentsOf: listen1Model.voiceList)
|
datas.shuffle()
|
}
|
|
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)
|
voicePlayer.delegate = nil
|
timer?.invalidate()
|
voicePlayer.playerInterrupt()
|
}
|
|
override func viewDidLoad() {
|
super.viewDidLoad()
|
|
startTimer()
|
}
|
|
override func setUI() {
|
super.setUI()
|
|
let label_surplusTitle = UILabel()
|
label_surplusTitle.textColor = UIColor.black
|
label_surplusTitle.text = "答题剩余时间:"
|
label_surplusTitle.font = .systemFont(ofSize: 14, weight: .medium)
|
|
view.addSubview(label_surplusTitle)
|
label_surplusTitle.snp.makeConstraints { make in
|
make.left.equalTo(40)
|
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(46)
|
make.height.equalTo(20)
|
}
|
|
view.addSubview(label_time)
|
label_time.snp.makeConstraints { make in
|
make.left.equalTo(label_surplusTitle.snp.right).offset(5)
|
make.centerY.equalTo(label_surplusTitle)
|
make.height.equalTo(44)
|
}
|
|
|
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(101)
|
make.left.right.equalToSuperview()
|
make.bottom.equalToSuperview()
|
}
|
|
view.layoutIfNeeded()
|
}
|
|
private 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(){
|
times -= 1
|
label_time.text = "\(times)s"
|
|
if times == 0{
|
timer?.fireDate = .distantFuture
|
CommonAlertView.showSimple(content: "答题时间已结束,停止作答!", completeTitle: "查看成绩") {
|
self.rootViewModel.answerItems[0] = self.listen1Model
|
NotificationCenter.default.post(name: NextLession_Noti, object: ["gameId":self.listen1Model.data!.id,"gameIntegral":self.listen1Model.data!.answerIntegral,"complete":false])
|
}
|
}
|
}
|
|
//判断检查两个Cell情况
|
private func checking(){
|
|
guard selectModels.count == 2 else {return}
|
|
let firstM = selectModels.first
|
let lastM = selectModels.last
|
|
|
if firstM != nil && lastM != nil{
|
if firstM!.model.id == lastM!.model.id{
|
firstM!.model.isOpen = true
|
lastM?.model.isOpen = true
|
selectModels.removeAll()
|
self.rootViewModel.insertCorrectAnswer(teamId: "\(listen1Model.data!.id)", answerId: firstM!.model.id)
|
viewModel.answerType.accept(.success)
|
rootViewModel.correctNum += 1
|
voicePlayer.playSuccessVoice()
|
self.selectModels.removeAll()
|
let firstIndexCell = self.collectionView.cellForItem(at: firstM!.indexPath) as! ListenFight_Game_Pocket_CCell
|
let secondIndexCell = self.collectionView.cellForItem(at: lastM!.indexPath) as! ListenFight_Game_Pocket_CCell
|
firstIndexCell.setState(success: true)
|
secondIndexCell.setState(success: true)
|
DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
|
self.view.isUserInteractionEnabled = true
|
}
|
|
}else{
|
viewModel.answerType.accept(.fail)
|
rootViewModel.errorNum += 1
|
let firstIndex = firstM!.indexPath
|
let secondIndex = lastM!.indexPath
|
voicePlayer.playFailVoice()
|
|
let firstIndexCell = self.collectionView.cellForItem(at: firstIndex!) as! ListenFight_Game_Pocket_CCell
|
let secondIndexCell = self.collectionView.cellForItem(at: secondIndex!) as! ListenFight_Game_Pocket_CCell
|
firstIndexCell.setState(success: false)
|
secondIndexCell.setState(success: false)
|
|
self.view.isUserInteractionEnabled = false
|
DispatchQueue.main.asyncAfter(deadline: .now()+1.0){
|
firstIndexCell.toBackAction(self.view)
|
secondIndexCell.toBackAction(self.view)
|
self.selectModels.removeAll()
|
}
|
DispatchQueue.main.asyncAfter(wallDeadline: .now()+1.7){
|
self.view.isUserInteractionEnabled = true
|
}
|
}
|
}
|
|
let surplusListCount = datas.filter({$0.isOpen == false}).count
|
if surplusListCount == 0{
|
rootViewModel.answerItems[0] = self.listen1Model
|
NotificationCenter.default.post(name: NextLession_Noti, object: ["gameId":listen1Model.data!.id,"gameIntegral":listen1Model.data!.answerIntegral,"complete":true])
|
timer?.invalidate()
|
}
|
print("剩余:\(surplusListCount)")
|
}
|
|
override func viewDidLayoutSubviews() {
|
super.viewDidLayoutSubviews()
|
let count = listen1Model.photoList.count + listen1Model.voiceList.count
|
if let res = Array<Any>.CalmulateCell(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()
|
}
|
}
|
}
|
}
|
|
extension HomeListenGame_2_VC:UICollectionViewDelegate{
|
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
|
if voicePlayer.isPlaying{
|
print("正在播放语音");return
|
}
|
|
if datas[indexPath.row].isOpen{
|
print("已经展开过了");return
|
}
|
|
if selectModels.last?.indexPath == indexPath{
|
print("重复点击");return
|
}
|
|
let model = datas[indexPath.row]
|
|
if selectModels.count >= 2{
|
selectModels.removeFirst()
|
}
|
|
selectModels.append(Game_2_SelectModel(indexPath: indexPath, model: model))
|
|
print(selectModels.map({"\($0.indexPath.row)"}).joined(separator: "——"))
|
|
if selectModels.count == 1{
|
let cell = self.collectionView.cellForItem(at: indexPath) as! ListenFight_Game_Pocket_CCell
|
cell.toFromAction(self.view,c: true)
|
|
if model.type == 2{
|
//播放
|
cell.cellPlaying()
|
voicePlayer.playerAt(url: model.voice)
|
}
|
}
|
|
if selectModels.count == 2{
|
let cell = self.collectionView.cellForItem(at: indexPath) as! ListenFight_Game_Pocket_CCell
|
cell.toFromAction(self.view)
|
|
if model.type == 2{
|
//语音先播放,再评估
|
cell.cellPlaying()
|
voicePlayer.playerAt(url: model.voice)
|
return
|
}
|
checking()
|
}
|
}
|
}
|
|
extension HomeListenGame_2_VC:UICollectionViewDataSource{
|
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
|
let model = datas[indexPath.row]
|
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_ListenFight_Game_Pocket_CCell", for: indexPath) as! ListenFight_Game_Pocket_CCell
|
cell.indexPath = indexPath
|
cell.setSimpleModel(model)
|
cell.cellPayatIndex {[weak self] index in
|
self?.currentPayCellIndex = index
|
}
|
return cell
|
}
|
|
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
|
return datas.count
|
}
|
}
|
|
extension HomeListenGame_2_VC: UICollectionViewDelegateFlowLayout {
|
|
// 实现以下方法以支持转场动画
|
func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
|
return UICollectionViewTransitionLayout(currentLayout: fromLayout, nextLayout: toLayout)
|
}
|
|
// 实现以下方法以返回自定义的转场动画控制器
|
func collectionView(_ collectionView: UICollectionView, transitionAnimationControllerForOldCell: UICollectionViewCell, newCell: UICollectionViewCell) -> UIViewControllerAnimatedTransitioning? {
|
return FlipAnimationController()
|
}
|
|
// FlipAnimationController实现转场动画的具体细节
|
class FlipAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
|
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
|
return 0.3
|
}
|
|
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
|
guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { return }
|
guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return }
|
let containerView = transitionContext.containerView
|
|
// 初始化动画参数
|
toView.frame = transitionContext.finalFrame(for: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!)
|
containerView.addSubview(toView)
|
|
// 翻牌动画
|
UIView.transition(from: fromView, to: toView, duration: transitionDuration(using: transitionContext), options: [.transitionFlipFromLeft]) { completed in
|
transitionContext.completeTransition(completed)
|
}
|
}
|
}
|
}
|
|
extension HomeListenGame_2_VC:VoicePlayerDelegate{
|
func playComplete() {
|
// view.isUserInteractionEnabled = true
|
//正在播放的语音Cell要归位
|
if let index = currentPayCellIndex{
|
let cell = collectionView.cellForItem(at: index) as! ListenFight_Game_Pocket_CCell
|
cell.cellResotePay()
|
view.isUserInteractionEnabled = true
|
}
|
checking()
|
}
|
|
func playing() {
|
// view.isUserInteractionEnabled = false
|
}
|
|
}
|