Walls in Pygame

眉间皱痕 提交于 2021-02-11 15:19:44

问题


I am trying to make a simple Pac-Man game in Pygame, but I don't know how to make walls. How I can make check if player hit a wall when it moves? This is the code of main.py :

# Imports
import pygame
import sys
import player
import room

# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
blue = (0, 255, 0)
green = (0, 0, 255)

# Global variables
S_WIDTH = 800
S_HEIGHT = 800
FPS = 60
# player speed
SPEED = 2
WALLS = pygame.sprite.Group()

# Initialization 
pygame.init()
screen = pygame.display.set_mode([S_WIDTH, S_HEIGHT])
pygame.display.set_caption("Py-Man Alpha")
clock = pygame.time.Clock()

# Add walls to WALLS var.
wall = room.Wall(0, 600, 1000, 30, black, screen)
WALLS.add(wall)

# Main class
class Main(object):
    """
    This is main class of 
    the program. Here, the menu 
    will be showed and player 
    can start game, load, access 
    options or quit.
    """
    def __init__(self, screen):
        self.screen = screen

        self.menu()

    def menu(self):
        # Show menu
        pass

    def load(self):
        # Load game
        pass

    def options(self):
        # Show options
        pass

    def quit(self):
        pygame.quit()
        sys.exit()

# Game class
class Game(object):
    """
    This is main class of game.
    All game events will happen here.
    """
    Player = player.Player(blue, 50, 50, 0, 0) 
    def __init__(self, screen, running):
        self.screen = screen
        self.running = running

        self.run()

    def run(self):
        while self.running:
            # Events
            for event in pygame.event.get():
                # If user hits 'x'
                if event.type == pygame.QUIT:
                    self.running = False
                # Keyborad events
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP:
                        self.Player.direction = 'up'
                    elif event.key == pygame.K_DOWN:
                        self.Player.direction = 'down'
                    elif event.key == pygame.K_LEFT:
                        self.Player.direction = 'left'
                    elif event.key == pygame.K_RIGHT:
                        self.Player.direction = 'right'
                    elif event.key == pygame.K_p:
                        self.Player.direction = 'pause'
            # Clear screen
            self.screen.fill(white)

            #Draw
            self.Player.move(SPEED, WALLS)
            self.Player.draw(self.screen)
            for wall in WALLS:
                wall.draw()

            # Set clock
            clock.tick(60)

            # Update screen
            pygame.display.flip()

        # End of game
        pygame.quit()
        sys.exit()

# Tests
game = Game(screen, True)

This is the player class in player.py file:

#imports
import pygame

class Player(pygame.sprite.Sprite):
    """
    This class represent the player image
    and has the player actions.
    """
    direction = 'right'
    def __init__(self, color, width, height, x, y):
        # Pygame constructor
        pygame.sprite.Sprite.__init__(self)

        # Init. variables
        self.color = color
        self.width = width
        self.height = height
        self.x = x
        self.y = y 

        # Create sprite
        self.image = pygame.Surface([width, height])
        self.image.fill(self.color)
        self.rect = self.image.get_rect()

    def draw(self, screen):
        # Draw player on the screen
        pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height], 0)

    def move(self, speed, walls):
        # Move the player
        if self.direction == 'up':
            self.y -= speed
        elif self.direction == 'down':
            self.y += speed
        elif self.direction == 'left':
            self.x -= speed
        elif self.direction == 'right':  
            self.x += speed

And here is the room.py file, this contain the Wall class:

import pygame

class Wall(pygame.sprite.Sprite):
    """
    Walls can't be passed by player.
    """
    def __init__(self, x, y, width, height, color, screen):
        # Init.
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.screen = screen
        # Create
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()

    def draw(self):
        pygame.draw.rect(self.screen, self.color, [self.x, self.y, self.width, self.height], 0)

回答1:


Before you move the player to a new position, you need to iterate over all elements in WALLS and check whether the bounding box of the player would intersect with the wall. pygame.Rect has a number of helper methods for this (Rect.collide*)

If it does, then reject the move.




回答2:


You could check for collisions against the walls in move() by using a.colliderect(b)

#Example
def move(self, speed, walls):
    # Move the player
    if playerRect.colliderect(wallRect) == False:
        if self.direction == 'up':
            self.y -= speed
    if playerRect.colliderect(wallRect) == True:
        #Deny the movement

Something along these lines



来源:https://stackoverflow.com/questions/24301702/walls-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!