Example #1
0
 def __init__(self):
   android.accelerometer_enable(True)
   x, y, z = android.accelerometer_reading()
   self._samples = []
   self._init_time = time.time()
   
   self._normal = None
Example #2
0
	def __init__(self):		
		self.loopFlag = True
				
		#Display
		if not ANDROID:
			os.environ['SDL_VIDEO_CENTERED'] = '1'		
		
		pygame.init()	
		if ANDROID:
			android.init()
			android.accelerometer_enable(True)
			android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
			
		width, height = 800, 480
		self.displaySize = width, height
		self.display = pygame.display.set_mode(self.displaySize)
		self.fps = 60		

		#Peripherals
		self.keyboard = Keyboard()
		self.mouse = Mouse()
				
		# world
		self.world = World(width, height)

		#Other objects
		self.clock = pygame.time.Clock()		
Example #3
0
def main():
  pygame.init()

  screen = pygame.display.set_mode([480, 800])

  if android:
    android.init()
    android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    android.accelerometer_enable(True)

  game = Game(screen, "images")

  ret = game.startScreen()

  if ret == False:
    pygame.quit()
    sys.exit(1)

  while 1:
    game.init()
    ret = game.play()
    if ret == False:
      pygame.quit()
      sys.exit(1)

    ret = game.gameOver()
    if ret == False:
      pygame.quit()
      sys.exit(1)
Example #4
0
def main():
    try:
        adv=advertise.advertise('http://ammar.pythonanywhere.com/adv/snake',g.canvas,(0,0),(240,320))
        while adv.show:
            adv.adv_cont.read_input()
            pygame.display.update()
    except:
        pass
    #print "running1"
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.QUIT)
    while g.running:
        if android:
            android.accelerometer_enable(bool(accelerometer))
            if accelerometer:
                d=check_dir_acc()
                if d=="up":
                    g.up()
                elif d=="down":
                    g.down()
                elif d=="left":
                    g.left()
                elif d=="right":
                    g.right()
                else:
                    pass
        #print "running2"
        g.move()
        #print "moved"
        try:
            ao_sleep(slow)
        except:
            pass
        ao_yield()
Example #5
0
 def __init__(self):
     android.accelerometer_enable(True)
     Clock.schedule_interval(self.detect_motion, 0.1)
     self.last = None
     self.history = deque()
     self.shake_callback = None
     self.enabled = True
Example #6
0
def main():
  pygame.init()
  mixer.init()

  screen = pygame.display.set_mode([480, 700])

  if android:
    android.init()
    android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    android.accelerometer_enable(True)

  game = Game(screen, "images")

  ret = game.startScreen()

  if ret == False:
    pygame.quit()
    sys.exit(1)

  while 1:
    game.init()
    for life in range(3):
        ball = game.createBall()
        game.balls.append(ball)
        ret = game.play()
        if ret == False:
          pygame.quit()
          sys.exit(1)

    ret = game.gameOver()
    if ret == False:
      pygame.quit()
      sys.exit(1)
Example #7
0
def main():
    if android:
        android.init()
        android.accelerometer_enable(True)
    pygame.init()

    screen = pygame.display.set_mode((800, 480))
    
    c = game.Controls(screen)
    space = game.Space(load_image('background.png'))
    camera = game.Camera(space)
    direction = game.DIR_STOP

    in_game = True
    while in_game:
        
        print c.angle, c.angle%(2*math.pi), c.press
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                in_game = False
            elif (event.type == pygame.KEYDOWN and
                  event.key == pygame.K_ESCAPE):
                in_game = False
            elif (event.type == pygame.KEYDOWN and
                  event.key == pygame.K_LEFT):
                direction = game.DIR_LEFT
            elif (event.type == pygame.KEYDOWN and
                  event.key == pygame.K_RIGHT):
                direction = game.DIR_RIGHT
            elif ((event.type == pygame.KEYUP) and
                  (event.key == pygame.K_LEFT) and
                  (direction == game.DIR_LEFT)):
                direction = game.DIR_STOP
            elif ((event.type == pygame.KEYUP) and
                  (event.key == pygame.K_RIGHT) and
                  (direction == game.DIR_RIGHT)):
                direction = game.DIR_STOP
            elif (event.type == pygame.KEYDOWN and
                  event.key == pygame.K_UP):
                direction = game.DIR_UP
            elif (event.type == pygame.KEYDOWN and
                  event.key == pygame.K_DOWN):
                direction = game.DIR_DOWN
            elif ((event.type == pygame.KEYUP) and
                  (event.key == pygame.K_UP) and
                  (direction == game.DIR_UP)):
                direction = game.DIR_STOP
            elif ((event.type == pygame.KEYUP) and
                  (event.key == pygame.K_DOWN) and
                  (direction == game.DIR_DOWN)):
                direction = game.DIR_STOP

        camera.move_camera(direction)
        dirty = screen.blit(camera.view, (0, 0))
        pygame.display.flip()
 def __init__(self, scene):
     """ intialize sprite class """
     pygame.sprite.DirtySprite.__init__(self)
     self.scene = scene
     self.screen = scene.screen     
     
     #default sprite attributes
     
     self.pause = 0
     self.frame = 0   
     self.delay = 800       
     self.imgsize = (75, 75)
     self.reset()        
     if android:
         android.accelerometer_enable(True)
Example #9
0
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
Example #10
0
def main():
	global f
	f = open("traceback.txt", 'w')
	import sys
	import traceback
	try:
		pygame.init()
		android.accelerometer_enable(True)
		mode = None
		for mode in pygame.display.list_modes():
			if mode[1] <= 640:
				break
		run(mode)
	except:
		global f
		traceback.print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, None, f) #@UndefinedVariable
		f.close()
Example #11
0
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
Example #12
0
def main():
  pygame.init()
  if android:
    android.init()
    # android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    android.accelerometer_enable(True)
  shaker = ShakeSensor()

  clock = pygame.time.Clock()

  main = pygame.display.set_mode((800, 400))
  pygame.display.set_caption('Shake Test')
  FONTFILE = 'freesansbold.ttf'
  font = pygame.font.Font(FONTFILE, 12)

  lastshake = time.time()

  label = 'no shake'
  while True:
    if android:
      shaker.update()
    for ev in pygame.event.get():
      if ev.type == pygame.QUIT:
	sys.exit()
      if ev.type == pygame.KEYDOWN:
	if android and ev.key == android.KEYCODE_BACK:
	  sys.exit()
      if ev.type == ShakeSensor.SHAKE_EVENT:
        label = '%s: %2.4fm, offset: %2.4fm' % (time.time(), ev.absolute.r, ev.overall.r)
        lastshake = time.time()

    color = 255 - (time.time() - lastshake) * 255
    if color > 255: color = 255
    if color < 0: color = 0
    main.fill((color, 0, 0))
    text = font.render(label, True, (255,255, 255))
    main.blit(text, text.get_rect())
    pygame.display.flip()

    clock.tick(15)
Example #13
0
### variables and creating the group for bullets
bullet_group = pygame.sprite.Group()
bullet_timer = bullet_delay
# character = Player()

monster_group = pygame.sprite.Group()
for number in range(0, 8):
    monster = Monster()
    monster_group.add(monster)

if android:
    android.init()
    android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    enable = True
    android.accelerometer_enable(enable)

WHITE = ((255, 255, 255))
BLACK = ((0, 0, 0))
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:
Example #14
0
    def point(self, pos):
        angle = self.angle(pos)
        hypotenuse = 50
        adjacent = math.cos(angle) * hypotenuse
        x = int(60 + adjacent)
        opposite = math.sin(angle) * hypotenuse
        y =  int(60-opposite)
        pygame.draw.circle(self.image, self.YELLOW, (x, y), 10, 2)

pygame.init()

if android:
    android.init()
    android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    enable = True
    android.accelerometer_enable(enable)

SCREENSIZE=(480,320)
SCREENCENTER=(SCREENSIZE[0]/2, SCREENSIZE[1]/2)
SCREEN = pygame.display.set_mode((480, 320))
RED=(255, 0, 0)
GREEN=(0, 255, 0)
BLACK=(0,0,0)
speed = 5
direction = "stop"

sprite_sheet = pygame.image.load("img/sprite_sheet.png").convert_alpha()

player_d = []
player_r = []
player_l = []
Example #15
0
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)	
Example #16
0
    def __init__(self):

        """Inits the game."""

        pygame.init()

        # Set size here so Android can overwrite it.
        size=[640,480]

        # Do some android stuff
        if android:
            android.init()

            # Map back key to to escape
            android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

            # Get display size and set game size to it
            disp_info = pygame.display.Info()
            size = [disp_info.current_w, disp_info.current_h]

            # Activate accelerometer
            if settings.getBool("android","accelerometer_enable"): android.accelerometer_enable(1)

        # Screen/Dialog stuff
        self.screen=pygame.display.set_mode(size, pygame.RESIZABLE)
        pygame.display.set_caption("UpChomp")

        # Used to manage how fast the screen updates
        self.clock=pygame.time.Clock()

        # Game Save
        self.save = iniget.iniGet(app_path + "game.sav")
        
        # Sprites
        self.all_sprites_list = pygame.sprite.RenderPlain()

        # Initalize Sound
        self.sound = sound.Sound()        
        
        # Init da Chomp
        self.chomp = chompy.Chompy(self.screen, self.sound)
        self.all_sprites_list.add(self.chomp)
        
        # Init Menu
        self.menu = menu.Menu(self.screen, self.sound, self.clock, self.save)        
        
        # Make a dialog object.
        self.dlogbox = dialog.Dialog(self.screen, self.sound)

        # Setup Hud
        self.hud = hud.Hud(self.screen, self.sound)

        # Setup Transition
        self.transition = transition.Transition()

        # Game State: 0-Playing, 1-Main Menu, 2-Pack Select, 3 - Load New Level
        self.state = 1

        # Init Game Map
        self.level = gamemap.Gamemap(self.sound, self.save)

        # Frame rate
        self.frames = 1

        # Set Current Map
        self.map_file = []

        # Opening a map... install it.
        if len(sys.argv) > 1:
          size = self.screen.get_size()

          # Unzip Map
          if not zipfile.is_zipfile(sys.argv[1]):
            self.gameLoop()
            return None
            
          # Make Temporary Storage Directory
          if os.path.exists(app_path + "temp"):
            shutil.rmtree(app_path +"temp")
            time.sleep(.25)
          os.mkdir(app_path + "temp")

          zip_file = zipfile.ZipFile(sys.argv[1])
          zip_file.extract("maps", app_path + "temp/")
          zip_file.close()
            
          
          mappack = iniget.iniGet(app_path + "temp/maps")

          # Get map hash (Used in save file)
          maphash = hashlib.sha224(open(sys.argv[1]).read()).hexdigest()
          
          if mappack.get("pack","name") and mappack.get("pack", "order"):         

              oldmaphash = ""
              if os.path.isfile(app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm"):
                  oldmaphash = hashlib.sha224(open(app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm").read()).hexdigest()

              if maphash == oldmaphash:
                  print "Failed to install new map pack."
                  self.dlogbox.setMessageBox(size, "The map you are trying to install appears to already be installed.", "Already Installed!", [['OK',self.menu.dialog.closeMessageBox]] )                  
                  
              else:

                  shutil.copy (sys.argv[1], app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm")
                  
                  if os.path.isfile(app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm"):
                      print "Installed map pack '"+ str(mappack.get("pack","name").replace(" ", "_")) + ".ucm'."
                      self.dlogbox.setMessageBox(size, "New map pack has been installed!", "New Map Pack!", [['OK',self.menu.dialog.closeMessageBox]] )  
                  else:
                      print "Failed to install new map pack."
                      self.dlogbox.setMessageBox(size, "Unable to install map pack.", "Error", [['OK',self.menu.dialog.closeMessageBox]] )  
                  
              events = pygame.event.get() 
              while self.dlogbox.drawBox(size, events):
                events = pygame.event.get()
                
                for event in events:
                    if event.type == pygame.QUIT: # If user clicked close
                        pygame.quit()
                        sys.exit()
                        
                    elif event.type == pygame.VIDEORESIZE:
                        size = event.size
                        
                # Android events
                if android:

                    if android.check_pause():
                        android.wait_for_resume()          
                                  
                pygame.display.flip()

        # Enter game loop
        self.gameLoop()
Example #17
0
def title(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

    menu_image = "assets/menu.png"
    play_image = "assets/play.png"
    played_image = "assets/play_pressed.png"
    highscore_image = "assets/highscore.png"
    highscored_image = "assets/highscore_pressed.png"
    exit_image = "assets/exit.png"
    exited_image = "assets/exit_pressed.png"
    font = pygame.font.Font("assets/freesansbold.ttf", 30)
    try:
        mixer.music.load("assets/menu.ogg")
        mixer.music.play(-1)
    except pygame.error:
        print "Couldn't find file."

    balloon_speed = 3
    moveRate = 2

    score = 0

    background = (0, 0, 0)

    sky = Backgrounds(screen, scroll_speed, menu_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, 3000)
    pygame.time.set_timer(USEREVENT + 1, 1000)
    pygame.time.set_timer(USEREVENT + 2, 2000)

    pygame.key.set_repeat(FPS, FPS)  # set key repeat on

    play = Balloons(screen, SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT / 2 - 330, 0, balloon_speed, play_image, played_image)
    highscore = Balloons(
        screen, SCREEN_WIDTH / 2 - 230, SCREEN_HEIGHT / 2 - 150, 0, balloon_speed, highscore_image, highscored_image
    )
    getout = Balloons(screen, SCREEN_WIDTH / 2 + 30, SCREEN_HEIGHT / 2 + 10, 0, balloon_speed, exit_image, exited_image)

    while True:
        # game loop
        time_passed = clock.tick(FPS)

        if android:

            if android.check_pause():
                android.wait_for_resume()

        init_x = randint(0, SCREEN_WIDTH)

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if getout.rect.collidepoint(event.pos):
                        getout.active = True
                        screen.fill(background)
                        sky.draw()
                        play.draw()
                        highscore.draw()
                        getout.draw()
                        pygame.display.flip()
                    elif play.rect.collidepoint(event.pos):
                        play.active = True
                        screen.fill(background)
                        sky.draw()
                        play.draw()
                        highscore.draw()
                        getout.draw()
                        pygame.display.flip()
                    elif highscore.rect.collidepoint(event.pos):
                        highscore.active = True
                        screen.fill(background)
                        sky.draw()
                        play.draw()
                        highscore.draw()
                        getout.draw()
                        pygame.display.flip()

            elif event.type == pygame.MOUSEBUTTONUP:
                highscore.active = False
                play.active = False
                getout.active = False
                if event.button == 1:
                    if getout.rect.collidepoint(event.pos):
                        sys.exit(0)
                        pygame.quit()
                    elif play.rect.collidepoint(event.pos):
                        mixer.music.fadeout(500)
                        return 99
                    elif highscore.rect.collidepoint(event.pos):
                        mixer.music.fadeout(500)
                        return 100

        screen.fill(background)

        sky.update()
        sky.draw()

        play.update()
        play.draw()

        highscore.update()
        highscore.draw()

        getout.update()
        getout.draw()

        pygame.display.flip()
Example #18
0
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)
Example #19
0
 def enable(self):
     android.accelerometer_enable(True)
     Clock.schedule_interval(self.detect_motion, 0.1)
Example #20
0
class MyGame(Widget):

    menu = ObjectProperty(None)
    gameMenu = ObjectProperty(None)
    player = ObjectProperty(None)
    boss = ObjectProperty(None)
    endGameMenu = ObjectProperty(None)
    gameOverMenu = ObjectProperty(None)

    #Sons
    musicaTema = ObjectProperty(None)
    gameOverSound = ObjectProperty(None)
    gameWinSound = ObjectProperty(None)

    gamePause = True
    currentTime = NumericProperty(0)
    timeGame = NumericProperty(30)
    soundOn = True
    temaPlaying = False
    niveis = []
    nivelCorrente = 0

    if (android):
        android.init()
        android.accelerometer_enable(True)
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    def start_menu(self):
        self.menu = StartMenu()
        self.menu.start_menu("./images/titulo.png")
        self.menu.startButton.bind(on_release=self.__removeStartMenu)
        self.menu.soundControl.bind(on_press=self.__soundOnOff)
        self.menu.exit.bind(on_press=self.__exit)
        self.add_widget(self.menu)
        self.gameMenu = GameMenu()
        self.gameMenu.startGameMenu()
        self.gameMenu.playPause.bind(on_press=self.__playPause)
        self.gameMenu.soundControl.bind(on_press=self.__soundOnOff)
        self.gameMenu.exit.bind(on_press=self.__exit)
        self.gameMenu.restart.bind(on_press=self.__restarCurrentLevelMenu)
        self.endGameMenu = EndGameMenu()
        self.endGameMenu.restart.bind(on_press=self.__restartCurrentLevel)
        self.gameOverMenu = GameOverMenu()
        self.gameOverMenu.restart.bind(on_press=self.__restartCurrentLevelOver)

    def __restartCurrentLevelOver(self, instance):

        if (self.gameOverSound.state == "play"):
            self.gameOverSound.stop()
        if (self.gameWinSound.state == "play"):
            self.gameWinSound.stop()

        self.player = Player()
        self.player.pos = [200, 10]
        self.lobo = Boss()

        self.niveis[self.nivelCorrente] = None
        self.niveis[self.nivelCorrente] = Nivel1(
            player=self.player,
            backgroundImage="./images/fundo.png",
            boss=self.lobo)

        self.niveis[0].soundOn = self.soundOn
        self.lobo.pos = [self.niveis[0].tamanhoFase / 3, 10]

        self.add_widget(self.niveis[0])
        self.add_widget(self.player)
        self.add_widget(self.lobo)
        self.add_widget(self.gameMenu)
        self.remove_widget(self.gameOverMenu)
        self.gamePause = False

    def __restarCurrentLevelMenu(self, instance):
        self.remove_widget(self.niveis[self.nivelCorrente])
        self.remove_widget(self.gameMenu)
        self.remove_widget(self.player)
        self.remove_widget(self.lobo)
        self.__restartCurrentLevel(instance)

    def __restartCurrentLevel(self, instance):

        if (self.gameOverSound.state == "play"):
            self.gameOverSound.stop()
        if (self.gameWinSound.state == "play"):
            self.gameWinSound.stop()

        self.player = Player()
        self.lobo = Boss()

        self.player.pos = [200, 10]
        self.niveis[self.nivelCorrente] = None
        self.niveis[self.nivelCorrente] = Nivel1(
            player=self.player,
            backgroundImage="./images/fundo.png",
            boss=self.lobo)

        self.niveis[0].soundOn = self.soundOn
        self.lobo.pos = [self.niveis[0].tamanhoFase / 3, 10]

        self.add_widget(self.niveis[0])
        self.add_widget(self.player)
        self.add_widget(self.lobo)
        self.add_widget(self.gameMenu)
        self.remove_widget(self.endGameMenu)
        self.gamePause = False

    def __startNiveis(self):
        self.player = Player()
        self.lobo = Boss()
        self.player.pos = [200, 10]

        self.niveis.append(
            Nivel1(player=self.player,
                   backgroundImage="./images/fundo.png",
                   boss=self.lobo))
        self.lobo.pos = [self.niveis[0].tamanhoFase / 3, 10]

        self.niveis[0].soundOn = self.soundOn

        self.add_widget(self.niveis[0])
        self.add_widget(self.player)
        self.add_widget(self.lobo)

    def __removeStartMenu(self, instance):
        self.gamePause = False
        self.remove_widget(self.menu)
        self.__startNiveis()
        self.add_widget(self.gameMenu)

    def __addStartMenu(self, instance):
        self.add_widget(self.menu)

    def __playPause(self, instance):
        if (self.gamePause is True):
            self.gamePause = False
            self.gameMenu.playPause.background_normal = \
                    "./images/botoes/start0.png"
        else:
            self.gamePause = True
            self.gameMenu.playPause.background_normal = \
                     "./images/botoes/pause0.png"

    def __soundOnOff(self, instance):
        if (self.soundOn is True):
            self.soundOn = False
            self.gameMenu.soundControl.background_normal = \
                    "./images/botoes/mute.png"
            if (self.menu):
                self.menu.soundControl.background_normal = \
                    "./images/botoes/mute.png"
        else:
            self.soundOn = True
            self.gameMenu.soundControl.background_normal = \
                    "./images/botoes/sound.png"
            if (self.menu):
                self.menu.soundControl.background_normal = \
                    "./images/botoes/sound.png"

    def __exit(self, instance):
        import sys
        sys.exit()

    def on_touch_move(self, touch):
        if (touch.y < Window.height * 0.8 - 100):
            if (self.player):
                self.player.jump()

    def updateNivel(self, dt):
        self.niveis[self.nivelCorrente].soundOn = self.soundOn
        self.niveis[self.nivelCorrente].update()

        self.gameMenu.labelPonto.text = "Points: " + \
                        str(self.niveis[self.nivelCorrente].pontos)

        self.gameMenu.labelTime.text = "Time: " + \
                                str(self.niveis[self.nivelCorrente].timeGame)

        self.currentTime += 1
        if (self.currentTime >= 60):
            self.currentTime = 0
            self.niveis[self.nivelCorrente].timeGame -= 1

        if (self.niveis[self.nivelCorrente].fimNivel):
            if (self.soundOn):
                self.gameWinSound.play()
            self.gamePause = True
            self.remove_widget(self.niveis[self.nivelCorrente])
            self.remove_widget(self.gameMenu)
            self.remove_widget(self.player)
            self.remove_widget(self.lobo)
            self.endGameMenu.label.text = "Points: " \
                    + str(self.niveis[self.nivelCorrente].pontos)
            self.add_widget(self.endGameMenu)

        if (self.niveis[self.nivelCorrente].timeGame <= 0
                or self.niveis[self.nivelCorrente].nivelPerdido is True):
            if (self.soundOn):
                self.gameOverSound.play()
            self.gamePause = True
            self.remove_widget(self.niveis[self.nivelCorrente])
            self.remove_widget(self.gameMenu)
            self.remove_widget(self.player)
            self.remove_widget(self.lobo)
            self.gameOverMenu.label.text = "Points: " \
                    + str(self.niveis[self.nivelCorrente].pontos)
            self.add_widget(self.gameOverMenu)

    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, dt):

        if (android):
            if android.check_pause():
                if (self.musicaTema.state == "play"):
                    self.musicaTema.stop()
                android.wait_for_resume()

        if (self.soundOn is True):
            if (self.musicaTema.state == "stop"):
                self.musicaTema.play()
                self.musicaTema.volume = 0.3
        else:
            if (self.musicaTema.state == "play"):
                self.musicaTema.stop()
                self.musicaTema.volume = 0.3

        if (self.gamePause is not True):
            self.__movingPlayerAndroid()
            self.updateNivel(dt)
Example #21
0
import pygame

try:
    import android
    import android_mixer as mixer
    android.accelerometer_enable(True)
except ImportError:
    android = None
    from pygame import mixer

# Some general utility functions here

def load_font(name, size):
    return pygame.font.Font("data/" + name + ".ttf", size)

def load_image(name):
    return pygame.image.load("data/" + name + ".png").convert_alpha()

def load_sound(name):
    return mixer.Sound("data/" + name + ".ogg")

def load_music(name):
    # The all-caps ogg is because the original file just happened to be that way
    mixer.music.load("data/" + name + ".ogg")

def android_check_pause():
    if android:
       if android.check_pause():
            android.wait_for_resume()

def vibrate():
Example #22
0
 def disable(self):
     android.accelerometer_enable(False)
     Clock.unschedule(self.detect_motion)
Example #23
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()