def loop(self): while self._running: self.event_timer.start() for event in pygame.event.get(): self.on_event(event) self.event_timer.clock() if not self.paused: self.physics_timer.start() self.update_platforms() self.gravity() self.collisions() self.physics_timer.clock() self.total_distance -= self.character.y_velocity if self.max_distance < self.total_distance: self.max_distance = self.total_distance if android: self.character.x_velocity = android.accelerometer_reading()[0] self.character.x_velocity *= -2 self.clock.tick(self.fps) self.render() if not android: self.save_scores() pygame.quit()
def __init__(self): android.accelerometer_enable(True) x, y, z = android.accelerometer_reading() self._samples = [] self._init_time = time.time() self._normal = None
def accelerometer(self): accelerometer = android.accelerometer_reading() y = float(accelerometer[0]) x = float (accelerometer[1]) #the 6 keeps it so you can hold the phone at a comfortable angle dx = x/1 dy = (y/1) - 6 return (dx,dy)
def __movingPlayerAndroid(self): if (android): accelerometer = android.accelerometer_reading() if (accelerometer[1] < -3 and self.player.jumping is False): self.player.velocity_x = -PLAYER_VX0 elif (accelerometer[1] > 3 and self.player.jumping is False): self.player.velocity_x = PLAYER_VX0 else: if (self.player.jumping is False): self.player.velocity_x = 0
def update(self): # Take a new sample. x, y, z = android.accelerometer_reading() ts = time.time() self._samples.append(Sample(ts, x, y, z)) while self._samples and ts - self._samples[0].ts > self.running_seconds: del self._samples[0] # If it's been long enough since sensor initialization, take a normal # reading as a first guess. if not self._normal and 1 > time.time() - self._init_time: self._normal = Sample(time.time(), x, y, z) # Shake detection. d = Sample(0, 0, 0, 0) ad = Sample(0, 0, 0, 0) n = self._normal prevts = ts rsamples = [] for s in reversed(self._samples): rsamples.append(s.r) a = Sample(0, s.x - n.x, s.y - n.y, s.z - n.z) dt = prevts - s.ts dist = Sample(0, dt * a.x, dt * a.y, dt * a.z) prevts = s.ts d = Sample(d.ts + dt, d.x + dist.x, d.y + dist.y, d.z + dist.z) ad = Sample(ad.ts + dt, ad.x + abs(dist.x), ad.y + abs(dist.y), ad.y + abs(dist.z)) if ad.ts > self.threshold_time: if ad.r > self.threshold_distance: self.postShakeEvent(d, ad) break print "new:", s, "r:", s.r, " overall:", d, "r:", d.r, " absolute:", ad, "r:", ad.r, " normal: ", self._normal, "r:", self._normal.r # Update the gravity vector. if rsamples: rnorm = reduce(lambda x, y: x*y, rsamples) ** (1.0/len(rsamples)) if rnorm != 0: snorm = Sample(0, 0, 0, 0) sn = 0 for s in self._samples: if abs(1 - s.r / rnorm) < self.normalization_threshold_ratio: sn += 1 snorm = Sample(0, snorm.x + s.x, snorm.y + s.y, snorm.z + s.z) if sn > 0: snorm = Sample(0, snorm.x / sn, snorm.y / sn, snorm.z / sn) self._normal = snorm
def play(self): while True: self.clock.tick(1000/FPS) # Android-specific: if android: if android.check_pause(): android.wait_for_resume() for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: pass elif event.key == pygame.K_RIGHT: pass elif event.key == pygame.K_ESCAPE: return True if android: a = android.accelerometer_reading() #self.debug_text = "%f" % a[0] ## did the ball hit a brick or paddle? for ball in self.balls: hit = pygame.sprite.spritecollide(ball, self.obstacles, False) if hit: if hit[0].type == "paddle": ball.vy = -ball.vy elif hit[0].type == "brick": ball.vy = -ball.vy self.points = self.points + 10 self.obstacles.remove(hit) self.splat.play() self.count = self.count - 1 if self.count <= 0: ## level complete self.level = self.level + 1 self.init() ## did the ball hit the top of the screen? if ball.rect.y < self.border: ball.vy = ball.vy * 1.5 ball.vy = -ball.vy ## did the ball hit the bottom of the screen? if ball.rect.y > self.screen_height: self.balls = [] return True self.score_text = self.font.render("Score: " + str(self.points), 1, (255,255,255)) self.animate()
def check_dir_acc(): p=android.accelerometer_reading() x=p[0] y=p[1] if x>0 and abs(x)>abs(y): return "left" elif x<0 and abs(x)>abs(y): return "right" elif y>0 and abs(x)<abs(y): return "down" elif y<0 and abs(x)<abs(y): return "up" else: return ""
def main(): pygame.init() if android: android.init() # Set the screen size. screen = pygame.display.set_mode((480, 800)) # Map the back button to the escape key. if android: android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) android.accelerometer_enable(True) # Use a timer to control FPS. pygame.time.set_timer(TIMEREVENT, 1000 / FPS) font = pygame.font.Font("FreeSans.ttf", 30) def text(s, x, y): surf = font.render(s, True, (200, 200, 200, 255)) screen.blit(surf, (x, y)) while True: ev = pygame.event.wait() if android.check_pause(): android.wait_for_resume() # Draw the screen based on the timer. if ev.type == TIMEREVENT: x, y, z = android.accelerometer_reading() screen.fill((0, 0, 0, 255)) text("X: %f" % x, 10, 10) text("Y: %f" % y, 10, 50) text("Z: %f" % z, 10, 90) pygame.display.flip() # When the user hits back, ESCAPE is sent. Handle it and end # the game. elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE: break
def detect_motion(self, *args): if self.enabled: accel = android.accelerometer_reading() if self.last: diff = sum(accel) - sum(self.last) history_size = 10 movement_threshold = 5 if len(self.history) == history_size: self.history.popleft() self.history.append(abs(diff)) if len(self.history) == history_size: rolling_average = sum(self.history) / len(self.history) if rolling_average > movement_threshold: self.lock(2) self.history.clear() self.shake_callback(rolling_average) self.last = accel
def play(self): while True: self.clock.tick(1000/FPS) # Android-specific: if android: if android.check_pause(): android.wait_for_resume() for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: pass elif event.key == pygame.K_RIGHT: pass elif event.key == pygame.K_ESCAPE: return True if android: a = android.accelerometer_reading() #self.debug_text = "%f" % a[0] x = a[0] if abs(x) < 1: self.speed = self.skier.set_angle(0) elif x > 3: self.speed = self.skier.set_angle(-2) elif x > 1: self.speed = self.skier.set_angle(-1) elif x < -3: self.speed = self.skier.set_angle(2) elif x < -1: self.speed = self.skier.set_angle(1) self.density = 1 + self.points/100 self.score_text = self.font.render("Score: " + str(self.points), 1, (255,255,255)) self.animate()
BLUE = ((85, 191, 223)) speed = 4 speed_2 = 6 x = 770 y = 360 windowSurface = pygame.display.set_mode((1280, 770)) player_circle = pygame.image.load("img/final_circle.png") control_circle = pygame.draw.circle(windowSurface, WHITE, (1080, 550), 100, 4) while True: if android: if android.check_pause(): android.wait_for_resume() velocity_reading = android.accelerometer_reading() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() mouse_pos = pygame.mouse.get_pos() ### x-axis acceleration if velocity_reading[1] > 1 and x < 1280: x = x + speed
def main(): if android: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) android.accelerometer_enable(True) carretera=Carretera() speed=0. coches=[] bichos=[] bichos.append(Objeto()) bichos[-1].pos=[-150.,15] bichos[-1].clase=1 bichos[-1].carga_imagen() bichos.append(Objeto()) bichos[-1].pos=[-150.,35] bichos[-1].clase=1 bichos[-1].carga_imagen() bichos.append(Objeto()) bichos[-1].pos=[150.,50] bichos[-1].clase=1 bichos[-1].carga_imagen() pygame.display.update() stage=1 TIMEREVENT = pygame.USEREVENT checkpoint=3000 FPS=25 t=0 l=0 dt=0.01 pos=0 vel=0 t0=time.time() t00=time.time()+60 last_coche=0 lives=3 dcoches=4 cracks=0 dentro=True if mixer: mixer.init() mixer.music.load('sound/blues.wav') mixer.music.play() while dentro: if android: if mixer.music_channel.get_busy()==False: mixer.music.play() else: if mixer.music.get_busy()==False: mixer.music.play() for ev in pygame.event.get(): if pygame.mouse.get_pressed()[0]: speed*=0.95 elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE: dentro=False t+=dt l+=dt*speed curva=math.cos(t)*0.75*math.sin(t/2+3)*math.cos(t/10+12) carretera.curva=curva n=0 for i in bichos: i.vel=speed i.pos[1]+=speed*i.pos[1]*dt+dt i.curva=curva if i.pos[1] > 100: bichos.pop(n) n+=1 n=0 for i in coches: i.vel=speed i.pos[1]+=speed*i.pos[1]*dt+dt i.curva=curva if i.pos[1] > 85 and i.pos[1] < 95: #print i.pos[0]-pos if i.clase==0: if abs(i.pos[0]-pos) < 30: if android: android.vibrate(2) pygame.time.delay(2000) lives-=1 cracks+=1 if lives < 0: dentro=False speed*=0 coches.pop(n) elif i.clase==1: if abs(i.pos[0]-pos) < 20: if lives < 3: lives+=1 if cracks > 0: cracks-=1 if android: android.vibrate(1) speed*=0 coches.pop(n) if i.pos[1] > 120: coches.pop(n) n+=1 if random.random() < 0.05: #print 'arbol' bichos.append(Objeto()) if random.random() < 0.5: bichos[-1].pos=[150.,0.1] else: bichos[-1].pos=[-150.,0.1] bichos[-1].radius=800 bichos[-1].clase=1 bichos[-1].carga_imagen() if random.random() < 0.1 and t-last_coche > dcoches: coches.append(Coche()) coches[-1].radius=100 coches[-1].curva=curva if random.random() < 0.05: coches[-1].clase=1 coches[-1].pos=[random.random()*150-75,0.1] coches[-1].carga_imagen() last_coche=t*1 speed+=dt if pos > 100 or pos < -100: speed*=0.9 if android: android.vibrate(0.1) if pos > 120: pos=120 speed=0. elif pos < -120: pos = -120 speed=0. if speed > 5: speed=5. if android: accels=android.accelerometer_reading() dpx=accels[1]*100 else: dp=pygame.mouse.get_pos() dpx=(dp[0]-400)*2 pos+=dt*curva*300*speed pos+=dpx*dt alpha=dpx/2*dt carretera.draw() screen.blit(sky,(0,0)) #screen.blit(sky2,(int(-150-curva*150),0)) for i in range(len(bichos)): bichos[-1-i].draw() for i in range(len(coches)): coches[-1-i].draw() motor=pygame.transform.rotate(moto,-int(alpha)*10) #(w,h)=motor.get_size() xn,yn,f=coordenadas((pos,90),curva) screen.blit(motor,(int(xn-w/2),int(yn-h))) while 1/(time.time()-t0) > 30: time.sleep(0.01) #display_text(screen,': '+str(int(speed*20))) if (t00-time.time()) < 0: lives-=1 if android: android.vibrate(1) t00+=60 if lives < 0: dentro=False elif l*100 < checkpoint*stage-500 and l*100 > checkpoint*stage-520: bichos.append(Objeto()) bichos[-1].pos=[0.,0.1] bichos[-1].radius=800 bichos[-1].clase=0 bichos[-1].carga_imagen() elif l*100 > checkpoint*stage: stage+=1 if checkpoint < 6000: checkpoint+=500 t00+=60 dcoches*=0.75 panel(screen,panel_image,crack1_image,crack2_image,crack3_image,font,int(checkpoint*stage-l*100),int(t00-time.time()),speed*20,lives,cracks) pygame.display.update() t0=time.time() screen.fill((150,255,150)) ending=pygame.image.load('images/ending.png').convert_alpha() screen.blit(ending,(0,0)) pygame.display.flip() pygame.time.delay(5000)
newBullet = False bulletDelay = 10 bulletFirst = True bullet_group = pygame.sprite.Group() mouse_pos = pygame.mouse.get_pos() # flock predator = False f = flock.Flock(30, 100., 500) while True: if android: if android.check_pause(): android.wait_for_resume() accel_reading = android.accelerometer_reading() for event in pygame.event.get(): if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() elif event.type == pygame.MOUSEBUTTONUP: mouse_pos = (0,0) if android: if accel_reading[1] > 1 or accel_reading[1] < -1 or accel_reading[0] > 6 or accel_reading[0] < 4: if accel_reading[1] > .8:
def update(self): if ANDROID: x,y,z = android.accelerometer_reading() self.world.y_gravity = x/10 self.world.x_gravity = y/10 self.world.step()
def startLevel(self): """Loads a level and begins gameplay.""" # Reset Chompy self.chomp.reset() # Screen size size = self.screen.get_size() # Stop all sounds self.sound.stopAllSfx(1, 1) # Load Level if self.level.packMaps and self.level.current_map > len(self.level.packMaps) - 1: self.menu.dialog.setMessageBox(size, "You've completed " + self.level.parser.get("pack", "name") + "!", "Complete!", [['OK',self.menu.dialog.closeMessageBox]] ) self.state = 2 return 0 try: self.level.loadLevel(self.map_file[0], self.map_file[1]) self.level.state = 0 except: traceback.print_exc(5, error_log) self.menu.dialog.setMessageBox(size, "There was an error with loading this map.", "Error", [['OK',self.menu.dialog.closeMessageBox]] ) self.state = 2 return 0 # Resize Chompy chomp_size = size[0] if size[1] > chomp_size: chomp_size = screensize[1] self.chomp.resize( math.ceil(chomp_size / 16) ) # Place character in level pos = self.level.parser.get(self.level.packMaps[self.level.current_map],"startpos").split(",") self.chomp.pos[0] = int(pos[0]) * self.level.tilesize[0] self.chomp.pos[1] = int(pos[1]) * self.level.tilesize[1] self.chomp.colliderect.x = self.chomp.pos[0] self.chomp.colliderect.y = self.chomp.pos[1] scroll = [(size[0] / 2) - self.chomp.pos[0] , (size[1] / 2) - self.chomp.pos[1] ] # If player is moving... move = 0 # Level time start_time = pygame.time.get_ticks() time = 0 self.hud.ready_time = pygame.time.get_ticks() # Load skills into the Hud self.hud.loadSkills(size, self.level.parser.get(self.level.packMaps[self.level.current_map],"skills").split(",")) # Load Dialog box if self.level.displayDialog: self.dlogbox.setMessageBox(size, self.level.parser.get(self.level.packMaps[self.level.current_map],"desc"), self.level.parser.get(self.level.packMaps[self.level.current_map],"name"), [['Play!',self.dlogbox.closeMessageBox],['Map Select', self.setState]] ) self.level.displayDialog = 0 no_dialog = 0 else: transition_status = 0 no_dialog = 1 pygame.event.set_allowed((pygame.KEYDOWN, pygame.QUIT, pygame.MOUSEMOTION, pygame.VIDEORESIZE, pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP)) # -------- Main Program Loop ----------- while self.state == 0: # Set frame rate to 30. self.clock.tick(30) # Plus one frame self.frames += 1 events = pygame.event.get() for event in events: # User did something if event.type == pygame.QUIT: # If user clicked close self.setState(-1) # Set game state to -1(Quit) elif event.type == pygame.MOUSEBUTTONDOWN: move = (event.pos[0] - (size[0] / 2.0)) / (size[0] / 8.0) elif event.type == pygame.MOUSEBUTTONUP: move = 0 elif event.type == pygame.MOUSEMOTION and move: move = (event.pos[0] - (size[0] / 2.0)) / (size[0] / 8.0) elif event.type == pygame.KEYDOWN: # Move with keyboard if event.key == pygame.K_LEFT: move = -2.5 elif event.key == pygame.K_RIGHT: move = 2.5 # Toogle Fullscreen elif event.key == 292: pygame.display.toggle_fullscreen() # Retry Level elif event.key == pygame.K_TAB: self.level.state = 2 self.levelTransition() elif event.type == pygame.KEYUP: # Move with keyboard if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: move = 0 elif event.type == pygame.VIDEORESIZE: self.screen=pygame.display.set_mode(event.size, pygame.RESIZABLE) size = event.size self.hud.loadSkills(size) new_tile_size = size[0] if size[1] > new_tile_size: new_tile_size = screensize[1] self.chomp.resize( math.ceil(new_tile_size / 16) ) self.level.resizeTiles( math.ceil(new_tile_size / 16)) # Android events if android: if android.check_pause(): android.wait_for_resume() accel = android.accelerometer_reading() if abs(accel[1]) > .5: move = accel[1] * 1.4 lscroll = scroll scroll = [(size[0] / 2) - self.chomp.pos[0] , (size[1] / 2) - self.chomp.pos[1] ] # Lock scrolling to edge of level if scroll[1] < size[1] - (self.level.mapheight * self.level.tilesize[1]): scroll[1] = size[1] - (self.level.mapheight * self.level.tilesize[1]) if scroll[0] > 0: scroll[0] = 0 if scroll[0] < size[0] - (self.level.mapwidth * self.level.tilesize[0]): scroll[0] = size[0] - (self.level.mapwidth * self.level.tilesize[0]) # Draw the background self.level.drawBackground(self.screen, scroll, size) # Draw tiles and handle tile collision with player self.level.updateTiles(self.screen, scroll, size, self.chomp, self.sound) # Update time time = pygame.time.get_ticks() - start_time # Android Sound Loops if android: self.sound.update() # If a dialog box isn't up. dbox = self.dlogbox.drawBox(size, events) if not dbox: # If the game has displayed the "Get Ready!" - "Go!" message. if not transition_status or no_dialog: getready = self.hud.getReady(size) else: getready = 0 if not getready: # Update Chomp Movement...only when level is playable(i.e. not beaten or lost) if not self.level.state: self.chomp.update(scroll, move, size) # Draw Sprites self.all_sprites_list.draw(self.screen) # If Chompy can't move it's game over... if not self.chomp.moveok and self.chomp.speed == 0: if self.chomp.stopclock < 0: self.chomp.stopclock = 30 else: self.chomp.stopclock = -1 if self.chomp.stopclock == 0: self.level.state = 2 # If Chompy falls below the level... if self.chomp.colliderect.y > self.level.mapheight * self.level.tilesize[1]: self.level.state = 2 # Game over level state... if self.level.state == 2: self.chomp.speed = .1 self.chomp.falling = .1 self.chomp.moveok = 1 if self.transition.type == 0: self.dlogbox.setMessageBox(size,"Chompy didn't make it...", "Oh No!!", [['Retry',self.levelTransition],['Map Select', self.setState]] ) # Update Hud self.hud.update(size,time) self.hud.checkSkillActivation(events, size, self.chomp) # Check level state if self.level.state == 1: self.chomp.speed = 0 self.chomp.falling = 0 if self.transition.type == 0: gametime = round( time / 1000.0,2 ) aranktime = float(self.level.parser.get(self.level.packMaps[self.level.current_map], "arank")) # Save Progress progress = self.save.getInt(self.level.maphash, "progress") besttime = self.save.getFloat(self.level.maphash, self.level.packMaps[self.level.current_map] ) if not besttime: besttime = 9999.99 if progress < self.level.current_map + 1: self.save.set(self.level.maphash, "progress", self.level.current_map + 1) if besttime and gametime < besttime: self.save.set(self.level.maphash, self.level.packMaps[self.level.current_map], gametime) newrecord = " - New Record!" else: newrecord = "" self.save.parser.read(app_path + "game.sav") if aranktime and gametime <= aranktime: self.dlogbox.setMessageBox(size,"A+! - TIME: " + str(round( time / 1000.0,2 )) + newrecord , "Pwned!!!", [['Retry',self.levelTransition],['Next Level',self.nextLevel]] ) else: self.dlogbox.setMessageBox(size,"TIME: " + str(round( time / 1000.0,2 )) + newrecord , "Winner!", [['Retry',self.levelTransition],['Next Level',self.nextLevel]] ) # If get ready message still up reset timers. else: start_time = pygame.time.get_ticks() time = 0 # If closed by clicking X return to map select. elif dbox == -1: self.setState(2) # Reset time as long as dialog box is up else: start_time = pygame.time.get_ticks() time = 0 self.hud.ready_time = pygame.time.get_ticks() # As long as dialog box is up reset "Get Ready!" - "Go!" message. # If there is a transition playing transition_status = self.transition.update(self.screen) if transition_status: if transition_status < 1: self.transition.type = 0 if transition_status and transition_status < 2 and self.level.state: self.setState(3) # If the back button was clicked in the hud... if self.hud.doMapSelect: self.setState(2) self.hud.doMapSelect = 0 # Go ahead and update the screen with what we've drawn. pygame.display.flip()
def main(): if android: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) android.accelerometer_enable(True) carretera = Carretera() speed = 0. coches = [] bichos = [] bichos.append(Objeto()) bichos[-1].pos = [-150., 15] bichos[-1].clase = 1 bichos[-1].carga_imagen() bichos.append(Objeto()) bichos[-1].pos = [-150., 35] bichos[-1].clase = 1 bichos[-1].carga_imagen() bichos.append(Objeto()) bichos[-1].pos = [150., 50] bichos[-1].clase = 1 bichos[-1].carga_imagen() pygame.display.update() stage = 1 TIMEREVENT = pygame.USEREVENT checkpoint = 3000 FPS = 25 t = 0 l = 0 dt = 0.01 pos = 0 vel = 0 t0 = time.time() t00 = time.time() + 60 last_coche = 0 lives = 3 dcoches = 4 cracks = 0 dentro = True if mixer: mixer.init() mixer.music.load('sound/blues.wav') mixer.music.play() while dentro: if android: if mixer.music_channel.get_busy() == False: mixer.music.play() else: if mixer.music.get_busy() == False: mixer.music.play() for ev in pygame.event.get(): if pygame.mouse.get_pressed()[0]: speed *= 0.95 elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE: dentro = False t += dt l += dt * speed curva = math.cos(t) * 0.75 * math.sin(t / 2 + 3) * math.cos(t / 10 + 12) carretera.curva = curva n = 0 for i in bichos: i.vel = speed i.pos[1] += speed * i.pos[1] * dt + dt i.curva = curva if i.pos[1] > 100: bichos.pop(n) n += 1 n = 0 for i in coches: i.vel = speed i.pos[1] += speed * i.pos[1] * dt + dt i.curva = curva if i.pos[1] > 85 and i.pos[1] < 95: #print i.pos[0]-pos if i.clase == 0: if abs(i.pos[0] - pos) < 30: if android: android.vibrate(2) pygame.time.delay(2000) lives -= 1 cracks += 1 if lives < 0: dentro = False speed *= 0 coches.pop(n) elif i.clase == 1: if abs(i.pos[0] - pos) < 20: if lives < 3: lives += 1 if cracks > 0: cracks -= 1 if android: android.vibrate(1) speed *= 0 coches.pop(n) if i.pos[1] > 120: coches.pop(n) n += 1 if random.random() < 0.05: #print 'arbol' bichos.append(Objeto()) if random.random() < 0.5: bichos[-1].pos = [150., 0.1] else: bichos[-1].pos = [-150., 0.1] bichos[-1].radius = 800 bichos[-1].clase = 1 bichos[-1].carga_imagen() if random.random() < 0.1 and t - last_coche > dcoches: coches.append(Coche()) coches[-1].radius = 100 coches[-1].curva = curva if random.random() < 0.05: coches[-1].clase = 1 coches[-1].pos = [random.random() * 150 - 75, 0.1] coches[-1].carga_imagen() last_coche = t * 1 speed += dt if pos > 100 or pos < -100: speed *= 0.9 if android: android.vibrate(0.1) if pos > 120: pos = 120 speed = 0. elif pos < -120: pos = -120 speed = 0. if speed > 5: speed = 5. if android: accels = android.accelerometer_reading() dpx = accels[1] * 100 else: dp = pygame.mouse.get_pos() dpx = (dp[0] - 400) * 2 pos += dt * curva * 300 * speed pos += dpx * dt alpha = dpx / 2 * dt carretera.draw() screen.blit(sky, (0, 0)) #screen.blit(sky2,(int(-150-curva*150),0)) for i in range(len(bichos)): bichos[-1 - i].draw() for i in range(len(coches)): coches[-1 - i].draw() motor = pygame.transform.rotate(moto, -int(alpha) * 10) #(w,h)=motor.get_size() xn, yn, f = coordenadas((pos, 90), curva) screen.blit(motor, (int(xn - w / 2), int(yn - h))) while 1 / (time.time() - t0) > 30: time.sleep(0.01) #display_text(screen,': '+str(int(speed*20))) if (t00 - time.time()) < 0: lives -= 1 if android: android.vibrate(1) t00 += 60 if lives < 0: dentro = False elif l * 100 < checkpoint * stage - 500 and l * 100 > checkpoint * stage - 520: bichos.append(Objeto()) bichos[-1].pos = [0., 0.1] bichos[-1].radius = 800 bichos[-1].clase = 0 bichos[-1].carga_imagen() elif l * 100 > checkpoint * stage: stage += 1 if checkpoint < 6000: checkpoint += 500 t00 += 60 dcoches *= 0.75 panel(screen, panel_image, crack1_image, crack2_image, crack3_image, font, int(checkpoint * stage - l * 100), int(t00 - time.time()), speed * 20, lives, cracks) pygame.display.update() t0 = time.time() screen.fill((150, 255, 150)) ending = pygame.image.load('images/ending.png').convert_alpha() screen.blit(ending, (0, 0)) pygame.display.flip() pygame.time.delay(5000)
def get_tiling(): x, y, z = android.accelerometer_reading() xrel = y/10 if xrel > 0.2: return 1 elif xrel < 0.2: return -1 else: return 0
def game(screen): '''main function that runs the game''' pygame.init() window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Sky High') screen = pygame.display.get_surface() clock = pygame.time.Clock() scroll_speed = 3 sky_image = "assets/sky.gif" balloon0 = pygame.transform.scale (load_image('assets/balloon.png'), (132, 200)) balloon1 = pygame.transform.scale (load_image('assets/balloon1.png'), (132, 200)) balloon2 = pygame.transform.scale (load_image('assets/balloon2.png'), (132, 200)) balloonflashing = pygame.transform.scale (load_image('assets/balloonflash.png'), (132, 200)) font = pygame.font.Font("BRLNSDB.TTF", 30) try: mixer.music.load("assets/Scores.ogg") hit = mixer.Sound("assets/hit.ogg") star = mixer.Sound("assets/star.ogg") mixer.music.play(-1) except pygame.error: print "Couldn't find file." balloon_speed = 6 moveRate = 2 score = 0 sky = Background(screen, scroll_speed, sky_image) # Map the back button to the escape key. if android: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) android.accelerometer_enable(True) # Use a timer to control FPS. pygame.time.set_timer(TIMEREVENT, 1000) pygame.time.set_timer(USEREVENT + 1, 3000) pygame.time.set_timer(USEREVENT + 2, 2000) pygame.time.set_timer(USEREVENT + 3, 4000) pygame.time.set_timer(USEREVENT + 4, 5000) pygame.time.set_timer(USEREVENT + 5, 8000) pygame.key.set_repeat(FPS, FPS) # set key repeat on lives = 10 balloon = Balloon(screen, SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT, 0, balloon_speed, "assets/balloon.png", lives) city = Enemy(screen,0, SCREEN_HEIGHT-800, 0, -3, "assets/cityskyline.png",(800,480),1,1) city.image = load_image("assets/cityskyline.png") city.rect = city.image.get_rect() airplanes = pygame.sprite.Group() birds = pygame.sprite.Group() missiles = pygame.sprite.Group() powerups = pygame.sprite.Group() spawn_pt = range(-200, -100) + range(SCREEN_WIDTH, SCREEN_WIDTH + 100) elapsed_time = 0 timer = 0 justcollided = 0 imagechanged = False while True: #game loop time_passed = clock.tick(FPS) elapsed_time += 1 text = font.render("Height: " + str(score), 1, (120, 40, 80)) #render score lives_txt = font.render("Balloon Strength: " + str(lives)+ "/10" , 1, (85, 0, 50)) timer -= 1 justcollided -= 1 if android: balloon_move = android.accelerometer_reading() if balloon.x >= 0 and balloon.x <= SCREEN_WIDTH - balloon.image_w: balloon.x = balloon.x - (balloon_move[0] * moveRate) elif balloon.x <= 0: balloon.x += 1 else: balloon.x -= 1 if balloon.rect.bottom <= SCREEN_HEIGHT and balloon.y >= (SCREEN_HEIGHT - balloon.image_h)/3: balloon.y = balloon.y + ((balloon_move[1] - 5) * moveRate) elif balloon.rect.bottom >= SCREEN_HEIGHT: balloon.y -= 1 else: balloon.y += 1 if android.check_pause(): android.wait_for_resume() #Randomly choose a spawn point from the list init_x = choice(spawn_pt) if init_x < SCREEN_WIDTH/2: enemy_image = "assets/plane-right.gif" else: enemy_image = "assets/plane-left.gif" for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() elif event.key == pygame.K_RIGHT: if balloon.x <= SCREEN_WIDTH - balloon.image_w: balloon.x += balloon_speed elif event.key == pygame.K_LEFT: if balloon.x >= 0: balloon.x -= balloon_speed elif event.key == pygame.K_DOWN: if balloon.y <= SCREEN_HEIGHT - balloon.image_h: balloon.y += balloon_speed elif event.key == pygame.K_UP: if balloon.y >= 0: balloon.y -= balloon_speed elif event.type == TIMEREVENT: score += 1 elif event.type == USEREVENT + 1 and score>=2 and score<=20: airplanes.add(Enemy(screen, init_x, randint(-50, 200), randint(1, 5), 3, enemy_image, (100, 50), 1, 1)) elif event.type == USEREVENT + 2 and score>=50: airplanes.add(Enemy(screen, init_x, randint(-50, 200), randint(1, 5), randint(3, 5), enemy_image, (100, 50), 1, 1)) elif event.type == USEREVENT + 3 and score>=5: birds.add(Enemy(screen, init_x, randint(-50, SCREEN_HEIGHT + 50), randint(2,4), 0, "assets/UFO.png", (100, 80), 1, 1)) if score >=20 and score<40: missiles.add(Enemy(screen, randint(0, SCREEN_WIDTH), SCREEN_HEIGHT, 0, randint(-8, -3), "assets/missile.png", (40, 150), 1, 1)) elif event.type == USEREVENT + 4 and score>=50: missiles.add(Enemy(screen, randint(0, SCREEN_WIDTH), SCREEN_HEIGHT, 0, randint(-8, -3), "assets/missile.png", (40, 150), 1, 1)) elif event.type == USEREVENT + 5 and score>=30: powerups.add(Enemy(screen, randint(100, SCREEN_WIDTH-100), 0, 0, 3, "assets/gold-star.gif", (60, 60), 1, 1)) if timer <= 20 and timer >= 0: sky.dy = 6 elif timer > 45: sky.dy = -6 else: sky.dy = 3 sky.update(score) sky.draw() city.update2(score,SCREEN_HEIGHT) city.draw() balloon.update(lives, balloon0, balloon1, balloon2, justcollided) balloon.draw() if balloon.y <= SCREEN_HEIGHT / 3: balloon.dy = 0 sky.scrolling = True if justcollided <= 0: balloon.update(lives, balloon0, balloon1, balloon2, justcollided) for enemy in airplanes: if pygame.sprite.collide_mask(enemy, balloon): # ADD GAME OVER SCREEN HERE if android: android.vibrate(0.3) if lives <= 0: return score enemy.dy = 20 timer = 80 if score >= 10: score -= 10 else: score = 1 justcollided = 20 lives -= 1 hit.play() for bird in birds: if bird.dy != 20: bird.dy = 6*cos(0.1*elapsed_time) + 1 if pygame.sprite.collide_mask(bird, balloon): # ADD GAME OVER SCREEN HERE if android: android.vibrate(0.3) if lives <= 0: return score bird.dy = 20 timer = 70 if score >= 5: score -= 5 else: score = 1 justcollided = 20 lives -= 1 hit.play() for missile in missiles: if pygame.sprite.collide_mask(missile, balloon): # ADD GAME OVER SCREEN HERE if android: android.vibrate(0.1) missile.dy = 20 if lives <= 0: return score timer = 80 if score >= 15: score -= 15 else: score = 1 justcollided = 20 lives -= 1 hit.play() for powerup in powerups: if pygame.sprite.collide_mask(powerup, balloon): timer = 25 powerup.kill() score += 10 star.play() else: balloon.image = balloonflashing imagechanged = True airplanes.update() airplanes.draw(screen) birds.update() birds.draw(screen) missiles.update() missiles.draw(screen) powerups.update() powerups.draw(screen) screen.blit(text, (0, SCREEN_HEIGHT - 30)) screen.blit(lives_txt, (0, 0)) pygame.display.flip()