简体   繁体   English

Python pygame sprite在到达屏幕底部后不会向上移动

[英]Python pygame sprite not moving back up after reaching bottom of screen

I'm riffing on an exercise in Python Crash Course v2.我正在复习 Python Crash Course v2 中的一个练习。 I replicated Space Invaders with the alien fleet moving up and down (instead of left and right).我复制了太空入侵者,外星人舰队上下移动(而不是左右移动)。 Now I'm modifying parts of that to create another game with a dog that should move up and down as it reaches the top and bottom of the screen.现在我正在修改其中的一部分来创建另一个游戏,当它到达屏幕的顶部和底部时,它应该上下移动。

Problem: The dog starts at center right, then moves down to the bottom right corner, but does not move back up.问题:狗从右中心开始,然后向下移动到右下角,但没有向上移动。 It jitters down there like it thinks it's reached the top and moved back down really fast.它在那里抖动,好像它认为它已经到达顶部并很快又向下移动。 I've been staring at this off and on for a couple of weeks and would really appreciate some help finding my mistake.我已经断断续续地盯着这个几周了,如果能帮我找到我的错误,我真的很感激。

The code below isolates the dog element in a single .py file.下面的代码将 dog 元素隔离在一个 .py 文件中。 (If you're not using an IDE, edit pygame.QUIT code so it will close gracefully.) (如果您没有使用 IDE,请编辑 pygame.QUIT 代码,使其正常关闭。)

You can get the dog image from the images folder for my [Github for PlayBall pygame][1].Or you can substitute any image about 96 x 56 px.您可以从我的 [Github for PlayBall pygame][1] 的图像文件夹中获取狗图像。或者您可以替换任何大约 96 x 56 像素的图像。

# -*- coding: utf-8 -*-
"""
Created on Mon Aug 31 19:25:26 2020

@author: Cathig
"""

import sys
import pygame
import pygame.font

class Settings:
    """A class to store all settings for Play Catch."""

    def __init__(self):
        """Initialize the game's settings."""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (20, 230, 80)

        # Dog settings
        self.dog_speed = 1.0
        # dog direction of 1 represents down; -1 represents up.
        self.dog_direction = 1

class Dog:
    def __init__(self, pb_game):
        """Initialize the dog and set its starting position."""
        self.screen = pb_game.screen
        self.settings = pb_game.settings
        self.screen_rect = pb_game.screen.get_rect()

        # Load the dog image and get its rect.
        self.image = pygame.image.load('images/dog.png')
        self.rect = self.image.get_rect()

        # Start the dog at the center right of the screen.
        self.rect.midright = self.screen_rect.midright

        # Store a decimal value for the dog's vertical position.
        self.y = float(self.rect.y)

    def check_edges(self):
        """Return True if the dog is at the edge of the screen."""
        screen_rect = self.screen.get_rect()
        if self.rect.bottom >= screen_rect.bottom or self.rect.top <= 0:
            return True

    def update(self, dog_direction):
        """Move the dog down or up."""
        self.y += (self.settings.dog_speed * dog_direction)
        self.rect.y = float(self.y)

    def center_dog(self):
        self.rect.midright = self.screen_rect.midright
        self.y = float(self.rect.y)

    def blitme(self):
        """Draw the dog at its current location."""
        self.screen.blit(self.image, self.rect)

class PlayBall:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        # Set the window size and title bar text
        # Windowed
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        # Full screen
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Dog test")

        self.dog = Dog(self)

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()

            self._update_dog()

            self._update_screen()

    def _update_dog(self):
        """Respond appropriately if the dog has reached an edge."""
        dog_direction = self.settings.dog_direction
        if self.dog.check_edges():
            dog_direction *= -1
        self.dog.update(dog_direction)

    def _check_events(self):
        """Respond to key presses and mouse events."""
        # Gracefully exit when 'X' or alt+F4 close the window
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit() # Use with IDE
                # sys.exit() # If not using IDE, use sys.exit()

    def _start_game(self):
        """Start a new game."""
        self.dog.center_dog()

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)
        self.dog.blitme()

        # Make the most recently drawn screen visible.
        pygame.display.flip()

if __name__ == '__main__':
    # Make a game instance, and run the game.
    pb = PlayBall()
    pb.run_game()

In the _update_dog method, you are copying the direction to a temporary variable then reversing the temporary variable if an edge is hit._update_dog方法中,您将方向复制到临时变量,然后在遇到边缘时反转临时变量。 The change is lost on the next loop.更改在下一个循环中丢失。 To keep the change, update the settings variable also.要保持更改,还要更新设置变量。

Here is the updated code:这是更新后的代码:

def _update_dog(self):
    """Respond appropriately if the dog has reached an edge."""
    dog_direction = self.settings.dog_direction
    if self.dog.check_edges():
        dog_direction *= -1
        self.settings.dog_direction *= -1  # need to update settings also
    self.dog.update(dog_direction)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM