Here are the various functions I used for the player and enemy logic.
- After creating a Sprite, I set the clayer to 0 so that more than one player / enemy is created.
- the Sprite must be added to the sprites list
- instead of using class methods, I prefer to use set functions for
the various methods -- loop and hit.
- Enemies are removed when they go off screen.
23:def player_new(g,t,value):
24: g.clayer[t.ty][t.tx] = 0
25: s = tilevid.Sprite(g.images['player'],t.rect)
26: g.sprites.append(s)
27: s.loop = player_loop
28:
29:def player_loop(g,s):
30: s.rect.x += SPEED
31:
32: keys = pygame.key.get_pressed()
33: dx,dy = 0,0
34: if keys[K_UP]: dy-=1
35: if keys[K_DOWN]: dy+=1
36: if keys[K_LEFT]: dx-=1
37: if keys[K_RIGHT]: dx+=1
38: s.rect.x += dx*5
39: s.rect.y += dy*5
40: s.rect.clamp_ip(g.view)
41:
42:def enemy_new(g,t,value):
43: g.clayer[t.ty][t.tx] = 0
44: s = tilevid.Sprite(g.images['enemy'],t.rect)
45: g.sprites.append(s)
46: s.loop = enemy_loop
47:
48:def enemy_loop(g,s):
49: if s.rect.right < g.view.left:
50: g.sprites.remove(s)
Here I initialize the image data. The columns are (name,file_name,shape)
54:idata = [
55: ('player','player.tga',(4,4,24,24)),
56: ('enemy','enemy.tga',(4,4,24,24)),
57: ('shot','shot.tga',(1,2,6,4)),
58: ]
Here I initialize the code data. The columns are (function, config).
62:cdata = {
63: 1:(player_new,None),
64: 2:(enemy_new,None),
65: 3:(enemy_new,None),
66: 4:(enemy_new,None),
67: }
In init(), loading in the sprite images.
81: g.load_images(idata)
In init(), running the codes for the initial screen.
86: g.run_codes(cdata,(0,0,25,17))
In run(), each frame I make sure to run the codes that are on the far
right of the screen.
109: g.run_codes(cdata,(g.view.right/TW,0,1,17))