0

I'm trying to make a simple platformer game, but cannot get the collisions to work properly. If I print my is_collided_with method I get an infinite amount of collisions, but I'm only expecting collisions with the platforms I've created. What are all these numbers that are being returned?

import pygame
from pygame.locals import *

# --- constants --- 
MAN_SCREEN_MARGIN = 19     # pixels
JUMPING_DURATION = 500      # milliseconds
HORZ_MOVE_INCREMENT = 5     # pixels
TIME_AT_PEAK = JUMPING_DURATION / 2
JUMP_HEIGHT = 200           # pixels

WIN_WIDTH = 680 #width of window
WIN_HEIGHT = 500 #height of window

DISPLAY = (WIN_WIDTH, WIN_HEIGHT) #variable for screen display
DEPTH = 32 #standard
FLAGS = 0 #standard
WHITE = (255, 255, 255) #white
RED = (255, 0, 0) #red

# --- classes ---

class Platform(pygame.Rect):

    def __init__(self, x, y, screen):
        pygame.Rect.__init__(self, x, y, 40, 20)
        self.screen = screen 
    def draw(self, screen):
        pygame.draw.rect(self.screen, RED, self)


class Player():
    def __init__(self):
        self.image = pygame.image.load('C:\\Users\\admin\\Desktop\\Knight_right.png').convert_alpha()
        self.rect = self.image.get_rect()
        self.collision = False

    def display_player(self):
        return self.image

    def is_collided_with(self):
        return self.rect.collidelistall(platforms)

    def facing_right(self):
        return pygame.image.load('C:\\Users\\admin\\Desktop\\Knight_right.png').convert_alpha()


    def facing_left(self):
        return pygame.image.load('C:\\Users\\admin\\Desktop\\Knight_left.png').convert_alpha()


# --- main ---

level = [
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP", #45 x 25
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                    PPPPPPPPPPP           P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P    PPPPPPPP                              P",
        "P                                          P",
        "P                          PPPPPPP         P",
        "P                 PPPPPP                   P",
        "P                                          P",
        "P         PPPPPPP                          P",
        "P                                          P",
        "P                     PPPPPP               P",
        "P                                          P",
        "P   PPPPPPPPPPP                            P",
        "P                                          P",
        "P                 PPPPPPPPPPP              P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
]

pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
pygame.display.set_caption('Rum Islands')
Hero = Player()
man = Hero.display_player()
def floorY():
    ''' The Y coordinate of the floor, where the man is placed '''
    return screen.get_height() - man.get_height() - MAN_SCREEN_MARGIN

def jumpHeightAtTime(elapsedTime):
    ''' The height of the jump at the given elapsed time (milliseconds) '''
    return ((-1.0/TIME_AT_PEAK**2)* \
        ((elapsedTime-TIME_AT_PEAK)**2)+1)*JUMP_HEIGHT #some maths bullshit

def horzMoveAmt():
        ''' Amount of horizontal movement based on left/right arrow keys '''
        direction = (keys[K_RIGHT] - keys[K_LEFT]) * HORZ_MOVE_INCREMENT #each key returns 0 or 1
        return direction


manX = screen.get_width() / 2 #place man in middle
manY = floorY() #position to place man
jumping = False #variable for jumping
jumpingHorz = 0 #variable for horizontal jumping
platforms = [] 

loop = True
while loop:
    for event in pygame.event.get():
        if event.type == QUIT \
            or (event.type == KEYDOWN and event.key == K_ESCAPE):
            loop = False

    keys = pygame.key.get_pressed()

    if not jumping:
        manX += horzMoveAmt() #if on ground, move left or right
        if horzMoveAmt() >= 1:
            man = Hero.facing_right()
        elif horzMoveAmt() < 0:
            man = Hero.facing_left()
        if keys[K_SPACE]: #if jump key is pressed
            jumping = True #jumping is true
            jumpingHorz = horzMoveAmt() #horizontal jumping based on move amt
            jumpingStart = pygame.time.get_ticks() #start time of jump

    if jumping: #if jumping
        t = pygame.time.get_ticks() - jumpingStart #current length of jump
        if t > JUMPING_DURATION: #if jump exceeds desired length
            jumping = False #stop jumping
            jumpHeight = 0 #height = 0
        else:
            jumpHeight = jumpHeightAtTime(t) #else, get jump height at current time


        manY = floorY() - jumpHeight 
        manX += jumpingHorz







    screen.fill(WHITE)

    platform_x = 0
    platform_y = 0

    print(Hero.is_collided_with())   
    for row in level:
        for col in row:
            if col == "P":
                col = Platform(platform_x, platform_y, screen)
                col.draw(screen)
                platforms.append(col)

            platform_x += 15
        platform_y += 20
        platform_x = 0



    screen.blit(man, (manX, manY))
    pygame.display.flip()
    clock.tick(50)
Perplexityy
  • 561
  • 1
  • 9
  • 26
  • next time read doc: [collidelistall](http://pygame.org/docs/ref/rect.html#pygame.Rect.collidelistall): "Returns a list of all the indices that contain rectangles that collide with the Rect. If no intersecting rectangles are found, an empty list is returned." – furas Jan 08 '17 at 13:21
  • BTW: you should create all platforms (Platform(...)) only once - before `while` loop. Now you create again, and again the same platforms - so you only waist your time. – furas Jan 08 '17 at 13:26
  • in `Player()` you should create method `draw()` with `blit()` inside instead of using `display_player()`. You should hide in class `man` and change faces inside class instead of returning images from `facing_right`, `facing_left` – furas Jan 08 '17 at 13:29
  • you should put all functions before `--- main ---` to make code more readable. – furas Jan 08 '17 at 13:32
  • `manX` and `maxY` should be hidden inside class `Player`. Functions `jumpHeightAtTime`, `horzMoveAmt` should be methods in `Player` too. – furas Jan 08 '17 at 13:34

0 Answers0