Source

hexbattle / hexbattle.py

Full commit
  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
#!/usr/bin/env python
# encoding: utf-8

"""The hexbattle game scene.

Plan:

- Get mouse position - done
- Add hexgrid. hex over which the mouse is gets highlighted. A highlighted hex can simply mean to overlay the grid with a brigther grid element. Just insert it via self.visible.insert(self.visible.index(self.hexgrid)+1), then it will be over the grix, but below everything else. Or split visible into layers. Better still: Make the layers properties, which automatically update self.visible when changed. - partly done, but not yet with hex-graphics (only blobs)
- Add a charakter on the hexgrid. - done
- Beam the Charakter (click, then click new position). - done
- Add a command interface: When a char gets dropped, show hexes around him. - done
- Let two charakters fight (click, then click other char). Who dies disappears  (→ to “died” list) - done, without the died list.
- Add several charakters and cycle through them in each round. All player controlled. - done

- Add basic AI.
    * Guess maximum effect per round up to the units next attack (single step, no complex tactics - done
    * → all attack the weakest point). - done
- Add real game: Scene selects the chars via initiative. User only controls one team. - done
- Add status info for an attack: hit, wound, critical, died.
- Add status info to characters (number of wounds and critical wounds). 
- Add movement on the grid with forbidden fields (different for final position and intermediate: Final not on anyone, intermediate not adjadent to an enemy).
- Highlight all allied units, differently for own group, enemy groups and neutral (None).
- Add hit info: overlay with life time (after which it disappears).

Ideas:

- Simple sparse hex collision ckecking:
    * hexmap = {}
    * hexmap[(thing.x, thing.y): thing]
    * def is_hex_free(x, y):
        return hexmap.has_key((x, y)). 

- Don’t move the unit itself, but a transparent copy of it and then let the unit walk (visualizes correctly, that the movement with the mouse is only decision making and not actual movement. See wesnoth :) ). 

"""

#### Imports ####

from core import core, Sprite, run
from pyglet import image, resource, gl
from pyglet.clock import schedule_interval, schedule_once
from pyglet.window import key
from pyglet.graphics import Batch
from pyglet.text import Label as load_text
from pyglet.sprite import Sprite as pyglet_sprite
from os.path import join
from random import choice
from rpg_1d6.char import Char
from time import time, sleep


# hex functions
from hexgrid import *

# characters and overlays
from hexbattle_units import *
from hexbattle_overlays import *

#### The Hexbattle Scene  ####

### Things needed for the scene

IMAGE_BLOB = join("graphics", "blob.png")
IMAGE_TILE = join("graphics", "wesnoth", "deciduous-fall-tile.png")
IMAGE_TILE_LIST = [join("wesnoth", i) for i in [
    #"sand-rock1.png", "sand-rock2.png", "sand-rock3.png", "sand.png",
    "desert-hills.png", "desert-hills3.png", "desert-mountain-peak2.png", "desert-mountains.png", "desert-tile.png", "desert2.png", "desert4.png", "desert6.png", "desert8.png", 
    "desert-hills2.png", "desert-mountain-peak1.png", "desert-mountain-peak3.png", "desert-oasis.png", "desert.png", "desert3.png", "desert5.png", "desert7.png"
    ]]

IMAGE_TILE_SNOW = [join("graphics", "wesnoth", i) for i in ["deciduous-fall-tile.png",
                                                "deciduous-winter-tile.png"]] # "forested-deciduous-summer-hills-tile.png", "forested-hills-tile.png"

class Presentation:
    def __init__(self, state):
        self.state = state
    def draw(self):
        for i in self.state.visible:
            i.draw()
        for i in self.state.overlay:
            i.draw()

### A "Scene method not implemented" Exception class. 

class MethodNotImplemented(Exception):
    """A warning to display if any necessary scripting function isn't implemented."""
    def __init__(self, func, implementation = None):
        self.func = func
        self.implementation = implementation

    def __str__(self):
        if self.implementation is None:
            return "The method " + str(self.func) + " must be implemented."
        else:
            return "The method " + str(self.func) + " must be implemented." + "\nThe simplest way is to just add the following lines to your class:" + self.implementation

### A base Scene class to inherit from (API definition)

class BaseScene: 
    """A dummy scene - mostly just the Scene API."""
    def __init__(self, *args, **kwds): 
        """Initialize the scene with a core object for basic functions."""
	
        ## Necessary attributes for any scene. 
        #: The core provides basic functions. It gets passed to every scene as first argument. 
        self.core = core
        #: Visible sprites. 
        self.visible = []
        #: Colliding sprites - this seperation allows for invisible colliders. 
        self.colliding = []
        #: Overlay sprites. They are above all other sprites (included for convenience, since most games need an overlay of sorts)
        self.overlay = []
        #: A scene to switch to on the next screen update. 
        self.switch_to_scene = False
    def update(self): 
        """Update the stats of all scene objects. """
        raise MethodNotImplemented(self.update, implementation="""    def update(self):         pass""")


### The Scene itself. 

class UiState(BaseScene): 
    """The Hexbattle Scene.
    
    The Scene has the following roles:
    
    * It creates new things.
    * It lets things coordinate, for example via the scene.hexmap dictionary.
    * It manages the relationship between things, for example via the method scene.enemies_around(thing).
    * It serves events to the things.
    * It manages the information, what the user can click and see. The objects change their visible and clickable states themselves. 
    * Every thing knows the scene (has it as self.scene attribute). 
    
    The Scene has three different states:
    
    * None selected. We can select units or (later) show the command overlay at a given position.
    * Unit selected. We can move the unit and drop it to show the command overlay for that unit.
    * Command overlay shown. We can select actions or dismiss the command overlay. After the overlay disappears, the selected unit gets deselected.
    
    >>> # start the scene with a fake core for testing
    >>> from fungus_core import Core
    >>> c = Core()
    >>> s = UiState(c)
    """
    def __init__(self, *args, **kwds): 
        """Initialize the scene with a core object for basic functions."""
        super(Scene, self).__init__(*args, **kwds)
        
        # set the background color to white
        gl.glClearColor(255, 255, 255, 0)
        
        #: States persistent over frames. 
        self.state = {}
        # Player States: CPU (computer decision), wait (animation), setup (setup of the scene, noninteractive).
        self.state["player"] = "setup"
        
        self.hex_vectors = hex_vectors
        
        # the background
        self.background_batch = Batch()
        self.visible.append(self.background_batch)
        
        self.terrain = []
        
        # a hexgrid
        for i in range(-1, 30):
            for j in range(-15, 15):
                # only the visible ones: 
                if j + 0.5*i < -1 or j + 0.5*i > 15:
                    continue
                x, y = hexgrid_to_coordinate(i, j)
                im = choice(IMAGE_TILE_LIST)
                blob = Hexfield(self, image_path=join("graphics", im), x=x, y=y, batch=self.background_batch)
                self.terrain.append(blob)
	
	self.hexfield = Hexfield(self)
        self.hexfield.show()
        self.blob = Sprite(IMAGE_BLOB, x=212, y=208)
        self.visible.append(self.blob)
        
        #: The possible level positions. 
        self.hexmap = {}
        #: The possible overlay positions.
        self.hexmap_overlay = {}
        
        self.player_team = "trees"
        
        self.chars = []
        for i in range(0):
            x, y = self.find_free_hex(2, 3)
            char = Character(self, self.hexmap)
            char.move_to_hex(x, y)
            char.team = "trees"
            char.attack = 18
            char.show()
            self.chars.append(char)
        
        
        self.num_rats = 10
        self.num_goblins = 5
        
        self.selected = None
        self.command_overlay = CommandOverlay(self)
        self.movement_overlay = MovementOverlay(self)
        self.overlay.append(self.command_overlay)
        self.overlay.append(self.movement_overlay)
        
        self.text_overlay = TextOverlay(self)
        self.text_overlay.show("""
Select a white hex to move
Click the sword to attack
Select the enemy to strike
     
     Kill all enemies.     
  Keep your units together.
  Don't get surrounded.    
     < enter to hide >     """)
        self.overlay.append(self.text_overlay)

    def find_free_hex(self, start_x, start_y):
        """Find the next free hexfield."""
        x, y = start_x, start_y
        vectors = set(self.hex_vectors)
        #: make sure only the new vector parts are tested.
        new_vectors = vectors.copy()
        while True:
            for dx, dy in new_vectors:
                pos = (x+dx, y+dy)
                if not pos in self.hexmap or self.hexmap[pos] is None:
                    return pos
            new_vectors_tmp = set()
            # add vectors around the new vectors new vectors
            for dx, dy in self.hex_vectors:
                for ddx, ddy in new_vectors: 
                    # never check hexes twice
                    pos = (dx+ddx, dy+ddy)
                    if not pos in vectors: 
                        vectors.add(pos)
                        new_vectors_tmp.add(pos)
            new_vectors = new_vectors_tmp
                    

    def setup_step(self, dt=0):
        """setup the level."""
        # TODO: Make loading a character from a file actually work.
        #with open(join("data", "units", "rats.yml")) as f: 
                  #rat_data = f.read()
        # add rats
        if self.num_rats > 0:
            x, y = self.find_free_hex(7, 1)
            char = Character(self, self.hexmap, image_path = join("graphics", "wesnoth", "giant-rat.png"), source = "tag:1w6.org,2010:Rat")#, template_data = rat_data)
            char.move_to_hex(x, y)
            # we are the rats!
            char.team = "rats"
            char.show()
            char.attack = 6
            self.chars.append(char)
            self.num_rats -= 1

        # and add goblins
        if self.num_goblins > 0:
            x, y = self.find_free_hex(6, -2)
            char = Character(self, self.hexmap, image_path = join("graphics", "wesnoth", "impaler.png"), source = "tag:1w6.org,2010:Rat")#, template_data = rat_data)
            char.move_to_hex(x, y)
            # we are the rats!
            char.team = "goblins"
            char.show()
            char.attack = 9
            self.chars.append(char)
            self.num_goblins -= 1
        # pass the control to the AI
        if self.num_goblins <= 0 and self.num_rats <= 0: 
            # sort by initiative
            self.chars_by_initiative = [[c.roll_initiative(), c] for c in self.chars]
            self.chars_by_initiative.sort()
            self.state["player"] = "CPU"
        # if we’re not finished yet, stay in the setup step
        else: schedule_once(self.setup_step, 0.02)
        

    def next_by_initiative(self):
        """Get the char with the highest initiative, reroll if needed."""
        # reroll while all are below 6. 
        while self.chars_by_initiative[-1][0] < 6:
            self.chars_by_initiative = [[ini + c.roll_initiative()/3, c] for ini, c in self.chars_by_initiative]
            self.chars_by_initiative.sort()
        # remove dead or inactive chars
        self.chars_by_initiative = [[ini, c] for ini, c in self.chars_by_initiative if c.active and c.alive]
        # return the char
        return self.chars_by_initiative[-1][1]

    def _initiative_step_current(self, amount=12):
        self.chars_by_initiative[-1][0] -= amount
        self.chars_by_initiative.sort()


    def update(self, dt=0): 
        """Update the stats of all scene objects. 

Don't blit them, though. That's done by the Game itself.

To show something, add it to the self.visible list. 
To add a collider, add it to the self.colliding list. 
To add an overlay sprite, add it to the self.overlay list. 
"""	
        for char in self.chars:
            char.update()
        # do the computer actions. As soon as it’s the players turn, computer_turn() changes the state.
        if self.state["player"] == "setup":
            schedule_once(self.setup_step, 0.01)
            self.state["player"]
        elif self.state["player"] == "CPU":
            self.computer_turn()
        elif self.state["player"] == None: # done
            pass

    def update_interactive_elements(self, dt=0): 
        """Update the interactive elements so they stay fast at all times."""	
        self.blob.update()

    def are_enemies(self, unit, other):
        """Check if the given units are enemies."""
        return unit.team is None or other.team is None or not unit.team == other.team

    def units_around_hex(self, x, y):
        """Return the units around the hexfield."""
        units = []
        for hex_x, hex_y in self.hex_vectors[1:]:
            other = self.hexmap.get((hex_x + x, hex_y + y), None)
            if other is not None: 
                units.append(other)
        return units        
    
    def enemies_around(self, unit):
        """Return the enemies which are on hexes touching the hex of the unit (hexfield).

        @param unit: A Charakter with at least the attributes group, hex_x and hex_y."""
        enemies = []
        for other in self.units_around_hex(unit.hex_x, unit.hex_y): 
            if other is not None and self.are_enemies(unit, other): 
                enemies.append(other)
        return enemies

    def all_enemies_of(self, unit):
        """Get all enemies of the unit, regardless of their position."""
        return [c for c in self.hexmap.values() if self.are_enemies(unit, c)]

    def switch_to_player_turn(self, char):
        """Pass control to the player."""
        self.state["player"] = "player"
        self.selected = char
        # show the movement overlay
        positions = self.selected.movement_targets()
        self.movement_overlay.show(positions)
        # simulate a mouse motion to make sure that the selected is shown at the correct position. TODO: Refactor: This is horrible. Needs to go out of scene.
        x, y = self.core.win._mouse_x, self.core.win._mouse_y
        self.on_mouse_motion(x, y, 0, 0)

    def switch_to_cpu_turn(self, dt=0):
        self.state["player"] = "CPU"

    def wait(self, delay=0.3):
        """wait for delay seconds. Then hand over to CPU turn."""
        self.state["player"] = "wait"
        schedule_once(self.switch_to_cpu_turn, delay)

    def computer_turn(self):
        """Do computer turns until it’s time for the player to act again."""
        # game end condition
        teams = set([c.team for c in self.hexmap.values()])
        if len(teams) == 1:
            print "Game finished."
            print list(teams)[0], "won"
            print
            self.text_overlay.show("Game finished. \n" + list(teams)[0] + " won. \n< Escape to quit >.")
            self.state["player"] = None
            return

        next_char = self.next_by_initiative()
        if next_char.team == self.player_team:
            return self.switch_to_player_turn(next_char)
            
        target = next_char.best_target_hex()
        next_char.move_to_hex(*target)
        next_char.attack_best_target_if_possible()
        self._initiative_step_current()
        # wait a moment so the user can see what happened.
        self.wait(0.1)
        
    def turn_finished_selected(self):
        """The turn of the selected unit is finished. Adjust initiative and get the next unit."""
        self.selected = None
        # unit acted ⇒ reduce init
        self._initiative_step_current()
        # let the computer act
        self.state["player"] = "CPU"

    def pickup_unit(self, unit):
        """Select a unit"""
        self.selected = unit
        self.selected.last_position = (self.selected.hex_x, self.selected.hex_y)

    def drop_selected_unit(self, hex_x, hex_y):
        """drop the selected unit unto a new place."""
        grid_unit = self.hexmap.get((hex_x, hex_y), None)
        if grid_unit is None or grid_unit is self.selected:
            self.movement_overlay.hide()
            self.selected.move_to_hex(hex_x, hex_y)
            actions = self.selected.actions
            self.command_overlay.show(hex_x, hex_y, actions)

    def postpone_selected_move(self):
        """Put the selected unit back to its original position and deselect it."""
        self.selected.move_to_hex(*self.selected.last_position)
        # adjust the initiative: ini - 6
        self.chars_by_initiative[-1][0] -= 6
        self.chars_by_initiative.sort()
        self.selected = self.next_by_initiative()


### Cleaner structure

"""Structure plan:

* Interaction
→ UiState
→ presentation (also needed for the sound later on, so uses its own class)
→ input (on_draw functions and such)

* Logic
→ model (scene.update should partly move into this: model.step)
→ command (callable functions, see results → possible commands). Never used directly (only via the possible actions)
→ results (hexmap, units, actor, possible commands)

Loosely coupled: 
- UiState sends commands and reads results. 
- Presentation just shows the UiState. 
- Input changes the UiState. It needs the state as attribute.
- command changes the _model and returns the results - including new commands to call.
- results are recreated after every command. Available as logic.results as well as returned by any command (to avoid having to issue empty commands).

"""

class Presentation:
    def __init__(self, state):
        self.state = state
    def draw(self):
        for i in self.state.visible:
            i.draw()
        for i in self.state.overlay:
            i.draw()

class Input:
    """Take all User Input."""
    def __init__(self, state):
        self.state = state
    # mouse control
    def on_mouse_motion(self, x, y, dx, dy):
        self.state.blob.x, self.state.blob.y = x, y
        self.state.hexfield.move(x, y)
        if self.state.selected is not None and not self.state.command_overlay.is_visible:
            self.state.selected.move(x, y)
        self.state.hexfield.move(x, y)

    def on_mouse_press(self, x, y, buttons, modifiers): 
        """Forwarded mouse input."""
        hex_pos = coordinate_to_hexgrid(x, y)
        # do nothing, if we hit an overlay field: Hides units below.
        if self.state.command_overlay.is_visible:
            return
    
    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): 
        """Forwarded mouse input."""
        if self.state.selected is not None and not self.state.command_overlay.is_visible:
            self.state.selected.move(x, y)
        self.state.hexfield.move(x, y)

    def on_mouse_release(self, x, y, buttons, modifiers): 
        """Forwarded mouse input."""
        hex_x, hex_y = coordinate_to_hexgrid(x, y)
        # TODO: move if/else into a state-machine in the UiState: Check if the action fits one of the possible commands.
        # if we’re dragging something, we act on that. 
        if self.state.selected is not None:
            # we only move the item and show the commands, if there’s no overlay. 
            if not self.state.command_overlay.is_visible:
                if self.state.movement_overlay.fields.get((hex_x, hex_y), None) is not None: 
                    self.state.drop_selected_unit(hex_x, hex_y)
            # if there’s already an overlay, we check if we resolved an item.
            else:
                action = self.state.command_overlay.on_mouse_release(x, y, buttons, modifiers)
                if action is not None:
                    # global (UI) actions
                    if action == "abort move":
                        self.state.abort_selected_move()
                        self.state.command_overlay.hide()
                        self.state.turn_finished_selected()
                    # actions by the unit
                    actions = self.state.selected.act(action)
                else:
                    actions = None
                # if we get new actions, let them appear around the unit.
                if actions is not None:
                    self.state.command_overlay.show(self.state.selected.hex_x,
                                              self.state.selected.hex_y,
                                              actions)
                else:
                    # unit turn finished
                    self.state.command_overlay.hide()
                    self.state.turn_finished_selected()
        elif not self.state.command_overlay.is_visible and self.state.hexmap.get((hex_x, hex_y), None) is not None:
            pass # no action. All selecting is done by the computer.
        else:
            self.state.command_overlay.on_mouse_release(x, y, buttons, modifiers)

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        """Forwarded mouse input."""
        pass

    def on_mouse_enter(self, x, y):
        """Forwarded mouse input."""
        pass

    def on_mouse_leave(self, x, y):
        """Forwarded mouse input."""
        pass

    def on_key_press(self, symbol, modifiers):
        """Forwarded keyboard input."""
        if symbol == key.ENTER or symbol == key.RETURN:
            self.state.text_overlay.hide()
    
class Interaction:
    def __init__(self):
        self.state = UiState()
        self.input = Input(self.state)
        self.presentation = Presentation(self.state)

def start(dt=0):
    """start the scene"""
    interaction = Interaction()
    scene = interaction.state
    @core.win.event
    def on_draw():
        interaction.presentation.draw()
    schedule_interval(scene.update, 0.02)
    schedule_interval(scene.update_interactive_elements, 0.01)
    core.win.push_handlers(scene)
    
if __name__ == "__main__": 
    # Call this Scene via game.py
    # pass the commandline args
    from sys import argv
    if "--test" in argv: 
        from doctest import testmod
        testmod()
    run(__file__)