Невозможно помешать игроку полностью уйти влево и фон не будет прокручиваться вверх - PullRequest
0 голосов
/ 07 февраля 2020

У меня была эта проблема некоторое время, и только сейчас я решил попробовать и спросить об этом. По сути, в игре уровень смещает фон влево и вправо, но, тем не менее, есть две основные проблемы, и было бы полезно, если бы любая из них была решена. может продолжать движение, несмотря на то, что там ничего нет и встречается с голубой пустотой.

Когда игрок поднимается, уровень может сместиться вверх, но, тем не менее, фон все еще застрял в своем стационарном состоянии.

И вот соответствующий код:

Основная игра l oop код, где уровень обновляется в зависимости от позиции игрока:

            # Update items in the level
            self.current_level.update()

            # If the player gets near the right side, shift the world left (-x)
            if self.player.rect.x >= 500:
                self.diff = self.player.rect.x - 500
                self.player.rect.x = 500
                self.current_level.shift_world(-self.diff)

            # If the player gets near the left side, shift the world right (+x)
            if self.player.rect.x <= 120:
                self.diff = 120 - self.player.rect.x
                self.player.rect.x = 120
                self.current_level.shift_world(self.diff)

            if self.player.rect.y <= 100:
                self.diff = self.player.rect.y - 100
                self.player.rect.y = 100
                self.current_level.shift_world_vertical(-self.diff)

            if self.player.rect.y > 515:
                self.diff = 515 - self.player.rect.y
                self.player.rect.y = 515
                self.current_level.shift_world_vertical(self.diff)


            # If the player gets to the end of the level, go to the next level
            self.current_position = [self.player.rect.x + self.current_level.world_shift,self.player.rect.y + self.current_level.world_shift_vertical]

И, наконец, соответствующие определения в классе Level:

    def draw(self, screen):
        """ Draw everything on this level. """

        # Draw the background
        # We don't shift the background as much as the sprites are shifted
        # to give a feeling of depth.
        screen.fill(constants.BLUE)
        screen.blit(self.background,(self.world_shift // 3,0))

        # Draw all the sprite lists that we have
        self.platform_list.draw(screen)
        self.enemy_list.draw(screen)

    def shift_world(self, shift_x):
        """ When the user moves left/right and we need to scroll everything: """

        # Keep track of the shift amount
        self.world_shift += shift_x

        # Go through all the sprite lists and shift
        for platform in self.platform_list:
            platform.rect.x += shift_x

        for enemy in self.enemy_list:
            enemy.rect.x += shift_x

    def shift_world_vertical(self, shift_y):
        """ When the user moves left/right and we need to scroll everything: """

        # Keep track of the shift amount
        self.world_shift_vertical += shift_y

        # Go through all the sprite lists and shift
        for platform in self.platform_list:
            platform.rect.y += shift_y

        for enemy in self.enemy_list:
            enemy.rect.y += shift_y

Большое спасибо заранее!

Ниже я решил включить, как мы надеемся, более модульный код, который сможет работать лучше, чем все это содержит игрок, который может двигаться. Для изображения оно должно быть больше экрана, но в остальном все приемлемо. Надеюсь, это поможет другим людям решить мою проблему, еще раз спасибо заранее!

import pygame, sys

"""
Global constants
"""

# Colors
ABLACK   = ( 0, 0, 0, 125)
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
BLUE     = (   0,   0, 255)
YELLOW   = ( 255, 255,   0)

# Screen dimensions
SCREEN_WIDTH  = 800
SCREEN_HEIGHT = 600

class Level():

    world_shift = 0
    world_shift_vertical = 0
    level_limit = -1000

    def __init__(self, player):
        self.player = player

    def draw(self, screen):
        """ Draw everything on this level. """

        # Draw the background
        # We don't shift the background as much as the sprites are shifted
        # to give a feeling of depth.
        screen.fill(BLUE)
        screen.blit(self.background,(self.world_shift // 3,0))

    def shift_world(self, shift_x):
        """ When the user moves left/right and we need to scroll everything: """

        # Keep track of the shift amount
        self.world_shift += shift_x

    def shift_world_vertical(self, shift_y):
        """ When the user moves left/right and we need to scroll everything: """

        # Keep track of the shift amount
        self.world_shift_vertical += shift_y

class Level_01(Level):
    """ Definition for level 1. """

    def __init__(self, player):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self, player)

        self.background = pygame.image.load("background_01.png").convert()
        self.background.set_colorkey(WHITE)
        self.level_limit = -2300

class Player(pygame.sprite.Sprite):
    """ This class represents the bar at the bottom that the player
    controls. """

    # -- Attributes
    # Set speed vector of player
    change_x = 0
    change_y = 0

    def __init__(self):
        """ Constructor function """

        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface([10, 90])
        self.image.fill(YELLOW)

        self.rect = self.image.get_rect()

    def update(self):
        """ Move the player. """
        # Gravity
        self.calc_grav()

        # Move left/right
        self.rect.x += self.change_x

        # Move up/down
        self.rect.y += self.change_y

    def calc_grav(self):
        """ Calculate effect of gravity. """
        if self.change_y == 0:
            self.change_y = 1
        else:
            self.change_y += 0.25

        # See if we are on the ground.
        if self.rect.y >= SCREEN_HEIGHT and self.change_y >= 0:
            self.change_y = 0
            self.rect.y = SCREEN_HEIGHT

    def jump(self):
        """ Called when user hits 'jump' button. """

        # move down a bit and see if there is a platform below us.
        self.change_y = -8.5

    # Player-controlled movement:
    def go_left(self):
        """ Called when the user hits the left arrow. """
        self.change_x = -6

    def go_right(self):
        """ Called when the user hits the right arrow. """
        self.change_x = 6

    def stop(self):
        """ Called when the user lets off the keyboard. """
        self.change_x = 0

class Game(object):

    def __init__(self):

        self.size = [SCREEN_WIDTH, SCREEN_HEIGHT]
        self.pauseScreen = pygame.Surface(self.size,pygame.SRCALPHA,32)
        # Create the player
        self.player = Player()
        self.current_level = Level_01(self.player)

        self.active_sprite_list = pygame.sprite.Group()
        self.player.level = self.current_level

        self.player.rect.x = 120
        self.player.rect.y = SCREEN_HEIGHT - self.player.rect.height
        self.active_sprite_list.add(self.player)

    def processEvents(self,screen):

        for event in pygame.event.get(): # User did something
            if event.type == pygame.QUIT: # If user clicked close
                return True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    self.player.go_left()
                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    self.player.go_right()
                if event.key == pygame.K_UP or event.key == pygame.K_w:
                    self.player.jump()

            if event.type == pygame.KEYUP:
                if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and self.player.change_x < 0:
                    self.player.stop()
                if (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and self.player.change_x > 0:
                    self.player.stop()

        return False

    def runLogic(self,screen):

        self.active_sprite_list.update()

            # If the player gets near the right side, shift the world left (-x)
        if self.player.rect.x >= 500:
            self.diff = self.player.rect.x - 500
            self.player.rect.x = 500
            self.current_level.shift_world(-self.diff)

            # If the player gets near the left side, shift the world right (+x)
        if self.player.rect.x <= 120:
            self.diff = 120 - self.player.rect.x
            self.player.rect.x = 120
            self.current_level.shift_world(self.diff)

        if self.player.rect.y <= 100:
            self.diff = self.player.rect.y - 100
            self.player.rect.y = 100
            self.current_level.shift_world_vertical(-self.diff)

        if self.player.rect.y > 515:
            self.diff = 515 - self.player.rect.y
            self.player.rect.y = 515
            self.current_level.shift_world_vertical(self.diff)

    def displayFrame(self, screen):

        self.current_level.draw(screen)
        self.active_sprite_list.draw(screen)

        pygame.display.flip()

pygame.init()

pygame.display.set_caption("Scroll Error Finder")

size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)

    #Loop until the user clicks the close button.
done = False

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

game = Game()

while not done:

            # Process events (keystrokes, mouse clicks, etc)
    done = game.processEvents(screen)

        # Update object positions, check for collisions
    game.runLogic(screen)

        # Draw the current frame
    game.displayFrame(screen)

        # Pause for the next frame
    clock.tick(60)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...