当一个玩家的数据被更改后,如何将数据反映到另一台设备上?多人游戏

问题描述

我正在使用Swift和Firestore打井字游戏。这个井字游戏应该是一个在线游戏,其中两个玩家可以使用两个手机进行战斗。

enter image description here

就目前而言,我能够使player1和player2访问Firestore中的同一游戏板阵列。 诸如[“ apple”,“”,“”,“”,“ apple”,“ apple”,“”,“”,“ apple”]之类的东西。该阵列可以存储9个项目(3 X 3方形井字游戏),分别是“”,“苹果”,“菠萝”。目前,我没有添加允许玩家将回合切换到对手的功能,因此在数组中,您只能看到“ apple”或“”。 当用户点击按钮时,可以使用字符串“ apple”和“菠萝”来更改图像的正方形。

所以,我现在要使用包含苹果的数组,我想更改对手屏幕的按钮图像。到目前为止,玩家1(renao)和玩家2(renaodesuyo)可以访问数组[[apple],“”,“”,“”,“ apple”,“ apple”,“”,“”,“ apple”],并且只有player1可以将按钮的图像更改为“ apple”(因为player1轻按了按钮,而player2则什么也不做)。我的问题是我不知道如何在播放器1轻按按钮时将播放器2的按钮图像自动更改为“苹果”。

这是我的代码的一部分。

class GameScreenViewController: UIViewController {

var gameBoard: [String] = [
    "","",]

override func viewDidLoad() {
    super.viewDidLoad()
    loadGameInfo()
}

func loadGameInfo() {
    
    let docRef = db.collection(K.FStore.newGameCollection).document(gameDocumentID)
    
    docRef.addSnapshotListener { documentSnapshot,error in
        guard let document = documentSnapshot else {
            print("Error fetching document: \(error!)")
            return
        }
        guard let data = document.data() else {
            print("Document data was empty.")
            return
        }

        self.player1UID = data[K.FStore.uID] as! String
        self.gameBoard = data[K.FStore.gameBoardField] as! [String]
    }
}

func changePlateImage (plate: UIButton) {

    let fruitImage = isPlayer1 ? K.Image.apple : K.Image.pineapple

    plate.setImage(UIImage(named: fruitImage),for: .normal)

    changeGameBoard(index: plate.tag,fruit: fruitImage)
}

func changeGameBoard (index: Int,fruit: String){
    // add name of the fruit in the gameBoard
    gameBoard[index] = fruit
    
    print("this is the local game board: \(gameBoard)")
}


func changePlateImage (plate: UIButton) {

    let fruitImage = isPlayer1 ? K.Image.apple : K.Image.pineapple

    plate.setImage(UIImage(named: fruitImage),fruit: fruitImage)
}

func updateGameData() {
    let docRef = db.collection(K.FStore.newGameCollection).document(gameDocumentID)
    
    print("this will be the new local game board \(gameBoard)")
    docRef.updateData([
        K.FStore.gameBoardField: gameBoard,]) 
}

@IBAction func platePressed(_ sender: UIButton) {
    if isPlayer1 && playerID == player1UID{

        changePlateImage(plate: sender)
        updateGameData()
        
    } else if !isPlayer1 && playerID != player1UID {
        print("\(isPlayer1)")
    }
}
}

对不起。我的代码很长,所以我只提取了我需要的部分。有没有办法自动更新另一部手机的图像?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...