Направление движения персонажа Pygame - PullRequest
1 голос
/ 17 января 2020

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

import pygame
from pygame.sprite import Sprite


class Mage:
    """A class that manages the character mage"""

    def __init__(self, ap_game):
        """Initialize the mage and set its starting position."""
        self.neg = 0
        self.screen_window = ap_game.screen_window
        self.settings = ap_game.settings
        self.screen_window_rect = ap_game.screen_window.get_rect()

        # Load images for character walking movement
        self.walk_left = [
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/left_walk1.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/left_walk2.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/left_walk3.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/left_walk4.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/left_walk5.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/left_walk6.bmp")
        ]
        self.walk_right = [
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/walk1.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/walk2.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/walk3.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/walk4.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/walk5.bmp"),
            pygame.image.load("/Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free"
                              "-pixel-art-game-heroes/Mage/Walk/walk6.bmp")
        ]

        # Load the character - mage mage and get its rect.
        image_file = "//Users/johnphillip/Desktop/alien_apocalypse/craftpix-891165-assassin-mage-viking-free-pixel" \
                     "-art-game-heroes/Mage/Walk/standing.bmp"

        self.mage = pygame.image.load(image_file)
        self.rect = self.mage.get_rect()

        # Start each new character at the bottom center of the screen.
        self.rect.midbottom = self.screen_window_rect.midbottom

        # Store the decimal value for the mage's horizontal position.
        self.x = float(self.rect.x)
        # Store the decimal value for the `mage's vertical position.
        self.y = float(self.rect.y)

        # Movement flag
        self.moving_right = False
        self.moving_left = False
        self.jump_move = False
        self.standing = True
        self.walk_count = 0
        self.jump_count = 10

    def update(self):
        """Update the mage's position based on the movement flag."""
        # Update the mage's x value, not the rect
        if self.moving_right and self.rect.right < self.screen_window_rect.right:
            self.x += self.settings.knight_speed
            self.standing = False

        elif self.moving_left and self.rect.left > 0:
            self.x -= self.settings.knight_speed
            self.standing = False

        else:
            self.standing = True
            self.walk_count = 0

        if self.jump_move:
            if self.jump_count >= -10:
                self.neg = 1
                if self.jump_count < 0:
                    self.neg = -1
                self.y -= (self.jump_count ** 2) * 0.5 * self.neg
                self.jump_count -= 1
            else:
                self.jump_count = 10
                self.jump_move = False

        # Update rect object from self.x.
        self.rect.x = self.x
        # Update rect object from self.y.
        self.rect.y = self.y

    def blitme(self):
        """Draw the character at its current location."""
        if self.walk_count + 1 >= 18:
            self.walk_count = 0

        if not self.standing:
            if self.moving_left:
                self.screen_window.blit(self.walk_left[self.walk_count // 3], self.rect)
                self.walk_count += 1

            elif self.moving_right:
                self.screen_window.blit(self.walk_right[self.walk_count // 3], self.rect)
                self.walk_count += 1
        else:
            if self.moving_right:
                self.screen_window.blit(self.walk_right[0], self.rect)
            else:
                self.screen_window.blit(self.walk_left[0], self.rect)

Основной скрипт:

import sys
import os
import pygame
from game_settings import GameSettings
from knight import Mage


class AlienApocalypse:
    """Overall class to manage game assets and behaviour"""

    def __init__(self):
        """Initialize the game and create game resources"""
        self.walking_step = 6
        pygame.init()
        self.settings = GameSettings()
        # Set up a clock that regulates the FPS of the game window
        self.clock = pygame.time.Clock()
        self.settings.vertical_momentum = 0

        drivers = ['directfb', 'fbcon', 'svgalib']

        found = False
        for driver in drivers:
            if not os.getenv('SDL_VIDEODRIVER'):
                os.putenv('SDL_VIDEODRIVER', driver)
            try:
                pygame.display.init()
            except pygame.error:
                print('Driver: {0} failed.'.format(driver))
                continue
            found = True
            break

        if not found:
            raise Exception('No suitable video driver found!')

        self.screen_window = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Apocalypse")

        """Setting background color"""
        self.background_color = (0, 0, 255)

        self.mage = Mage(self)

    def run_game(self):
        """Start the main loop for the game"""
        while True:
            self.clock.tick(27)
            self._check_events()
            self.mage.update()
            self._update_screen()

    def _check_events(self):
        """Respond to key presses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_event(event)

            elif event.type == pygame.KEYUP:
                self._check_keyup_event(event)

    def _check_keydown_event(self, event):
        """Respond to KEYDOWN presses"""
        if event.key == pygame.K_RIGHT:
            self.mage.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.mage.moving_left = True
        elif event.key == pygame.K_SPACE:
            self.mage.jump_move = True
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_event(self, event):
        """Respond to KEY releases"""
        if event.key == pygame.K_RIGHT:
            self.mage.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.mage.moving_left = False

    def _update_screen(self):
        # Redraw the screen during each pass through the loop.
        self.screen_window.fill(self.settings.background_color)
        self.mage.blitme()

        # Make the most recently drawn screen visible.
        pygame.display.flip()
        self.clock.tick(60)


if __name__ == "__main__":
    """Make a game instance, and run the game"""
    ap = AlienApocalypse()
    ap.run_game()

Настройки скрипта:

class GameSettings:
    """This class stores all the game settings"""

    def __init__(self):
        """Initialize the game's settings attributes"""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.background_color = (0, 0, 255)
        self.vertical_momentum = 0

        # Knight settings
        self.knight_speed = 2.5

        # Bullet/Sword settings
        self.bullet_speed = 8.0
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = (255, 60, 60)
        # self.facing = facing



1 Ответ

1 голос
/ 17 января 2020

Добавить состояние self.last_move в класс Mage. Установите состояние при перемещении персонажа и нарисуйте россыпь в зависимости от состояния, если self.standing. например:

class Mage:
    def __init__(self, ap_game):
        # [...]

        self.last_move = None

    # [...]

    def blitme(self):
        """Draw the character at its current location."""
        if self.walk_count + 1 >= 18:
            self.walk_count = 0

        if not self.standing:
            if self.moving_left:
                self.screen_window.blit(self.walk_left[self.walk_count // 3], self.rect)
                self.walk_count += 1
                self.last_move = "left"

            elif self.moving_right:
                self.screen_window.blit(self.walk_right[self.walk_count // 3], self.rect)
                self.walk_count += 1
                self.last_move = "right"
        else:
            if self.last_move == "right":
                self.screen_window.blit(self.walk_right[0], self.rect)
            elif self.last_move == "left":
                self.screen_window.blit(self.walk_left[0], self.rect)
            else:
                self.screen_window.blit(self.mage, self.rect)
...