Пример #1
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND
            if ((event.type == KEYDOWN or event.type == KEYUP)
                    and self.keyDict.has_key(event.key)):
                if event.type == KEYDOWN:
                    inp = self.keyDict[event.key]
                elif event.type == KEYUP:
                    keyDown = key.get_pressed()
                    if (keyDown[self.commandDict[UP]]):
                        inp = UP
                    elif (keyDown[self.commandDict[DOWN]]):
                        inp = DOWN
                    elif (keyDown[self.commandDict[LEFT]]):
                        inp = LEFT
                    elif (keyDown[self.commandDict[RIGHT]]):
                        inp = RIGHT
                    else:
                        inp = STOP
                else:
                    raise UnexpectedInput
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
Пример #2
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND
            if ((event.type == KEYDOWN or event.type == KEYUP)
                and self.keyDict.has_key(event.key)):
                if event.type == KEYDOWN:
                    inp = self.keyDict[event.key]
                elif event.type == KEYUP:
                    keyDown = key.get_pressed()
                    if(keyDown[self.commandDict[UP]]):
                        inp = UP
                    elif(keyDown[self.commandDict[DOWN]]):
                        inp = DOWN
                    elif(keyDown[self.commandDict[LEFT]]):
                        inp = LEFT
                    elif(keyDown[self.commandDict[RIGHT]]):
                        inp = RIGHT
                    else:
                        inp = STOP
                else:
                    raise UnexpectedInput
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
Пример #3
0
    def run(self):
        self.serial = serial.Serial(self.port-1)
        self.serial.setBaudrate(9600)

        temp = ""
        recving = False

        while self.running:
            e.pump()
            rx = self.serial.read(1)
            
            if rx == "[":
                recving = True
            elif rx == "]":
                try:
                    recving = False
                    x = temp.split(":")
                    key = x[0].strip()
                    value = x[1].strip()
                    self.msgs[key] = eval(value)
                    temp = ""
                except:
                    temp = ""
                    recving = False
            elif recving==True:
                temp = temp + rx

        self.serial.close()
    def on_execute(self):
        global game_state

        if self.on_init() is False:
            self._running = False

        # run and unload loading screen
        su.game_state = su.GameState.LOADING
        self.loading_screen.run(self._display_surf)
        self.loading_screen = None
        # Displays intro message
        fb.show_info_feedback(WELCOME)

        su.game_state = su.GameState.MAIN_LOOP
        while (self._running and su.game_state == su.GameState.MAIN_LOOP):
            event.pump()
            keys = key.get_pressed()

            self.on_event(keys, event)
            self.on_loop()
            self.on_render()

        if su.game_state == su.GameState.WON:
            self.game_won()

        self.on_cleanup()
Пример #5
0
def main(sprites=[]):
    """ Test function """
    # pylint: disable= global-statement
    # Why is there a global statement that I'm not allowed to use?
    global screen
    global width
    global height
    game = True
    while game:
        ev.pump()
        for event in ev.get():
            if event.type == QUIT:
                game = False
                pygame.display.quit()
                log(__name__, "exiting")
                exit(1)
            elif event.type == VIDEORESIZE:
                width, height = event.dict['size']
                screen = pygame.display.set_mode(
                    (width, height), HWSURFACE | DOUBLEBUF | RESIZABLE)
                # pylint: disable=expression-not-assigned
                # Don't want this to be assigned.
                [sprite.resize(width, height) for sprite in sprites]
            print event

        screen.fill((randint(1, 255), randint(1, 255), randint(1, 255)))
        pygame.display.flip()
Пример #6
0
def main():
	pygame.init()

	print("Initiating mobotctl.")

	sticks = joystick.get_count()

	if sticks <= 0:
		print("Error: gamepad not connected.")

	pad = joystick.Joystick(0)
	pad.init()

	axes = []
	buttons = []

	while True:

		event.pump()
	
		for a in range(pad.get_numaxes()):
		
				
		for b in range(pad.get_numbuttons())	


if __name__ == "__main__":

	main()
    def next_frame(self, action):
        pump()
        reward = 0.1
        terminal = False
        # Check input action
        if action == 1:
            self.current_velocity_y = self.upward_speed
            self.is_flapped = True

        # Update score
        bird_center_x = self.bird_x + self.bird_width / 2
        for pipe in self.pipes:
            pipe_center_x = pipe["x_upper"] + self.pipe_width / 2
            if pipe_center_x < bird_center_x < pipe_center_x + 5:
                self.score += 1
                reward = 1
                break

        # Update index and iteration
        if (self.iter + 1) % 3 == 0:
            self.bird_index = next(self.bird_index_generator)
            self.iter = 0
        self.base_x = -((-self.base_x + 100) % self.base_shift)

        # Update bird's position
        if self.current_velocity_y < self.max_velocity_y and not self.is_flapped:
            self.current_velocity_y += self.downward_speed
        if self.is_flapped:
            self.is_flapped = False
        self.bird_y += min(self.current_velocity_y, self.bird_y - self.current_velocity_y - self.bird_height)
        if self.bird_y < 0:
            self.bird_y = 0

        # Update pipes' position
        for pipe in self.pipes:
            pipe["x_upper"] += self.pipe_velocity_x
            pipe["x_lower"] += self.pipe_velocity_x
        # Update pipes
        if 0 < self.pipes[0]["x_lower"] < 5:
            self.pipes.append(self.generate_pipe())
        if self.pipes[0]["x_lower"] < -self.pipe_width:
            del self.pipes[0]
        if self.is_collided():
            terminal = True
            reward = -1
            self.__init__()

        # Draw everything
        if self.screen is not None:
            self.screen.blit(self.background_image, (0, 0))
            self.screen.blit(self.base_image, (self.base_x, self.base_y))
            self.screen.blit(self.bird_images[self.bird_index], (self.bird_x, self.bird_y))
            for pipe in self.pipes:
                self.screen.blit(self.pipe_images[0], (pipe["x_upper"], pipe["y_upper"]))
                self.screen.blit(self.pipe_images[1], (pipe["x_lower"], pipe["y_lower"]))
        image = array3d(display.get_surface())
        display.update()
        self.fps_clock.tick(self.fps)
        return image, reward, terminal
Пример #8
0
    def EkrandaGoruntuOlustur(self):

        Olay.pump()

        OyunEkrani.fill(RGBSiyahRenk)

        RaketOlustur("Ajan", self.AjanRaketYEkseni)
        RaketOlustur("Normal", self.NormalRaketYEkseni)

        TopOlustur(self.TopXEkseni, self.TopYEkseni)

        Goruntule.flip()
Пример #9
0
 def dispatch_events(self):
     if self.enabled:
         subscribers = self.subscribers
         for evt in event.get():
             kind = evt.type
             if kind in subscribers:
                 for subscriber in subscribers[kind]:
                     self.print_debug("Passing {0} to {1}".\
                                                format(evt, subscriber))
                     subscriber(evt)
     else:
         event.pump()
Пример #10
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND

            elif (event.dict
                and event.dict.has_key('joy')
                and event.dict['joy'] == self.joyEnabled.get_id()):
                if event.type == JOYBUTTONDOWN:
                    if self.joyEnabled.get_button(0):
                        inp = BOMB
                    elif self.joyEnabled.get_button(1):
                        inp = ACTION
                elif event.type == JOYAXISMOTION:
                    if self.joyEnabled.get_numaxes() >= 6:
                        if self.joyEnabled.get_axis(5) > 0.2:
                            inp = DOWN
                        elif self.joyEnabled.get_axis(5) < -0.2:
                            inp = UP
                        elif self.joyEnabled.get_axis(4) < -0.2:
                            inp = LEFT
                        elif self.joyEnabled.get_axis(4) > 0.2:
                            inp = RIGHT
                        elif self.joyEnabled.get_axis(5) <= 0.1 and\
                                 self.joyEnabled.get_axis(5) >= -0.1 and\
                                 self.joyEnabled.get_axis(4) <= 0.1 and\
                                 self.joyEnabled.get_axis(4) >= -0.1:
                            inp = STOP
                    
                    if self.joyEnabled.get_axis(1) > 0.2:
                        inp = DOWN
                    elif self.joyEnabled.get_axis(1) < -0.2:
                        inp = UP
                    elif self.joyEnabled.get_axis(0) < -0.2:
                        inp = LEFT
                    elif self.joyEnabled.get_axis(0) > 0.2:
                        inp = RIGHT
                    elif self.joyEnabled.get_axis(0) <= 0.1 and\
                             self.joyEnabled.get_axis(0) >= -0.1 and\
                             self.joyEnabled.get_axis(1) <= 0.1 and\
                             self.joyEnabled.get_axis(1) >= -0.1:
                        inp = STOP
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
Пример #11
0
def main():
    pygame.init()
    screen = display.set_mode((800, 600))

    init(screen)

    running = True

    while running:
        screen.fill(BLACK)
        update(screen)
        display.update()
        event.pump()
Пример #12
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND

            elif (event.dict and event.dict.has_key('joy')
                  and event.dict['joy'] == self.joyEnabled.get_id()):
                if event.type == JOYBUTTONDOWN:
                    if self.joyEnabled.get_button(0):
                        inp = BOMB
                    elif self.joyEnabled.get_button(1):
                        inp = ACTION
                elif event.type == JOYAXISMOTION:
                    if self.joyEnabled.get_numaxes() >= 6:
                        if self.joyEnabled.get_axis(5) > 0.2:
                            inp = DOWN
                        elif self.joyEnabled.get_axis(5) < -0.2:
                            inp = UP
                        elif self.joyEnabled.get_axis(4) < -0.2:
                            inp = LEFT
                        elif self.joyEnabled.get_axis(4) > 0.2:
                            inp = RIGHT
                        elif self.joyEnabled.get_axis(5) <= 0.1 and\
                                 self.joyEnabled.get_axis(5) >= -0.1 and\
                                 self.joyEnabled.get_axis(4) <= 0.1 and\
                                 self.joyEnabled.get_axis(4) >= -0.1:
                            inp = STOP

                    if self.joyEnabled.get_axis(1) > 0.2:
                        inp = DOWN
                    elif self.joyEnabled.get_axis(1) < -0.2:
                        inp = UP
                    elif self.joyEnabled.get_axis(0) < -0.2:
                        inp = LEFT
                    elif self.joyEnabled.get_axis(0) > 0.2:
                        inp = RIGHT
                    elif self.joyEnabled.get_axis(0) <= 0.1 and\
                             self.joyEnabled.get_axis(0) >= -0.1 and\
                             self.joyEnabled.get_axis(1) <= 0.1 and\
                             self.joyEnabled.get_axis(1) >= -0.1:
                        inp = STOP
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
Пример #13
0
    def _update(self):
        """not finished, please leave - Jonathan"""
        event.pump()
        keys = key.get_pressed()
        if keys[K_LEFT]:
            self.left()
        elif keys[K_RIGHT]:
            self.right()

        if keys[K_SPACE]:
            self.jump()

        if self.walk_force:
            self.do_walk()
Пример #14
0
    def _update(self):
        """not finished, please leave - Jonathan"""
        event.pump()
        keys = key.get_pressed()
        if keys[K_LEFT]:
            self.left()
        elif keys[K_RIGHT]:
            self.right()

        if keys[K_SPACE]:
            self.jump()

        if self.walk_force:
            self.do_walk()
Пример #15
0
    def test_issue_208(self):
        """PATCH: pygame.scrap on X11, fix copying into PRIMARY selection

           Copying into theX11 PRIMARY selection (mouse copy/paste) would not
           work due to a confusion between content type and clipboard type.

        """

        from pygame import display, event, freetype
        from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT
        from pygame.locals import KEYDOWN, K_y, QUIT

        success = False
        freetype.init()
        font = freetype.Font(None, 24)
        display.init()
        display.set_caption("Interactive X11 Paste Test")
        screen = display.set_mode((600, 200))
        screen.fill(pygame.Color("white"))
        text = "Scrap put() succeeded."
        msg = (
            "Some text has been placed into the X11 clipboard."
            " Please click the center mouse button in an open"
            " text window to retrieve it."
            '\n\nDid you get "{}"? (y/n)'
        ).format(text)
        word_wrap(screen, msg, font, 6)
        display.flip()
        event.pump()
        scrap.init()
        scrap.set_mode(SCRAP_SELECTION)
        scrap.put(SCRAP_TEXT, text.encode("UTF-8"))
        while True:
            e = event.wait()
            if e.type == QUIT:
                break
            if e.type == KEYDOWN:
                success = e.key == K_y
                break
        pygame.display.quit()
        self.assertTrue(success)
Пример #16
0
    def test_issue_208(self):
        """PATCH: pygame.scrap on X11, fix copying into PRIMARY selection

           Copying into theX11 PRIMARY selection (mouse copy/paste) would not
           work due to a confusion between content type and clipboard type.

        """

        from pygame import display, event, freetype
        from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT
        from pygame.locals import KEYDOWN, K_y, QUIT

        success = False
        freetype.init()
        font = freetype.Font(None, 24)
        display.init()
        display.set_caption("Interactive X11 Paste Test")
        screen = display.set_mode((600, 200))
        screen.fill(pygame.Color("white"))
        text = "Scrap put() succeeded."
        msg = (
            "Some text has been placed into the X11 clipboard."
            " Please click the center mouse button in an open"
            " text window to retrieve it."
            '\n\nDid you get "{}"? (y/n)'
        ).format(text)
        word_wrap(screen, msg, font, 6)
        display.flip()
        event.pump()
        scrap.init()
        scrap.set_mode(SCRAP_SELECTION)
        scrap.put(SCRAP_TEXT, text.encode("UTF-8"))
        while True:
            e = event.wait()
            if e.type == QUIT:
                break
            if e.type == KEYDOWN:
                success = e.key == K_y
                break
        pygame.display.quit()
        self.assertTrue(success)
Пример #17
0
    def HareketEttir(self, Aksiyon):

        Olay.pump()

        Skor = 0

        OyunEkrani.fill(RGBSiyahRenk)

        self.AjanRaketYEkseni = RaketGuncelle("Ajan", Aksiyon,
                                              self.AjanRaketYEkseni,
                                              self.TopYEkseni)
        RaketOlustur("Ajan", self.AjanRaketYEkseni)

        self.NormalRaketYEkseni = RaketGuncelle("Normal", Aksiyon,
                                                self.NormalRaketYEkseni,
                                                self.TopYEkseni)
        RaketOlustur("Normal", self.NormalRaketYEkseni)

        [Skor, self.TopXEkseni, self.TopYEkseni, self.TopXYonu,
         self.TopYYonu] = TopGuncelle(self.AjanRaketYEkseni,
                                      self.NormalRaketYEkseni, self.TopXEkseni,
                                      self.TopYEkseni, self.TopXYonu,
                                      self.TopYYonu)

        TopOlustur(self.TopXEkseni, self.TopYEkseni)

        if Skor == 0.05:
            self.AjanSkor += 1
        if Skor == -10:
            self.NormalSkor += 1

        if (Skor > 0.5 or Skor < -0.5):
            self.OyunSkor = self.OyunSkor * 0.9 + 0.1 * Skor

        EkranGoruntusu = DiziEkran.array3d(Goruntule.get_surface())
        SkorYazdir(OyunEkrani, str(self.AjanSkor), 0)
        SkorYazdir(OyunEkrani, str(self.NormalSkor), 1)
        Goruntule.flip()

        return [Skor, EkranGoruntusu]
Пример #18
0
def main():
    pygame.init()
    screen = display.set_mode((CELL_SIZE*GRID_SIZE, CELL_SIZE*GRID_SIZE))

    # On commence avec un écran de la couleur par défaut (blanc)
    screen.fill(COLORS[0])

    running = False

    # On ne lance le jeu que si le serveur est joignable
    try:
        game = Game(screen)
        running = True
    except requests.exceptions.ConnectionError:
        print('Impossible de joindre le serveur, veuillez relancer le jeu')

    while running:
        # event.pump() permet de dire à PyGame de gérer les évènements
        event.pump()

        # Dans ce projet, on n'efface pas l'écran à chaque frame du coup

        game.update()
        display.update()
Пример #19
0
    def next_frame(self, action):
        pump()
        reward = 0.01
        terminal = False
        # Check input action
        self.current_velocity_x = action

        if self.is_flapped:
            self.is_flapped = False
        if self.state == 1:
            self.current_velocity_y = self.floor_velocity_y
        elif self.state == 2:
        	self.current_velocity_y = -4
        else:
            self.current_velocity_y = max(min(-1,self.current_velocity_y-1),self.min_velocity_y)
        #print(self.state,self.current_velocity_y)
        self.man_y -= self.current_velocity_y
        self.man_x = min(max(0,self.man_x+self.current_velocity_x),self.screen_width-self.man_width)
        if(self.man_x == 0 or self.man_x == self.screen_width-self.man_width):
            reward -=1
        # Update pipes' position
        for floor in self.floors:
            #print(floor["y"],self.floor_velocity_y)
            floor["y"] -= self.floor_velocity_y
        # Update pipes
        if self.floors[0]["y"] < 0:
            self.floors.append(self.generate_floor())
            del self.floors[0]
        
        is_collided, floor = self.is_collided()
        if (self.state2_counter==0):
	        if self.man_y >=self.screen_height:
	        	self.state = 3
	        	terminal = True
	        	reward = -1
	        	self.__init__()
	        elif self.man_y <=0:
	        	self.state = 2
	        	self.state2_counter = 10
	        	reward = -0.2
	        elif is_collided:
	            self.man_y = floor['y']-28
	            self.state = 1
	            reward = 0.4
	        else:
	            self.state = 0
	            #reward = -1
        else:
            self.state2_counter = max(0,self.state2_counter-1)

        # Draw everything
        self.screen.blit(self.background_image, (0, 0))
        #self.screen.blit(self.base_image, (self.base_x, self.base_y))
        self.screen.blit(self.man_images[0], (self.man_x, self.man_y))
        for floor in self.floors:
            self.screen.blit(self.floor_images[0], (floor["x"], floor["y"]))
            #self.screen.blit(self.pipe_images[1], (pipe["x_lower"], pipe["y_lower"]))
        image = array3d(display.get_surface())
        display.update()
        self.fps_clock.tick(self.fps)
        return image, reward, terminal
    def _update(self):
        """Timer callback function."""
        event.pump()

        """LEFT DRIVE"""
        if self.left_drive['control'] == 0:
            left_drive_stick = self.primary
        else:
            left_drive_stick = self.secondary
        left_raw = left_drive_stick.get_axis(self.left_drive['axis'])
        left_out = self.expo(left_raw, self.left_drive['expo'])
        if self.left_drive['invert']: left_out = -1.0 * left_out

        """RIGHT DRIVE"""
        if self.right_drive['control'] == 0:
            right_drive_stick = self.primary
        else:
            right_drive_stick = self.secondary
        right_raw = right_drive_stick.get_axis(self.right_drive['axis'])
        right_out = self.expo(right_raw, self.right_drive['expo'])
        if self.right_drive['invert']: right_out = -1.0 * right_out

        self.controller.drive_command(left_out, right_out)

        """ARM AZIMUTH"""
        if self.arm_azimuth['control'] == 0:
            arm_azimuth_stick = self.primary
        else:
            arm_azimuth_stick = self.secondary
        azimuth_raw = arm_azimuth_stick.get_axis(self.arm_azimuth['axis'])
        azimuth_out = self.expo(azimuth_raw, self.arm_azimuth['expo'])
        if self.arm_azimuth['invert']: azimuth_out = -1.0 * azimuth_out

        """ARM SHOULDER"""
        if self.arm_shoulder['control'] == 0:
            arm_shoulder_stick = self.primary
        else:
            arm_shoulder_stick = self.secondary
        shoulder_raw = arm_shoulder_stick.get_axis(self.arm_shoulder['axis'])
        shoulder_out = self.expo(shoulder_raw, self.arm_shoulder['expo'])
        if self.arm_shoulder['invert']: shoulder_out = -1.0 * shoulder_out

        """ARM ELBOW"""
        if self.arm_elbow['control'] == 0:
            arm_elbow_stick = self.primary
        else:
            arm_elbow_stick = self.secondary
        elbow_raw = arm_elbow_stick.get_axis(self.arm_elbow['axis'])
        elbow_out = self.expo(elbow_raw, self.arm_elbow['expo'])
        if self.arm_elbow['invert']: elbow_out = -1.0 * elbow_out

        self.controller.arm_speed_command(azimuth_out, shoulder_out, elbow_out)

        """CAMERA PAN"""
        if self.camera_pan['control'] == 0:
            camera_pan_stick = self.primary
        else:
            camera_pan_stick = self.secondary

        if self.camera_pan['use_axis']:
            pan_raw = camera_pan_stick.get_axis(self.camera_pan['axis'])
            pan_out = self.expo(pan_raw, self.camera_pan['expo'])
            if self.camera_pan['invert']:
                pan_out *= -1.0
        else:
            # pressing both buttons causes them to cancel out
            # subtract since buttons are labeled starting at 1, indexed starting at 0
            pan_raw = camera_pan_stick.get_button(self.camera_pan['button_p'] - 1) - \
                      camera_pan_stick.get_button(self.camera_pan['button_n'] - 1)
            pan_out = pan_raw * self.camera_pan['button_speed']

        """CAMERA TILT"""
        if self.camera_tilt['control'] == 0:
            camera_tilt_stick = self.primary
        else:
            camera_tilt_stick = self.secondary

        if self.camera_tilt['use_axis']:
            tilt_raw = camera_tilt_stick.get_axis(self.camera_tilt['axis'])
            tilt_out = self.expo(tilt_raw, self.camera_tilt['expo'])
            if self.camera_tilt['invert']:
                tilt_out *= -1.0
        else:
            # pressing both buttons causes them to cancel out
            # subtract since buttons are labeled starting at 1, indexed starting at 0
            tilt_raw = camera_tilt_stick.get_button(self.camera_tilt['button_p'] - 1) - \
                       camera_tilt_stick.get_button(self.camera_tilt['button_n'] - 1)
            tilt_out = tilt_raw * self.camera_tilt['button_speed']

        self.controller.camera_pos_command(pan_out, tilt_out)
Пример #21
0
    def next_frame(self, action, text=''):
        pump()
        reward = 1
        terminal = False
        # Check input action
        if action == 0:  # 0 means flap
            self.current_velocity_y = self.upward_speed
            self.is_flapped = True

        # Update score
        bird_center_x = self.bird_x + self.bird_width / 2
        for pipe in self.pipes:
            pipe_center_x = pipe["x_upper"] + self.pipe_width / 2
            if pipe_center_x < bird_center_x < pipe_center_x + 5:
                self.score += 1
                break

        # get detal_x, detal_y
        for pipe in self.pipes:
            if self.bird_x < pipe["x_lower"] + self.pipe_width:
                detal_x = pipe['x_lower'] + self.pipe_width - self.bird_x
                detal_y = pipe['y_lower'] - self.bird_y + self.bird_height

                # a triangle
                points = ((self.bird_x, self.bird_y + self.bird_height),
                          (pipe['x_lower'] + self.pipe_width,
                           pipe['y_lower']), (self.bird_x, pipe['y_lower']))
                break

        # Update index and iteration
        if (self.iter + 1) % 3 == 0:
            self.bird_index = next(self.bird_index_generator)
            self.iter = 0
        self.base_x = -((-self.base_x + 100) % self.base_shift)

        # Update bird's position
        if self.current_velocity_y < self.max_velocity_y and not self.is_flapped:
            self.current_velocity_y += self.downward_speed
        if self.is_flapped:
            self.is_flapped = False
        self.bird_y += min(
            self.current_velocity_y,
            self.bird_y - self.current_velocity_y - self.bird_height)
        if self.bird_y < 0:
            self.bird_y = 0

        # Update pipes' position
        for pipe in self.pipes:
            pipe["x_upper"] += self.pipe_velocity_x
            pipe["x_lower"] += self.pipe_velocity_x
        # Update pipes
        if 0 < self.pipes[0]["x_lower"] < 5:
            self.pipes.append(self.generate_pipe())
        if self.pipes[0]["x_lower"] < -self.pipe_width:
            del self.pipes[0]
        if self.is_collided():
            terminal = True
            reward = -1000
            self.__init__()

        # show info
        font = pygame.font.Font('freesansbold.ttf', 20)
        info = font.render(text, False, (255, 200, 10))

        # Draw everything
        self.screen.blit(self.background_image, (0, 0))
        self.screen.blit(self.base_image, (self.base_x, self.base_y))
        self.screen.blit(self.bird_images[self.bird_index],
                         (self.bird_x, self.bird_y))
        for pipe in self.pipes:
            self.screen.blit(self.pipe_images[0],
                             (pipe["x_upper"], pipe["y_upper"]))
            self.screen.blit(self.pipe_images[1],
                             (pipe["x_lower"], pipe["y_lower"]))
        self.screen.blit(info, (0, 100))
        pygame.draw.polygon(display.get_surface(), (255, 0, 0),
                            points,
                            width=1)

        image = array3d(display.get_surface())
        display.update()
        self.fps_clock.tick(self.fps)

        return image, reward, terminal, self.score, str(
            (int(detal_x / 4), int(detal_y / 4)))
Пример #22
0
def yield_api_events() -> None:
    api_events.pump()
Пример #23
0
def main(background_layers=[],
         foreground_layers=[],
         sprites=[],
         text=None,
         sprite_groups=None,
         tiles=[],
         base_sprite=None,
         **kwargs):
    """Main game loop handles the running of the game. """
    global SCREEN
    global BLANK_SCREEN
    text_queue = ["Hello Game", "How are you today?"]
    game = True
    clock = pygame.time.Clock()
    rect_list = []
    tile_previews = [load_tile(tile) for tile in tiles]
    try:
        current_background_dump = load_background('level.yml')
        if current_background_dump is None:
            current_background_dump = []
    except IOError:
        current_background_dump = []
        log(__name__, 'load failed')
    current_tile = 0
    sudo_clock = 0
    play_song('grosse.ogg')
    while game:
        ev.pump()
        blocking = []
        position = pygame.mouse.get_pos()
        grid_position = position_to_grid(position[0], position[1])
        cursor = pygame.Rect(grid_position[0], grid_position[1], SPACING,
                             SPACING)
        rect_list.append(cursor)

        for event in ev.get():
            if event.type == QUIT:
                game = False
                save_background("level.yml", current_background_dump)
                pygame.display.quit()
                log(__name__, "exiting")
                exit(1)

            elif event.type == VIDEORESIZE:
                width, height = event.dict['size']
                SCREEN = pygame.display.set_mode((width, height),
                                                 DOUBLEBUF | RESIZABLE, 12)
                BLANK_SCREEN = pygame.Surface((width, height))
                BLANK_SCREEN.fill((255, 255, 255))

                # pylint: disable=expression-not-assigned
                # Don't want this assigned
                [sprite.resize(width, height) for sprite in sprites]
                text.resize(width, height)

            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 4:
                    current_tile = scroll(current_tile, tiles)
                elif event.button == 5:
                    current_tile = scroll(current_tile, tiles, -1)
                else:
                    states_copy = {}
                    for state in tiles[current_tile]['states']:
                        states_copy[state] = list(
                            tiles[current_tile]['states'][state])
                    new_tile = base_sprite(**tiles[current_tile])
                    new_tile.i = int(grid_position[0] - X)
                    new_tile.j = int(grid_position[1] - Y)
                    background_layers.append(new_tile)
                    tiles[current_tile]['states'] = states_copy
                    tile_copy = dict(tiles[current_tile])
                    tile_copy["i"] = int(grid_position[0] - X)
                    tile_copy["j"] = int(grid_position[1] - Y)
                    current_background_dump.append(deepcopy(tile_copy))

            elif event.type == KEYDOWN:
                if event.scancode in KEY_MAP["up"]:
                    ev.post(ev.Event(20, {"up": True}))
                elif event.scancode in KEY_MAP["down"]:
                    ev.post(ev.Event(20, {"down": True}))
                elif event.scancode in KEY_MAP["left"]:
                    ev.post(ev.Event(20, {"left": True}))
                elif event.scancode in KEY_MAP["right"]:
                    ev.post(ev.Event(20, {"right": True}))
                if event.scancode in KEY_MAP["attack"]:
                    ev.post(ev.Event(20, {"attack": True}))
                if event.scancode in KEY_MAP["back"]:
                    ev.post(ev.Event(20, {"back": True}))

            elif event.type == KEYUP:
                if event.scancode in KEY_MAP["up"]:
                    ev.post(ev.Event(20, {"up": False}))
                elif event.scancode in KEY_MAP["down"]:
                    ev.post(ev.Event(20, {"down": False}))
                elif event.scancode in KEY_MAP["left"]:
                    ev.post(ev.Event(20, {"left": False}))
                elif event.scancode in KEY_MAP["right"]:
                    ev.post(ev.Event(20, {"right": False}))
                if event.scancode in KEY_MAP["attack"]:
                    ev.post(ev.Event(20, {"attack": False}))
                if event.scancode in KEY_MAP["back"]:
                    ev.post(ev.Event(20, {"back": False}))

            elif event.type == 20:
                log(__name__, event)
                direction = event.dict.keys()[0]
                ACTIONS[direction] = event.dict[direction]

        for layer in background_layers:
            layer.update(sudo_clock / 10)
        sprites = sorted(sprites, None, lambda sprite:
                         (sprite.rect.y, sprite.rect.x))
        #grid(screen, rect_list, 640, 480)
        for sprite in sprites:
            sprite_pass_back = sprite.update(sudo_clock / 10)
            #pygame.draw.rect(screen, (0,0,255), sprite.rect)
            rect_list.append(sprite.rect)

            if sprite_pass_back.get('text'):
                text_queue.append(sprite_pass_back['text'])
            for group in sprite_groups:
                if sprite in group:
                    group.remove(sprite)
                    collision = pygame.sprite.spritecollideany(sprite, group)
                    if collision:
                        if sprite.collide(collision.rect):
                            for collision in pygame.sprite.groupcollide(
                                    sprite_groups[1], sprite_groups[0], False,
                                    False)[sprite]:
                                #pygame.draw.rect(screen, (255,0,0,40), collision.rect)
                                #pygame.draw.line(
                                #    SCREEN,
                                #    (255, 128, 40),
                                #    sprite.rect.center,
                                #    collision.rect.center,
                                #    5)
                                if collision.children.get("col"):
                                    if collision.rect.collidepoint(sprite.rect.midbottom) or \
                                        collision.rect.collidepoint(sprite.rect.bottomright) or  \
                                        collision.rect.collidepoint(sprite.rect.bottomleft):
                                        col = [
                                            WIDTH / 2 - X - 16 - 2,
                                            HEIGHT / 2 - Y + 16
                                        ]
                                        collision.children["col"].i, collision.children["col"].j \
                                                = col
                                        collision.children["col"].update(
                                            sudo_clock / 10)
                                        rect_list.append(
                                            collision.children["col"].rect)
                                blocking += sprite.collide(collision.rect)
                    group.add(sprite)
        for layer in foreground_layers:
            layer.update(sudo_clock / 10)
        text_queue = text.update(text_queue)
        #grid(screen, rect_list, 640, 480)
        able_to_move = check_move(blocking)
        check_blocking(blocking)
        #crt_tv(screen, rect_list, 640, 480)
        pygame.draw.rect(SCREEN, (255, 128, 56), cursor, 0)
        rect_list = draw_tile_previews(SCREEN,
                                       WIDTH,
                                       tile_previews,
                                       rect_list,
                                       selected=current_tile)
        pygame.display.update(rect_list)
        if able_to_move:
            #screen.fill((randint(1,255), randint(1,255), randint(1,255)))
            pass
        SCREEN.fill((0, 0, 0, 0))
        # pygame.display.update(rect_list)
        clock.tick(40)
        game_info = "mouse: {m_x} , {m_y}, pos: {x}, {y} fps: {fps}, tile: {tile}".format(
            m_x=cursor.x,
            m_y=cursor.y,
            x=X,
            y=Y,
            fps=clock.get_fps(),
            tile=tiles[current_tile].get("name"))
        pygame.display.set_caption(game_info)
        sudo_clock += 1
Пример #24
0
def pumpMessage():
    init()
    while True:
        pump()
Пример #25
0
    def next_frame(self, action):
        pump()
        reward = 0.1
        terminal = False
        if action == 1:
            self.current_velocity_y = self.playerFlapAcc
            self.is_flapped = True
            # SOUNDS['wing'].play()

        playerMidPos = self.player_x + IMAGES['player'][0].get_width() / 2
        for pipe in self.upperPipes:
            pipeMidPos = pipe['x'] + IMAGES['pipe'][0].get_width() / 2
            if pipeMidPos <= playerMidPos < pipeMidPos + 4:
                self.score += 1
                SOUNDS['point'].play()
                reward = 1

        if (self.iter + 1) % 3 == 0:
            self.player_index = next(self.playerIndexGen)
            self.iter = 0
        # self.iter = (self.iter + 1) % 30
        self.base_x = -((-self.base_x + 100) % self.baseShift)

        # if self.playerRot > -90:
        #     self.playerRot -= self.playerVelRot

        if self.current_velocity_y < 10 and not self.is_flapped:
            self.current_velocity_y += 1
        if self.is_flapped:
            self.is_flapped = False
            # self.playerRot = 45
        self.player_y += min(
            self.current_velocity_y,
            self.player_y - self.current_velocity_y - self.player_height)
        if self.player_y < 0:
            self.player_y = 0

        # self.player_height = IMAGES['player'][self.player_index].get_height()

        for uPipe, lPipe in zip(self.upperPipes, self.lowerPipes):
            uPipe['x'] += self.pipeVelX
            lPipe['x'] += self.pipeVelX

        # add new pipe when first pipe is about to touch left of screen
        if len(self.upperPipes) > 0 and 0 < self.upperPipes[0]['x'] < 5:
            newPipe = self.getRandomPipe()
            self.upperPipes.append(newPipe[0])
            self.lowerPipes.append(newPipe[1])

        # remove first pipe if its out of the screen
        if len(
                self.upperPipes
        ) > 0 and self.upperPipes[0]['x'] < -IMAGES['pipe'][0].get_width():
            self.upperPipes.pop(0)
            self.lowerPipes.pop(0)

        if self.checkCrash():
            terminal = True
            reward = -1
            self.__init__()

        SCREEN.blit(IMAGES['background'], (0, 0))
        SCREEN.blit(IMAGES['base'], (self.base_x, self.base_y))
        # visibleRot = self.playerRotThr
        # if self.playerRot <= self.playerRotThr:
        #     visibleRot = self.playerRot
        # playerSurface = pygame.transform.rotate(IMAGES['player'][self.player_index], visibleRot)
        self.showScore(self.score)
        SCREEN.blit(IMAGES['player'][self.player_index],
                    (self.player_x, self.player_y))
        for uPipe, lPipe in zip(self.upperPipes, self.lowerPipes):
            SCREEN.blit(IMAGES['pipe'][0], (uPipe['x'], uPipe['y']))
            SCREEN.blit(IMAGES['pipe'][1], (lPipe['x'], lPipe['y']))

        image = array3d(pygame.display.get_surface())
        pygame.display.update()
        FPSCLOCK.tick(FPS)

        return image, reward, terminal