3a363b4f5d83ac0c76ba52b3fab7836e403a6426
[base2-runner.git] / pygame-scroller.py
1 #!/usr/bin/python3
2
3 import sys, os, time, random, pygame
4
5 DEBUG = True
6
7 pygame.init()
8
9 class Channel:
10  # use integers to control volume which avoids float rounding error issues
11  MAX = 100
12  MIN = 0
13  step = 5
14  def __init__(self, volume=1.0, channel_id=0): 
15   self.volume = int(volume*100)
16   self.channel_id = 0
17   if channel_id == -1:
18    self.channel_id = channel_id
19    self.channel = None # flag to show this uses pygame.mixer.music 
20   elif channel_id < pygame.mixer.get_num_channels():
21    self.channel_id = channel_id
22    self.channel = pygame.mixer.Channel(self.channel_id)
23
24  def set_volume(self, new_level):
25   if new_level >= Channel.MIN and new_level <= Channel.MAX:
26    self.volume = new_level
27    if self.channel == None:
28     pygame.mixer.music.set_volume(self.volume/100)
29    else:
30     self.channel.set_volume(self.volume/100)
31    if DEBUG: print("Channel.set_volume(", self.volume, ")")
32  def up(self):
33   if self.volume+self.step <= Channel.MAX:
34    self.set_volume(self.volume + self.step)
35  def down(self):
36   if self.volume-self.step >= Channel.MIN:
37    self.set_volume(self.volume - self.step)
38  def get(self):
39   return self.volume
40  def queue(self, sound):
41   if self.channel != None:
42    self.channel.queue(sound)
43  def get_queue(self):
44   return self.channel.get_queue() if self.channel != None else None
45  def play(self, sound, loops=0, maxtime=0, fade_ms=0):
46   if self.channel != None:
47    # allow 'sound' to be a path string or an object
48    sound = pygame.mixer.Sound(sound)
49    self.channel.play(sound, loops, maxtime, fade_ms)
50   else:
51    pygame.mixer.music.load(sound)
52    pygame.mixer.music.play(loops)
53
54 # container for all game control and configuration items
55 class Config:
56  config = dict()
57  soundtrack = Channel(channel_id=-1)
58  sound_effects = Channel(channel_id=0)
59  def __init__(self, width=0, height=0, title=""):
60   self.config.update({'width':width, 'height':height})
61   self.config.update({'title':title})
62   self.config.update({'sound':1})
63   self.play = False
64   self.resolution = width, height
65   self.debug = DEBUG
66
67 class SeamlessBackground:
68  image_path = None
69  image = None
70  offset_x = 0
71  width = None
72  def __init__(self, filename, offset=0):
73   if os.path.exists(filename):
74    self.image_path = filename
75    self.image = pygame.image.load(self.image_path) #.convert()
76    self.offset = offset
77    self.width = self.image.get_size()[0]
78   if self.image == None:
79    print("Failed to load image", filename)
80
81  def draw(self, screen,  x_pos, step):
82   if DEBUG: print("SeamlessBackground(screen, %d, %d)" % (x_pos, step))
83   if self.image != None:
84    resolution = screen.get_size()
85    if step > 0:
86     x_pos = x_pos + resolution[0] - step
87    
88    bk_x_start = x_pos % self.width
89    bk_rect = pygame.Rect(bk_x_start, 0, abs(step) if step != 0 else resolution[0], resolution[1])
90    patch = pygame.Surface((bk_rect.width, bk_rect.height))
91    patch.blit(self.image, (0, 0), bk_rect)
92    remainder = self.width - bk_x_start
93    if remainder < abs(step):
94     # need more pixels because we're just wrapped around the background image
95     patch.blit(self.image, (4,0), pygame.Rect(0, 0, remainder, resolution[1]))
96     if DEBUG: print("Wrap-around, remainder=%d" % remainder)
97
98    scr_x_dest = resolution[0] - step if step > 0 else 0
99    if DEBUG: print("x_pos=%d, scr_x_dest=%d, bk_x_start=%d, bk_rect=%s" % (x_pos, scr_x_dest, bk_x_start, bk_rect))
100    screen.blit(patch, (scr_x_dest, 0))
101   else:
102    print("No image to draw")
103
104 myGame = Config(1500, 1000)
105 flags = pygame.OPENGL & pygame.DOUBLEBUF
106 depth = 0
107
108 # main loop sleep (100 milliseconds)
109 delay = 0.01
110
111 pygame.display.set_caption("TJ's platform scroller")
112
113 # background colour
114 stepping = 8 # pixels scrolled each flip
115 background_colour = (20, 20, 64)
116 screen = pygame.display.set_mode(myGame.resolution, flags, depth)
117 resolution = screen.get_size()
118 screen.fill(background_colour)
119
120 # background image
121 background_image = SeamlessBackground(os.path.join("resources", "binary.jpg"))
122 background_image.draw(screen, 0, 0)
123 pygame.display.flip()
124
125 # scrolling object
126 blip = pygame.Surface((abs(stepping), abs(stepping)), pygame.HWSURFACE)
127 blip_colour = (128, 128, 128)
128 blip.fill(blip_colour)
129
130 # starting position
131 y = resolution[1] / 2
132
133 if myGame.config['sound'] == 1:
134  myGame.soundtrack.play(os.path.join("resources","Music","Rolemusic_-_Savage_Steel_Fun_Club.mp3"), loops=-1)
135
136 x_pos = 0
137 myGame.play = True
138 while (myGame.play):
139  # update game state
140  x_pos += stepping
141
142  # change colour randomly
143  d_red = random.randrange(-1,2) *8
144  d_green = random.randrange(-1,2) *8
145  d_blue = random.randrange(-1,2) *8
146  # build a new tuple, ensuring all values are valid
147  blip_colour = tuple( b+d if b+d < 256 and b+d >=0 else b for b, d in zip(blip_colour, (d_red, d_green, d_blue)) )
148  blip.fill(blip_colour)
149
150  # change position up or down randomly by one step
151  dy = random.randrange(-1,2) * abs(stepping)
152  if((y + dy) < resolution[1] and (y + dy) >= 0):
153   # screen.fill(background_colour, pygame.Rect(resolution[0] - abs(stepping), y, abs(stepping), abs(stepping) ))
154   y += dy
155
156  # debug info
157  #if myGame.debug:
158   #print(y, blip_colour)
159
160  # redraw the display
161  screen.scroll(-stepping, 0)
162  background_image.draw(screen, x_pos, stepping)
163  screen.blit(blip, (resolution[0] - abs(stepping), y))
164  pygame.display.flip()
165  
166  # manage the frame-rate
167  time.sleep(delay)
168
169  # process events
170  for event in pygame.event.get():
171   if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
172    myGame.play = False
173   if event.type == pygame.KEYDOWN:
174    k = event.key
175    if k == pygame.K_p:
176     time.sleep(10)
177
178  keys_pressed = pygame.key.get_pressed()
179  if sum(keys_pressed):
180   if keys_pressed[pygame.K_6]:
181    # volume down
182    myGame.soundtrack.down()
183   elif keys_pressed[pygame.K_7]:
184    # volume up
185    myGame.soundtrack.up()
186
187 time.sleep(10)
188 pygame.display.quit()
189 exit(0)