summaryrefslogtreecommitdiff
path: root/battle/main.py
blob: f3b13f9759f2b3488cb903ef0fe47357f8298e95 (plain) (blame)
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
########################################################################################
#     This file is part of Spheres.
#     Copyright (C) 2019  Jesusalva

#     This library is free software; you can redistribute it and/or
#     modify it under the terms of the GNU Lesser General Public
#     License as published by the Free Software Foundation; either
#     version 2.1 of the License, or (at your option) any later version.

#     This library is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#     Lesser General Public License for more details.

#     You should have received a copy of the GNU Lesser General Public
#     License along with this library; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
########################################################################################
# Battle Module - Main module
from utils import stdout, dl_search, compress, allunits, Player, Battle, allquests
from consts import (CRYSTAL_MIN, CRYSTAL_MAX, EXPRATE_MIN, EXPRATE_MAX,
    GPPRATE_MIN, GPPRATE_MAX, ERR_ERR, ERR_BAD, ST_TOWN, ST_QUEST, ACT_SPHERE,
    SFLAG_CLEARGEMS, SFLAG_DOUBLEGEMS, SFLAG_SPECIAL,
    SFLAG_FIRSTLOOT, SFLAG_DOUBLEEXP, SFLAG_DOUBLEGP,
    SPH_WIDEATTACK, SPH_PIERCE, SPH_ASSAULT, SPH_HEAL, SPH_HEALALL, SPH_ATKUP,
    SPH_DEFUP, SPH_NONE)
import json, random, traceback
import player
from battle.common import (find_target, check_enemy_alive, check_player_alive,
    calc_dmg)
from battle.spheres import sphere_attack
#from battle.summons import summon # <-- Protocol?
#from battle.skills import skill_core, handle_skill # <-- WIP

# Prepare a randomness seed
random.seed()

#############################################
# Structural functions
#############################################
# Update enemy list with the next wave data. No checks are conducted.
def advance_wave(token, world, quest_id, next_wave):
    global Battle, allquests
    Battle[token]["enemy"]=[]
    Battle[token]["log"].append(["WAVE", 0, True, "", 0])
    stdout("advance_wave was called")

    quest=dl_search(allquests[world], "quest_id", quest_id)
    if quest == "ERROR":
        stdout("ERROR, INVALID QUEST: %d" % (quest_id))
        # TODO: HANDLE THIS ERROR (FIXME)

    for en in quest["waves"][next_wave]:
        mil=quest["difficulty"]/10.0
        if (en["boss"]):
            mil*=5.5

        mil=mil
        stdout("Recording new enemy with mil: %d" % mil)
        Battle[token]["enemy"].append({
            "name": en["name"],
            "unit_id": en["sprite"],
            "max_hp": int(900*mil),
            "hp": int(900*mil),
            "atk": int(100*mil),
            "ele": en["attribute"],
            "status_effects": 0
            })

    # Update wave
    stdout("Advancing wave")
    Battle[token]["wave"]+=1
    return True

# get_result(str, bool, str, int)
def get_result(token, victory, world, quest_id):
    global Player, Battle, allquests
    result={
            "result": "",
            "gp": 0,
            "exp": 0,
            "crystals": 0,
            "loot": [],
            "rank": 0,
            "log": Battle[token]["log"]
        }

    stdout("GR: Begin")
    # You lost?
    if not victory:
        result["result"]="DEFEAT"
        return result

    # Prepare data
    result["result"]="VICTORY"
    quest=dl_search(allquests[world], "quest_id", quest_id)
    if quest == "ERROR":
        print("ERROR, INVALID QUEST")
        stdout("Quest %d is invalid", str(quest_id))
        # TODO: HANDLE THIS ERROR (FIXME)
        return result

    stdout("GR: Rolling")
    # Roll each wave
    # Base quest experience gain
    result["exp"]+=quest["difficulty"]*10
    for wave in quest["waves"]:
        for en in wave:
            # Roll GP for each wave
            if en["boss"]:
                result["gp"]+=quest["difficulty"]*30
                result["exp"]+=quest["difficulty"]
            else:
                result["gp"]+=quest["difficulty"]*10
                result["exp"]+=quest["difficulty"]/3

            # TODO: Roll the loots for every enemy in every death

    result["exp"]=int(result["exp"])
    stdout("GR: Looting")
    # For now, loots are rolled for quest
    # 2- Roll loot list
    for loot, chance in quest["loot"]:
        if (random.randint(0, 10000) < chance):
            loot=int(loot)
            # Crystals are... Tricky
            if loot >= CRYSTAL_MIN and loot <= CRYSTAL_MAX:
                result["crystals"]+=(loot-CRYSTAL_MIN)
            elif loot >= EXPRATE_MIN and loot <= EXPRATE_MAX:
                result["exp"]*=(loot-EXPRATE_MIN)/1000.0
                result["exp"]=int(result["exp"])
            elif loot >= GPPRATE_MIN and loot <= GPPRATE_MAX:
                result["gp"]*=(loot-GPPRATE_MIN)/1000.0
                result["gp"]=int(result["gp"])
            else:
                result["loot"].append(int(loot)*100) # Fix Unit ID from base to ID

    stdout("GR: Flagging")
    # Mark the quest as complete and grant you crystals for first clear
    # But this is based on the flags (we can have special quests)
    if (not (quest["flags"] & SFLAG_SPECIAL) and Player[token]["quest"] < quest["quest_id"]):
        Player[token]["quest"]=0+quest["quest_id"]
        if (quest["flags"] & SFLAG_CLEARGEMS):
            result["crystals"]+=100
        if (quest["flags"] & SFLAG_DOUBLEGEMS):
            result["crystals"]+=200
        if (quest["flags"] & SFLAG_FIRSTLOOT):
            loot=int(quest["loot"][0][0])
            # Crystals are... Tricky
            if loot >= CRYSTAL_MIN and loot <= CRYSTAL_MAX:
                result["crystals"]+=(loot-CRYSTAL_MIN)
            else:
                result["loot"].append(int(loot)*100) # Fix Unit ID from base to ID
    if (quest["flags"] & SFLAG_DOUBLEEXP):
        result["exp"]*=2
    if (quest["flags"] & SFLAG_DOUBLEGP):
        result["gp"]*=2

    stdout("GR: Applying")
    # Apply the results to player data
    Player[token]["gp"]+=result["gp"]
    Player[token]["exp"]+=result["exp"]
    Player[token]["crystals"]+=result["crystals"]
    for it in result["loot"]:
        ix=player.inventoryplace(token)
        if (ix >= 0):
            unit={
                "unit_id": it,
                "level": 1,
                "exp": 0
            }
            Player[token]["inv"][ix]=unit
        else:
            result["loot"].remove(it)
            # TODO: Send result ERR_FULL

    stdout("GR: EXPing")
    # Grant to party the same amount of experience
    pid=Battle[token]["party_id"]
    for m in Player[token]["party_"+str(pid)]:
        # This can happen normally
        if m["unit_id"] <= 0:
            continue
        player.grant_exp(token, m["inv_id"], result["exp"])
        v5=player.check_level_up(token, m["inv_id"])
        # FIXME: Don't disregard result
        stdout("Unit %d levelled up %d times" % (m["inv_id"], v5))


    stdout("GR: Ranking")
    # Player rank up
    rk=player.check_rank_up(token)
    if rk["code"]:
        result["rank"]=1+rk["ap"]
        result["rk_exp"]=Player[token]["exp"]
        result["rk_mexp"]=Player[token]["max_exp"]

    stdout("GR: Complete")

    # Send data
    return result

#############################################
# Client commands
#############################################
# begin_quest( world, quest_id, party_id )
def begin_quest(args, token, client_side=True):
    global allquests, Player, Battle
    # Data validation
    try:
        stdout("Begin Quest: %s" % args)
        bq=json.loads(args)
        stdout("JSON loaded")
        # Validation
        tmp=int(bq["quest_id"])
        tmp=int(bq["party_id"])
        if (tmp < 1 or tmp > 3):
            return ERR_BAD
        tmpw=str(bq["world"])
        tmp=int(Player[token]["quest"]) # FIXME
        for quest in allquests[tmpw]:
            if (quest["quest_id"] == bq["quest_id"]):
                break
        if (quest["quest_id"] != bq["quest_id"]):
            raise Exception("Quest not found")
        stdout("All fine thus far")
    except:
        stdout(traceback.format_exc())
        # Invalid data
        return ERR_BAD

    # We have `quest` variable loaded and now we'll only use it, but...

    # Can you start a quest? (In Town, Requeriments met, etc.)
    if (Player[token]["status"] != ST_TOWN and client_side):
        return ERR_BAD
    if (Player[token]["quest"] < quest["requeriment"]):
        return ERR_BAD
    if (Player[token]["ap"] < quest["cost"] and client_side):
        return ERR_BAD
    stdout("You can begin it!")


    Player[token]["status"]=int(quest["quest_id"])
    # client_side is an internal flag
    if client_side:
        #Player[token]["ap"]-=quest["cost"]
        player.update_ap(token, -(quest["cost"]))

    Battle[token]={
        "world": bq["world"],
        "quest_id": quest["quest_id"],
        "difficulty": quest["difficulty"],
        "result": "",
        "bp": 0,
        "wave": 0,
        "max_wave": len(quest["waves"]),
        "enemy": [],
        "party": [],
        "party_id": int(bq["party_id"]),
        "spheres": [],
        "log": [],
        "turn": 1}

    stdout("Data set")
    # Write the current wave enemies data
    advance_wave(token, bq["world"], quest["quest_id"], 0)

    # Write the current party (and their HP bar)
    for ux in Player[token]["party_"+str(int(bq["party_id"]))]:
        # If you don't have anyone here: Don't append to party
        if ux["unit_id"] == 0:
            continue

        #stdout("FOUND AN UX: %s" % str(ux))
        # Un: Entry in unit database. Ux: Entry on party.
        # TODO: Maybe use dl_search instead
        for un in allunits:
            if (un["unit_id"] == ux["unit_id"]):
                #stdout("[BEGIN_QUEST] Match found for un and ux unit_id (un is: %s)" % str(un))
                break
            else:
                continue

        # Wait, what?
        if (un["unit_id"] != ux["unit_id"]):
            print("Error, un and ux differs: %s vs %s" % (str(un["unit_id"]), str(ux["unit_id"])))
            return ERR_ERR

        stdout("Preparing party member")

        # How much HP/ATK bonus per level you'll get?
        # Each level boosts your stats in 1%
        lvl=int(Player[token]["inv"][ux["inv_id"]]["level"])-1
        hpboost=int(un["hp"]*(max(lvl-1, 0)/100.0))
        akboost=int(un["strength"]*(max(lvl-1, 0)/100.0))

        # generate unit data for battle
        Battle[token]["party"].append({
            "unit_id": un["unit_id"],
            "max_hp": un["hp"]+hpboost,
            "hp": un["hp"]+hpboost,
            "atk": un["strength"]+akboost,
            "ele": un["attribute"],
            "status_effects": 0
            })

    # Add 1~3 random spheres
    i=random.randint(1,3)
    while i > 0:
        i-=1
        Battle[token]["spheres"].append(random.choice([
            SPH_WIDEATTACK,
            SPH_PIERCE,
            SPH_ASSAULT,
            SPH_HEAL,
            SPH_HEALALL,
            SPH_ATKUP,
            SPH_DEFUP
            ]))

    # Add empty spheres to keep length
    while (len(Battle[token]["spheres"]) < 5):
        Battle[token]["spheres"].append(SPH_NONE)

    sjson=compress(Battle[token])
    return sjson



# This is separate for loop logic reasons. Ends the turn.
# Gives sphere, handle rewards if needed and sends data to client
def battle_endturn(token, spheres):
    global Battle
    # We now have to handle turn end and conditions
    Battle[token]["turn"]+=1
    stdout("Turn has ended")

    # Resave spheres
    stdout("Sphere list: "+str(spheres))
    Battle[token]["spheres"]=[]
    for i in spheres:
        Battle[token]["spheres"].append(int(i))

    # Remove an eventual none spheres
    while (Battle[token]["spheres"].count(SPH_NONE)):
        Battle[token]["spheres"].remove(SPH_NONE)
    stdout("Exceeding spheres removed")

    # Add 1~3 random spheres; But never go over 5 spheres
    i=min(random.randint(1,3), len(Battle[token]["spheres"]) - 5)
    while i > 0:
        i-=1
        sp=random.choice([
            SPH_WIDEATTACK,
            SPH_PIERCE,
            SPH_ASSAULT,
            SPH_HEAL,
            SPH_HEALALL,
            SPH_ATKUP,
            SPH_DEFUP
            ])
        Battle[token]["log"].append(["SP", len(Battle[token]["spheres"]), sp, "", 0])
        Battle[token]["spheres"].append(sp)

    stdout("Spheres added; Status before adjust: %s" % (str(Battle[token]["spheres"])))

    # Add empty spheres to keep length
    while (len(Battle[token]["spheres"]) < 5):
        Battle[token]["spheres"].append(SPH_NONE)

    # Delete Summon data if exists
    try:
        del Battle["s"]
    except:
        pass

    # Send data to client
    stdout("Sending data")
    sjson=compress(Battle[token])
    stdout("Data sent: %s" % sjson)
    return sjson

# Advance turn button. Main turn logic
# Receives a list of units position, and if they'll use sphere:
# { "unit": [uid1, uid2 ....], "sphere": [True/False array, in future will save skill as 2] }
def battle(args, token):
    global allquests, Player, Battle
    # Data validation
    try:
        #stdout("Advance round: %s" % args)
        bt=json.loads(args)
        #stdout("JSON loaded")
        # Validation
        tmp=len(bt["unit"])
        #stdout("vu: %d" % tmp)
        tmp=len(bt["sphere"])
        #stdout("vs: %d" % tmp)
        tmp=int(Player[token]["quest"]) # FIXME
        #stdout("ptq: %d pts: %d" % (tmp, Player[token]["status"]))
        if (Player[token]["status"] < ST_QUEST):
            return ERR_BAD
        #stdout("validation step 1")

        # Check if all members you've told us are valid
        """
        for j in bt["unit"]:
            i=False
            for k in Battle[token]["party"]:
                if (k["unit_id"] == j["unit_id"]):
                    i=True
                    break
            if not i:
                stdout("Supplied data is valid: Attempt to add invalid members")
                raise Exception("Attempted to add invalid members")
        """
        # Check if all spheres you've told us are valid
        # FIXME: bt["sphere"] should be bt["action"]
        """
        if sorted(bt["sphere"]) != sorted(Battle[token]["spheres"]):
            stdout("Spheres differ: %s != %s" % (str(sorted(bt["sphere"])), str(sorted(Battle[token]["spheres"]))))
            raise Exception("Different spheres")
        """
    except:
        # Invalid data
        traceback.print_exc()
        return ERR_BAD

    #######################################
    # Reorder your party based on your request. We already know its valid

    """
    tmp=[]
    for bat in Battle[token]["party"]:
        tmp.append(bat)

    Battle[token]["party"]=[]

    for j in bt["unit"]:
        for k in tmp:
            if (j["unit_id"] == k["unit_id"]):
                Battle[token]["party"].append(k)
                break
    """

    # Erase temporary variables
    del tmp
    stdout("Party reordered (SKIPPED)")
    Battle[token]["log"]=[]

    #######################################
    # Prepare temporary data
    spheres=[]
    for i in Battle[token]["spheres"]:
        spheres.append(int(i))
    print("Sphere list: "+str(spheres))

    #######################################
    # TODO: determine battle order

    ############
    # Friends
    for bat in Battle[token]["party"]:
        # The dead can't fight
        if (bat["hp"] <= 0):
            continue

        # Will you use a sphere?
        idx=Battle[token]["party"].index(bat)
        stdout("Check index %d" % idx)
        if (bt["sphere"][idx] == ACT_SPHERE):
            # Remove the sphere
            spheres[idx]=SPH_NONE
            sphere_attack(token, bat, Battle[token]["spheres"][idx], idx)
            Battle[token]["bp"]+=2
        else:
            sphere_attack(token, bat, SPH_NONE, idx)
            Battle[token]["bp"]+=1
        stdout("Attack performed")

        # If HP ends up broken
        if (bat["hp"] > bat["max_hp"]):
            bat["hp"]=0+bat["max_hp"]

        # HOLD THAT! Handle event
        if (not check_enemy_alive(token)):
            # You won! Do we have a next wave?
            stdout("You won!")
            if (Battle[token]["wave"] < Battle[token]["max_wave"]):
                stdout("Next wave detected: %s, Quest ID: %s\nWave: %s" % (token, Battle[token]["quest_id"], Battle[token]["wave"]))
                advance_wave(token, Battle[token]["world"], Battle[token]["quest_id"], Battle[token]["wave"])
                # Do not continue this loop: End the turn now
                return battle_endturn(token, spheres)
            else:
                # You won!
                stdout("Total Victory")
                Player[token]["status"]=ST_TOWN
                # TODO: enemy die = add reward
                result=get_result(token, True, Battle[token]["world"], Battle[token]["quest_id"])
                del Battle[token]
                return compress(result)

    stdout("Friends executed")

    # It never harms checking for suicide...
    if (not check_player_alive(token)):
        # You lost!
        Player[token]["status"]=ST_TOWN
        result=get_result(token, False, Battle[token]["world"], Battle[token]["quest_id"])
        del Battle[token]
        return compress(result)

    ############
    # Enemies
    for idx, bat in enumerate(Battle[token]["enemy"]):
        # The dead can't fight
        if (bat["hp"] <= 0):
            continue

        # Simple Attack
        target_id=find_target(token, "party")
        stdout("ENEMY: Perform attack against %d" % target_id)
        target=Battle[token]["party"][target_id]
        target["hp"]-=calc_dmg(token, bat, target, bat["atk"])
        Battle[token]["bp"]+=1

        Battle[token]["log"].append(["enemy", idx, SPH_NONE, "party", target_id])
        stdout("ENEMY: Attack performed")

        # If HP ends up broken
        if (bat["hp"] > bat["max_hp"]):
            bat["hp"]=0+bat["max_hp"]
            continue

        # HOLD THAT! Handle event
        if (not check_player_alive(token)):
            # You lost!
            Player[token]["status"]=ST_TOWN
            result=get_result(token, False, Battle[token]["world"], Battle[token]["quest_id"])
            del Battle[token]
            return compress(result)


    stdout("Enemies executed")
    return battle_endturn(token, spheres)

# Reload battle will only inform the client again of the battle status
# If in a battle, otherwise it returns: ERR_BAD
# TODO FIXME: Do not default to PID 1. Probably save it as a mask.
# eg. PID + QID as string. So ST_QUEST becomes 11 (PID 1 QID 1)
# FIXME: Token might have changed, maybe we should save to userid instead of token
def reload_battle(token):
    if (Player[token]["status"] < ST_QUEST):
        return ERR_BAD

    try:
        bq=0+int(Battle[token]["quest_id"])
        del bq
        return compress(Battle[token])
    except:
        # FIXME: Detect world
        v1=begin_quest('{"world": "Main", "quest_id": %d, "party_id": 1}' % Player[token]["status"], token, client_side=False)
        stdout("Restarting quest...")
        return v1


#################################################
# Handles CI false positives in a lame way
def pyflakes():
    return allquests