-
Notifications
You must be signed in to change notification settings - Fork 0
/
AndroidFirebaseConnection.kt
373 lines (333 loc) · 16.4 KB
/
AndroidFirebaseConnection.kt
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
package group16.project.game
import android.app.Activity
import android.content.ContentValues.TAG
import android.util.Log
import com.badlogic.gdx.Gdx
import com.google.firebase.database.*
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.ValueEventListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import group16.project.game.models.FirebaseInterface
import group16.project.game.models.Game
import group16.project.game.models.GameInfo
import group16.project.game.models.GameState
import group16.project.game.views.GameScreen
import group16.project.game.views.JoinLobbyScreen
import group16.project.game.views.HighScoreScreen
import kotlin.properties.Delegates
class AndroidFirebaseConnection : FirebaseInterface, Activity() {
//the link should may be stored in a separate file, be put here through a reference.
private val database = Firebase.database("https://tdt4240-battlestar-default-rtdb.europe-west1.firebasedatabase.app/")
private var auth: FirebaseAuth = Firebase.auth
/**
* Sign in the user anonymously, is it is a new user add user to db
*/
override fun signInAnonymously() {
// [START signin_anonymously]
var myRef: DatabaseReference = database.getReference("users")
auth.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
println("signInAnonymously:success")
val currentUser = auth.currentUser
// If new user make user in db
if (currentUser != null) {
//If user do not exist add user to db with userName
myRef.child(currentUser.uid).get().addOnSuccessListener {
if (it.value == null) {
val userName = "user-" + currentUser.uid
myRef.child(currentUser.uid).child("userName").setValue(userName)
Gdx.app.log("Firebase", "Success on crating user")
} else {
Gdx.app.log("Firebase", "Success user already exist")
}
}.addOnFailureListener { //Failure, not connected to db
Gdx.app.log("Firebase", "Error getting data", it)
}
}
} else {
//Failure, could not sign in user
println("signInAnonymously:failure" + task.exception)
}
}
// [END signin_anonymously]
}
fun generateLobbyCode(): String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
return (1..6)
.map { allowedChars.random() }
.joinToString("")
}
/**
* Create new lobby with lobby name.
*/
override fun createLobby(lobbyName: String, gameController: StarBattle){
val randomLobbyCode = generateLobbyCode()
var myRef: DatabaseReference = database.getReference("lobbies").child(randomLobbyCode)
//Creates a random lobby code with letters and numbers (6 char code)
val user = auth.currentUser
myRef.get().addOnSuccessListener {
//If lobby with the randomly created lobby code do not exists create lobby
//and user logged in
if (it.value == null && user != null) {
//Set name of lobby and host with the user id
myRef.child("name").setValue(lobbyName)
myRef.child("host").child("id").setValue(user.uid)
myRef.child("host").child("lives").setValue(3)
gameController.updateCurrentGame(randomLobbyCode, "host", "player_2")
updateCurrentGameState(GameState.START)
// Adds newly created lobby to user in db
database.getReference("users").child(user.uid).child(randomLobbyCode).setValue(true)
println(randomLobbyCode)
Gdx.app.log("Firebase", "Success on creating lobby")
}
//If lobby exists or user not logged in try again
else {
createLobby(lobbyName, gameController)
}
}.addOnFailureListener {
//Failure, could not connect to db
Gdx.app.log("Firebase", "Error getting data", it)
}
}
/**
* Join lobby with lobby code
* Screen is for sending error message to the user
*/
override fun joinLobby(lobbyCode: String, screen: JoinLobbyScreen){
var myRef: DatabaseReference = database.getReference("lobbies").child(lobbyCode)
val user = auth.currentUser
myRef.get().addOnSuccessListener {
var lobby = it.value
//If user no logged in try again
if (user == null) {
joinLobby(lobbyCode, screen)
}
else if (lobby != null && lobby is Map<*, *> ) {
//If lobby exist and do not contain already a user add user to lobby
if (!lobby.containsKey("player_2")) {
myRef.child("player_2").child("id").setValue(user.uid)
myRef.child("player_2").child("lives").setValue(3)
screen.gameController.updateCurrentGame(lobbyCode, "player_2", "host")
updateCurrentGameState(GameState.SETUP)
//Add lobby to user
database.getReference("users")
.child(user.uid).child(lobbyCode).setValue(true)
Gdx.app.log("Firebase", "Success joining lobby")
//Sendig success message to user, also enabled to change screen
screen.errorMessage("Success")
} else {
//Sending error messge to user
screen.errorMessage("Lobby is full")
}
} else {
//Sending error message to user
screen.errorMessage("Lobby do not exist")
}
}.addOnFailureListener {
//Not connected to db
//Sending error message to user
screen.errorMessage("Something went wrong, not connected to server")
Gdx.app.log("Firebase", "Error getting data", it)
}
}
/**
* Create listener for highScore, update highScoreScreen when top 10 change og score change
*/
override fun getHighScoreListener(screen: HighScoreScreen) {
val myTopScore = database.getReference("score")
.orderByValue().limitToFirst(10)
Gdx.app.log("Firebase", "On child change ${myTopScore}")
myTopScore.addChildEventListener(object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) {
Gdx.app.log("Firebase", "On child added ${dataSnapshot} ${s}")
val userName = dataSnapshot.getKey().toString()
val score = Integer.parseInt(dataSnapshot.getValue().toString())
if (userName != null && userName is String && score != null && score is Int) {
screen.updateHighscore(userName, score)
}
}
override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) {
Gdx.app.log("Firebase", "on child change ${dataSnapshot} ${s}")
val userName = dataSnapshot.getKey().toString()
val score = Integer.parseInt(dataSnapshot.getValue().toString())
if (userName != null && userName is String && score != null && score is Int) {
screen.updateHighscore(userName, score)
}
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {
}
override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) {
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
override fun updateScore(points: Int) {
val updates: MutableMap<String, Any> = HashMap()
var myRef: DatabaseReference = database.getReference("score")
var user = auth.currentUser
if (user != null) {
var userName = "user-" + user.uid
myRef.child(userName).get().addOnSuccessListener {
var score = it.value
if (score != null) {
updates[userName] = ServerValue.increment(points * 1.0)
myRef.updateChildren(updates)
} else if (points < 0) {
myRef.child(userName).setValue(points)
}
}
}
}
override fun updateCurrentGameState(state: GameState) {
var myRef: DatabaseReference = database.getReference("lobbies").child(GameInfo.currentGame).child("current_gamestate")
println("State: ${state.name}")
myRef.setValue(state.name)
println("UPDATE GAME STATE: $state")
}
override fun setPlayersChoice(position: Int, targetPostion: Int, shieldPosition: Int, gameScreen: GameScreen) {
var myRef: DatabaseReference = database.getReference("lobbies").child(GameInfo.currentGame)
myRef.get().addOnSuccessListener {
if(it.value != null) {
myRef.child(GameInfo.player).child("position").setValue(position)
myRef.child(GameInfo.player).child("target_position").setValue(targetPostion)
myRef.child(GameInfo.player).child("shield_position").setValue(shieldPosition)
myRef.child(GameInfo.player).child("ready_to_fire").setValue(true)
println("YOU FIRE")
fire(gameScreen)
}
}.addOnFailureListener {
//Failure, could not connect to db
Gdx.app.log("Firebase", "Error getting data", it)
}
}
override fun getCurrentState(game: Game){
var gameState: DatabaseReference = database.getReference("lobbies").child(GameInfo.currentGame).child("current_gamestate")
gameState.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val currentState = dataSnapshot.getValue()
if (currentState != null) {
game.changeState(GameState.valueOf(currentState.toString()))
println("GET GAME STATE: ${GameState.valueOf(currentState.toString())}")
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
override fun heartListener(player: String, screen: GameScreen){
val health = database.getReference("lobbies").child(GameInfo.currentGame).child(player).child("lives")
health.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val playerHealth = dataSnapshot.getValue()
if(playerHealth != null) {
println("HEART LISTENER: ${player} ${playerHealth.toString()}")
screen.updateHealth(player, Integer.parseInt(playerHealth.toString()))
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
override fun reduceHeartsAmount() {
val updates: MutableMap<String, Any> = HashMap()
updates["${GameInfo.currentGame}/${GameInfo.player}/lives"] = ServerValue.increment(-1)
database.getReference("lobbies").updateChildren(updates)
}
override fun removeShield() {
val updates: MutableMap<String, Any> = HashMap()
updates["${GameInfo.currentGame}/${GameInfo.player}/shield_position"] = -2
updates["${GameInfo.currentGame}/${GameInfo.player}/shield_destroyed"] = true
database.getReference("lobbies").updateChildren(updates)
}
override fun updatePlayerHealth(){
var myRef: DatabaseReference = database.getReference("lobbies").child(GameInfo.currentGame)
myRef.get().addOnSuccessListener {
val opponentTargetPosition = (it.child(GameInfo.opponent).child("target_position").value as Long).toInt()
val shieldPosition = (it.child(GameInfo.player).child("shield_position").value as Long).toInt()
var shieldDestroyed = it.child(GameInfo.player).child("shield_destroyed").value
if (shieldDestroyed != null) shieldDestroyed = shieldDestroyed as Boolean
else shieldDestroyed = false
val yourPosition = (it.child(GameInfo.player).child("position").value as Long).toInt()
if (!shieldDestroyed && opponentTargetPosition == shieldPosition) {
println("REMOVE SHIELD")
removeShield()
} else {
if (opponentTargetPosition == yourPosition) {
println("UPDATE PLAYER HEALTH")
println(opponentTargetPosition)
println(yourPosition)
reduceHeartsAmount()
}
}
}
}
override fun checkIfOpponentReady(screen: GameScreen) {
var myRef: DatabaseReference = database.getReference("lobbies").child(GameInfo.currentGame).child(
GameInfo.opponent).child("ready_to_fire")
myRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val isReady = dataSnapshot.getValue()
if (isReady == true) {
println("ENEMY FIRE")
fire(screen)
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
override fun fire(screen : GameScreen) {
var myRef: DatabaseReference = database.getReference("lobbies").child(GameInfo.currentGame)
var bothHit = false
myRef.get().addOnSuccessListener {
if(it.value != null) {
val host = it.child("host")
val player2 = it.child("player_2")
val hostReady = host.child("ready_to_fire").value == true
val player2Ready = player2.child("ready_to_fire").value == true
if(hostReady and player2Ready) {
val player1MovingTo = host.child("position").value.toString().toInt()
val player1Shooting = host.child("target_position").value.toString().toInt()
var player1Shields = host.child("shield_position").value
if (player1Shields != null) player1Shields = player1Shields.toString().toInt()
else player1Shields = -1
val player2MovingTo = player2.child("position").value.toString().toInt()
val player2Shooting = player2.child("target_position").value.toString().toInt()
var player2Shields = player2.child("shield_position").value
if (player2Shields != null) player2Shields = player2Shields.toString().toInt()
else player2Shields = -1
if (player1MovingTo == player2Shooting && player2MovingTo == player1Shooting) bothHit = true
if (GameInfo.player == "host") screen.bothReady(
player2MovingTo,
player2Shooting,
bothHit,
player2Shields
)
else screen.bothReady(
player1MovingTo,
player1Shooting,
bothHit,
player1Shields
)
}
}
}.addOnFailureListener {
//Failure, could not connect to db
Gdx.app.log("Firebase", "Error getting data", it)
}
}
override fun resetReady() {
var myRef: DatabaseReference = database.getReference("lobbies").child(GameInfo.currentGame)
myRef.get().addOnSuccessListener {
if (it.value != null) {
myRef.child("host").child("ready_to_fire").setValue(false)
myRef.child("player_2").child("ready_to_fire").setValue(false)
}
}
}
override fun deleteLobby() {
database.getReference("users").child(auth.currentUser!!.uid).child(GameInfo.currentGame).removeValue()
database.getReference("lobbies").child(GameInfo.currentGame).removeValue()
}
}