Example #1
0
 def __init__(self):
     # Get the helicopter instance
     self.heli = Helicopter()
     # Gyro - how we sense the difference between the demand and the reality
     self.gyro = Gyro(
         normalise_rates=True,
         gyro_normalisation_values=self._gyro_normalisation_values,
         acceleration_normalisation_values=[1, 1, 1])
     # Init the demands variable
     self.demands = None
     self.flying = False
     self.thread_running = True
     # Create a thread for this to run in
     self.pilot_thread = Thread(target=self.fly, daemon=True)
     self.pilot_thread.start()
Example #2
0
 def __init__(self):
     self.__screen_width = 800
     self.__screen_height = 600
     self.__display = pygame.display
     self.__surface = self.__display.set_mode((self.__screen_width, self.__screen_height))
     self.__clock = pygame.time.Clock()
     self.__heli = Helicopter("helicopter.png")
     self.__logger = None
     self.__obstacle_list = []
     self.__colors = [LIGHTBLUE, ORANGE, PURPLE, YELLOW, YELLOWGREEN]
     self.score = 0
Example #3
0
class Game:
    def __init__(self):
        self.__screen_width = 800
        self.__screen_height = 600
        self.__display = pygame.display
        self.__surface = self.__display.set_mode((self.__screen_width, self.__screen_height))
        self.__clock = pygame.time.Clock()
        self.__heli = Helicopter("helicopter.png")
        self.__logger = None
        self.__obstacle_list = []
        self.__colors = [LIGHTBLUE, ORANGE, PURPLE, YELLOW, YELLOWGREEN]
        self.score = 0

    # Update all objects
    def update(self):
        self.__heli.update()
        for obstacle in self.__obstacle_list:
            # Check if colliding with obstacle
            if obstacle.is_colliding(self.__heli):
                self.game_over()
            # Check if we've successfully passed this obstacle. Only count score once
            if not obstacle.passed_player and obstacle.x + obstacle.width <= self.__heli.x:
                obstacle.passed_player = True
                self.score += 1

            # Remove obstacles that are now off the screen
            if obstacle.x + obstacle.width <= 0:
                self.__obstacle_list.remove(obstacle)

        # Check for hitting ceiling/floor after checking objects
        if self.__heli.is_out_of_bounds():
            self.game_over()

        # Update obstacle speed and position.
        # We do this after checking for scores to guarantee that all speeds will be the same
        for obstacle in self.__obstacle_list:
            diff_settings = self.get_difficulty_settings()
            obstacle.vel_x = diff_settings[0]
            obstacle.update()

        # Decide whether to generate a new obstacle
        self.generate_obstacle()

    # Draw all objects
    def draw(self):
        self.__heli.draw(self.__surface)
        for obstacle in self.__obstacle_list:
            obstacle.draw(self.__surface)
        self.__logger.score(self.score)

    # Quit the game or return user input
    def replay_or_quit(self):
        for event in pygame.event.get([KEYDOWN, KEYUP, QUIT]):
            if event.type is QUIT or event.key is K_ESCAPE:
                pygame.quit()
                quit()
            elif event.type is KEYDOWN or event.type is KEYUP:
                return event.key
        if pygame.mouse.get_pressed()[0]:
                return True
        return None

    # Display game over message and wait for user input
    def game_over(self):
        self.__logger.game_over("Kaboom!", 1)
        while self.replay_or_quit() is None:
            self.__clock.tick()
        self.reset()
        self.run()

    # Reset the game
    def reset(self):
        self.__heli.reset()
        self.__obstacle_list = []
        self.score = 0

    # Determine when and what type of obstacle to generate
    def generate_obstacle(self):
        types = {0: Platform, 1: Pipe, 2: DoublePipe}

        create_obstacle = len(self.__obstacle_list) is 0
        if not create_obstacle:
            last_obstacle = self.__obstacle_list[-1]
            if last_obstacle.x + last_obstacle.width <= self.__screen_width - 400:
                create_obstacle = randint(0, 1) is 1
        if create_obstacle:
            color = self.__colors[randrange(0, len(self.__colors))]
            diff_settings = self.get_difficulty_settings()
            obs_type = types[randint(0, 2)]
            if obs_type is Platform:
                platform_height = 50
                obstacle = obs_type(self.__screen_width, (self.__screen_height - platform_height) / 2,
                                    randint(150, self.__screen_width / 2), platform_height, diff_settings[0], color)
            else:
                obstacle = obs_type(self.__screen_width, 0, 75, randint(0, self.__screen_height), diff_settings[0],
                                    self.__heli.height * diff_settings[1], color)
            self.__obstacle_list.append(obstacle)

    # Change difficulty based on the player's score
    def get_difficulty_settings(self):
        # First part is speed, second is gap modifier
        settings = (3, 3.2)
        if 3 <= self.score < 5:
            settings = (4, 3.1)
        elif 5 <= self.score < 8:
            settings = (5, 3.0)
        elif 8 <= self.score < 14:
            settings = (6, 2.9)
        elif self.score >= 14:
            settings = (7, 2.8)
        return settings

    # Run the game
    def run(self):
        self.__logger = Logger(self.__display, self.__surface)
        self.generate_obstacle()
        while True:
            self.__surface.fill(BLACK)
            self.update()
            self.draw()
            self.replay_or_quit()
            self.__display.update()
            self.__clock.tick(75)
Example #4
0
def run_game():
	#initialize pygame
	pygame.init()
	clock = pygame.time.Clock()
	screen = pygame.display.set_mode((cfg.width, cfg.height))
	pygame.display.set_caption('Helicopter')
	pygame.mouse.set_visible(1)

	#Create background
	background = pygame.Surface(screen.get_size())
	background = background.convert()
	background.fill((25, 25, 25))

    #Prepare game objects
	controller = Level_controller()
	helicopter = Helicopter()
	copter = pygame.sprite.RenderPlain()
	copter.add(helicopter)

	#Main loop
	while 1: 
		clock.tick(60)
		for event in pygame.event.get():
			if event.type == QUIT:
				return
			elif event.type == KEYDOWN and event.key == K_ESCAPE:
				return
			elif event.type == MOUSEBUTTONDOWN or \
            event.type == KEYDOWN and event.key == K_UP:
				helicopter.hit_gas()
			elif event.type is MOUSEBUTTONUP or \
            event.type == KEYUP and event.key == K_UP:
				helicopter.release_gas()
			elif event.type is KEYDOWN and event.key == K_r:
				controller = Level_controller()
				helicopter = Helicopter()
				copter = pygame.sprite.RenderPlain()
				copter.add(helicopter)

		#Draw the current frame
		screen.blit(background, (0,0))
		controller.bottom_wall_sprites.draw(screen)
		controller.top_wall_sprites.draw(screen)
		controller.obstacle_sprites.draw(screen)
		copter.draw(screen)
		screen.blit(get_score_surface(controller.get_score()), (10, 10))


		#Check for collisions, stopping the game if any are found
		if len(pygame.sprite.groupcollide(copter, controller.top_wall_sprites, 0, 0)) != 0 or \
			len(pygame.sprite.groupcollide(copter, controller.bottom_wall_sprites, 0, 0)) != 0 or \
			len(pygame.sprite.groupcollide(copter, controller.obstacle_sprites, 0, 0)) != 0:
			controller.moving = False
			text = get_game_over_surface(controller.get_score())
			textpos = text.get_rect(centerx=background.get_width()/2, centery=background.get_height()/2)
			screen.blit(text, textpos)
		
		pygame.display.flip()

		#Move the level, updating all sprites in the process.
		#ONLY done if level is moving -- ie, game is not over
		controller.move_level()
		if controller.moving:
			copter.update()
Example #5
0
def csv_to_helicopters(file_name: str):
    helicopters = []
    csv_file = open(file_name, 'r')
    for row in csv.reader(csv_file):
        helicopters.append(Helicopter(int(row[0]), row[1], int(row[2])))
    return helicopters
Example #6
0
def main():
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    
    size = width, height = 1152, 648
    moveRight = 0
    moveLeft = 0
    points = 10
    timer = 30
    running = 1
    screen = pygame.display.set_mode(size)

    background = pygame.image.load('E:/Koodi/Python/pygame/data/bg.png').convert()
    screen.blit(background, (0, 0))
    
    pygame.mixer.music.load('E:/Koodi/Python/pygame/data/music/08.mp3')
    boom = pygame.mixer.Sound('E:/Koodi/Python/pygame/data/music/explosion-02.wav')
    pygame.mixer.music.play(-1)
    
    clock = pygame.time.Clock()
    snowman = SnowMan()
    heli = Helicopter()
    uisprites = pygame.sprite.Group((heli))
    shootables = pygame.sprite.Group((snowman))
    CAREVENT = USEREVENT+1
    TIMEEVENT = USEREVENT+2
    
    pygame.time.set_timer(CAREVENT, random.randint(600, 1000))
    pygame.time.set_timer(TIMEEVENT, 1000)
    while running:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == KEYDOWN and event.key == K_RIGHT:
                print "right"
                moveRight = 1
            elif event.type == KEYDOWN and event.key == K_LEFT:
                print "left"
                moveLeft = 1
            elif event.type == KEYDOWN and event.key == K_SPACE:
                points = points-1
                uisprites.add(Ball(heli.rect.right-65))
                print "space"
            elif event.type == KEYUP and event.key == K_LEFT:
                moveLeft = 0
            elif event.type == KEYUP and event.key == K_RIGHT:
                moveRight = 0
                
            elif event.type is CAREVENT:
                pygame.time.set_timer(CAREVENT, random.randint(600, 1000))
                shootables.add(Car())
            elif event.type is TIMEEVENT:
                timer = timer - 1
                if timer == 0:
                    running = 0
                
        if moveRight:
            heli.moveRight()
        elif moveLeft:
            heli.moveLeft()
            
        for shootable in pygame.sprite.groupcollide(shootables, uisprites , 1, 1):
            print "shoot"
            shootable.shooted()
            print shootable.rnd
            if shootable.rnd == 5:
                points = points + 1
            elif shootable.rnd == 0:
                points = points - 10
            elif shootable.rnd == 2 or shootable.rnd == 3:
                points = points + 2
            else:
                points = points + 5
            boom.play()
            
        font = pygame.font.Font(None, 30)
        text = font.render('Points '+str(points), 1, (255,
        255, 255))
        timetext = font.render('Time: '+str(timer), 1, (255,
        255, 255))

        shootables.update()
        uisprites.update()
        screen.blit(background, (0, 0))
        screen.blit(text, (1000, 50))
        screen.blit(timetext, (1000, 80))
        
        shootables.draw(screen)
        uisprites.draw(screen)
        pygame.display.flip()
        
    raw_input('Press Enter...')
Example #7
0
def run():
    pygame.init()
    pygame.font.init()
    # recursos del juego
    screen = pygame.display.set_mode((799, 464), pygame.RESIZABLE)
    #screen = pygame.display.set_mode((0, 0), pygame.RESIZABLE)
    pygame.display.set_caption("MachineMCD")
    temporizador = pygame.time.Clock()
    power = 0
    maximo = 0
    gameOver = 0
    mcd1 = 1

    haybomba = False
    controlMaximo = True
    texto = pygame.font.Font('digital-7.ttf', 42)
    texto2 = pygame.font.Font('digital-7.ttf', 25)
    textobomba = pygame.font.Font('Crysta.ttf', 26)
    # fondo de pantalla
    fondo = util.cargar_imagen('escenario.png', optimizar=True)
    decoracion = util.cargar_imagen('decoracion.png')
    final = util.cargar_imagen('Final.png')

    bomba = Bomba(-20, -20)
    bombaE = BombaE(100, 100)
    # grupos
    sprites = pygame.sprite.OrderedUpdates()
    explo = pygame.sprite.Group()
    control = pygame.sprite.Group()
    cube1 = pygame.sprite.Group()
    cube2 = pygame.sprite.Group()
    helicopter = pygame.sprite.Group()
    Bomasprites = pygame.sprite.Group()
    botonA = Boton(500, 435, 'a')
    botonB = Boton(600, 435, 's')
    palanca = Palanca(208, 387)
    helicoptero = Helicopter(105, 95)
    control.add([botonA, botonB, palanca])
    helicopter.add([helicoptero])
    sprites.add([cube1, cube2, helicopter])

    salir = False

    def divisoresPropios(n):
        lista = []
        for i in range(1, (n / 2) + 1):
            if (n % i) == 0:
                lista.append(i)
        lista.append(n)
        return lista

    def mcd(a, b):
        a, b = max(abs(a), abs(b)), min(abs(a), abs(b))
        while b > 0:
            a, b = b, a % b
        return a

    def draw_cubes():
        posY1 = 350
        posX1 = 60
        posY2 = 350
        posX2 = 410
        n = 0
        j = 0
        for i in range(numcubes1):
            if j < 11:
                j = j + 1
                posX1 = posX1 + 25
                cube1.add(Cube(posX1, posY1))
            else:
                j = 1
                posX1 = 60 + 25
                posY1 = posY1 - 25
                cube1.add(Cube(posX1, posY1))
        for m in range(numcubes2):
            if n < 11:
                n = n + 1
                posX2 = posX2 + 25
                cube2.add(Cube(posX2, posY2))
            else:
                n = 1
                posX2 = 410 + 25
                posY2 = posY2 - 25
                cube2.add(Cube(posX2, posY2))

    numero1 = random.randint(0, 70)
    numero2 = random.randint(1, 70)

    numcubes1 = numero1
    numcubes2 = numero2
    #numcubes1=4
    #numcubes2=12
    mcd1 = mcd(numero1, numero2)
    div1 = []
    div2 = []
    div1 = divisoresPropios(numero1)
    div2 = divisoresPropios(numero2)
    Text_Divisores1 = ""
    Text_Divisores2 = ""
    for divisor1 in div1:
        Text_Divisores1 += str(divisor1) + " "
    for divisor2 in div2:
        Text_Divisores2 += str(divisor2) + " "

    draw_cubes()
    bombanumero = textobomba.render("00", 1, (176, 0, 0))
    while not salir:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                salir = True
            elif e.type == pygame.KEYDOWN:
                if e.unicode == 'a' or e.unicode == 'A':
                    if haybomba == False:
                        power = maximo
                        controlMaximo = False
                        bomba = Bomba(helicoptero.rect.x + 45,
                                      helicoptero.rect.y + 20)
                        sprites.add(bomba)
                        haybomba = True
        #    elif e.type == pygame.JOYBUTTONUP:

        if controlMaximo == True:
            teclasSelect = pygame.key.get_pressed()
            if teclasSelect[K_DOWN] and maximo > 0:
                maximo = maximo - 1
                bombanumero = textobomba.render(str(maximo), 1, (176, 0, 0))
                #text = font.render( str(maximo),1,WHITE)
            elif teclasSelect[K_UP] and maximo < 99:
                maximo = maximo + 1
                bombanumero = textobomba.render(str(maximo), 1, (176, 0, 0))

        if numcubes1 == 0 and numcubes2 == 0:

            gameOver = 2
    #    if (numcubes1>0 or numcubes2>0)and power == 0 and haybomba == True:

    #    if (numcubes1>0 or numcubes2>0):

    #      gameOver = 1

        if power > 0:
            bomba_en_colision2 = pygame.sprite.spritecollide(
                bomba, cube2, False)
            bomba_en_colision1 = pygame.sprite.spritecollide(
                bomba, cube1, False)

            if (bomba_en_colision1):
                if (numcubes2 > 0
                        and numcubes1 < power) or (numcubes2 > 0
                                                   and numcubes1 == 0):
                    gameOver = 1
                    bomba.kill()
            if (bomba_en_colision2):
                if (numcubes1 > 0
                        and numcubes2 < power) or (numcubes1 > 0
                                                   and numcubes2 == 0):
                    gameOver = 1
                    bomba.kill()

                #haybomba = False

            if bomba_en_colision1 and numcubes1 >= power:
                power -= 1
                numcubes1 -= 1

                bomba_en_colision1[0].kill()
                cube1.remove(bomba_en_colision1[0])
                sprites.add(Explosion(bomba_en_colision1[0]))
                sonidos.reproducir_sonido('boom')

            if bomba_en_colision2 and numcubes2 >= power:
                power -= 1
                numcubes2 -= 1
                bomba_en_colision2[0].kill()
                cube2.remove(bomba_en_colision2[0])
                sprites.add(Explosion(bomba_en_colision2[0]))
                sonidos.reproducir_sonido('boom')

        elif power == 0:
            bomba.kill()
            haybomba = False

        cubos1 = texto.render(str(len(cube1.sprites())), 1, (255, 215, 0))
        cubos2 = texto.render(str(len(cube2.sprites())), 1, (255, 215, 0))

        game1 = [
            "Ganaste!! ", "el poder de mayor destruccion es",
            "Casi lo logras!!", "Lo sentimos!!", "Divisores del ", ":"
        ]
        gameMCD = texto2.render(str(mcd1), 1, (255, 255, 255))
        num1 = texto2.render(str(numero1), 1, (255, 255, 255))
        num2 = texto2.render(str(numero2), 1, (255, 255, 255))

        sprites.update()
        screen.blit(fondo, (0, 0))
        cube1.draw(screen)
        cube2.draw(screen)
        sprites.draw(screen)
        helicopter.draw(screen)
        Bomasprites.draw(screen)
        screen.blit(decoracion, (0, 0))
        screen.blit(cubos1, (347, 98))
        screen.blit(cubos2, (417, 98))
        screen.blit(bombanumero, (387, 55))

        if gameOver != 0:
            screen.blit(final, (0, 0))

            if gameOver == 2 and maximo == mcd1:
                textIm1 = texto.render(game1[0], 1, (255, 255, 255))
                textIm2 = texto2.render(game1[1], 1, (255, 255, 255))
            if gameOver == 2 and maximo != mcd1:
                textIm1 = texto.render(game1[2], 1, (255, 255, 255))
                textIm2 = texto2.render(game1[1], 1, (255, 255, 255))
            if gameOver == 1:
                textIm1 = texto.render(game1[3], 1, (255, 255, 255))
                textIm2 = texto2.render(game1[1], 1, (255, 255, 255))
            textIm3 = texto2.render(game1[4], 1, (255, 255, 255))
            # mcd2 = texto2.render(mcd1,1,(255,255,255))
            screen.blit(textIm1, (150, 110))
            screen.blit(textIm2, (150, 145))
            screen.blit(gameMCD, (520, 145))
            #screen.blit(mcd2, (520, 145))
            screen.blit(textIm3, (170, 185))
            screen.blit(num1, (320, 185))
            screen.blit(texto2.render(Text_Divisores1, 1, (255, 255, 255)),
                        (175, 210))
            screen.blit(textIm3, (170, 250))
            screen.blit(num2, (320, 250))
            screen.blit(texto2.render(Text_Divisores2, 1, (255, 255, 255)),
                        (175, 275))

        control.draw(screen)
        control.update()
        pygame.display.flip()
        temporizador.tick(60)
Example #8
0
class HelicopterPilot:

    # Rates which equate to a demand of 1
    _gyro_normalisation_values = [50, 50, 80]

    # Thresholds
    _min_throttle = 0.3
    _yaw_threshold = 0.1

    def __init__(self):
        # Get the helicopter instance
        self.heli = Helicopter()
        # Gyro - how we sense the difference between the demand and the reality
        self.gyro = Gyro(
            normalise_rates=True,
            gyro_normalisation_values=self._gyro_normalisation_values,
            acceleration_normalisation_values=[1, 1, 1])
        # Init the demands variable
        self.demands = None
        self.flying = False
        self.thread_running = True
        # Create a thread for this to run in
        self.pilot_thread = Thread(target=self.fly, daemon=True)
        self.pilot_thread.start()

    def update_demands(self, demands):
        """ Update the helicopter's input demands"""
        if demands:
            #            print(f"Latest demands: {demands}")
            if not self.flying:
                if 'start_demand' in demands and 'stop_demand' in demands:
                    if demands['start_demand'] and not demands['stop_demand']:
                        # Then we haven't fired the motor up yet, so get it spinning
                        self.heli.start_motor()
                        self.flying = True
                if 'calibration_demand' in demands and demands[
                        'calibration_demand']:
                    # Then we want to calibrate - the gyro class will prevent us from running this multiple times, so just call calibrate() while the button is down
                    self.gyro.calibrate()

            self.demands = demands

    def fly(self):
        while self.thread_running:
            if self.flying:
                try:
                    accelerations = self.gyro.get_acceleration()
                    gyro_rates = self.gyro.get_gyro()
                except IOError as e:
                    print("Error getting gyro/accelerometer details!")
                    print(e)
                    accelerations = [0, 0, 0]
                    gyro_rates = [0, 0, 0]
                for demand in self.demands:
                    demand_value = self.demands[demand]
                    #print(f"Demand: {demand}, value = {demand_value}")
                    if demand == 'stop_demand':
                        if demand_value:
                            self.heli.stop()
                            self.flying = False
                            # This call blocks, so we can't do any processing anyway
                            # Don't stop processing in this thread just yet in case we still need to do something on the other controls
                    if demand == 'start_demand':
                        # self.heli.start_motor()
                        # Motor started before we're 'flying', so do nothing now...
                        pass
                    if demand == 'throttle_demand':
                        # Need to blend the throttle and blade pitch - increment throttle to match demand if above the threshold
                        throttle_demand = max(
                            self._min_throttle, abs(demand_value)
                        )  # Make sure that the throttle is always at least _min_throttle, and set it equal to the magnitude of the demand
                        if self.flying:
                            # Update the motor speed
                            self.heli.motor.set_motor_speed(throttle_demand)
                            # Update the swash plate position
                            self.heli.swash_plate.set_height(demand_value)
                    if demand == 'yaw_demand':
                        current_yaw_rate = gyro_rates[2]
                        demand_delta = demand_value - current_yaw_rate
                        # Only take action if we're outside the threshold range
                        if demand_delta > self._yaw_threshold:
                            print("Turning more left")
                            self.heli.turn_more_left()
                        elif demand_delta < -self._yaw_threshold:
                            print("Turning more right")
                            self.heli.turn_more_right()
                    if demand == 'pitch_demand':
                        pass
                    if demand == 'roll_demand':
                        pass
                    if demand == 'request_gyro_state_demand':
                        if demand_value:
                            print(
                                f"Gyro rates: {gyro_rates}, accelerations: {accelerations}"
                            )

    def stop_flying(self):
        """ Cleanly and safely shut down the helicopter """
        self.heli.stop()
        self.thread_running = False
Example #9
0
terminal2 = Terminal(2, "T2")
terminal2.add_airport(airport1)

flight1 = Flight("1", "India", "01/05/2019")
flight1.add_terminal(terminal1)

flight2 = Flight("2", "California", "20/07/2019")
flight2.add_terminal(terminal1)

flight3 = Flight("3", "St. Lucia", "23/10/2019")
flight3.add_terminal(terminal2)

flight4 = Flight("4", "Paris", "11/11/2019")
flight4.add_terminal(terminal2)

flight5 = Flight("5", "Australia", "05/10/2019", True)

helicopter1 = Helicopter("H101",)

plane1 = Plane("P001")
plane1.add_flight(flight1)
plane1.add_flight(flight3)

plane2 = Plane("P002")
plane2.add_flight(flight2)
plane2.add_flight(flight4)