Jan-24-2023, 06:32 PM
import pygame # Initialize pygame pygame.init() # Set the screen size and caption screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("My Mario Game") class Mario(): def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height self.color = (255, 0, 0) # red color self.y_velocity = 0 self.jumping = False def draw(self, screen): pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height)) def check_collision(self, floor): # check if bottom of Mario object is at or below top of Floor object if self.y + self.height >= floor.y: # check if left and right edges of Mario object are within left and right edges of Floor object if self.x >= floor.x and self.x + self.width <= floor.x + floor.width: return True return False def handle_collision(self, floor): self.y = floor.y - self.height self.y_velocity = 0 self.jumping = False if self.x < floor.x + floor.width and self.x > floor.x: # Check if collision is occurring on the left edge if self.x < screen.get_width() - self.width: self.x = floor.x + floor.width else: self.x = floor.x + floor.width class Floor(): def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height self.color = (0, 200, 0) #green color def draw(self, screen): pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height)) floors = [Floor(0, 550, 800, 50), Floor(200, 450, 400, 50), Floor(600, 350, 200, 50)] # Create a Mario object mario = Mario(100, 400, 50, 100) # Main game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: if mario.jumping == False: mario.y_velocity = -1 mario.jumping = True keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: if mario.x > 0: # Check if Mario is within the left boundary mario.x -= 0.5 if keys[pygame.K_RIGHT]: if mario.x < screen.get_width() - mario.width: # Check if Mario is within the right boundary mario.x += 0.5 mario.y_velocity += 0.003 mario.y += mario.y_velocity for floor in floors: if mario.check_collision(floor): mario.handle_collision(floor) if mario.x < 0: # Check if Mario is within the left boundary mario.x = 0 elif mario.x > screen.get_width() - mario.width: # Check if Mario is within the right boundary mario.x = screen.get_width() - mario.width if mario.y < 0: # Check if Mario is within the top boundary mario.y = 0 elif mario.y > screen.get_height() - mario.height: # Check if Mario is within the bottom boundary mario.y = screen.get_height() - mario.height screen.fill((0, 0, 0)) mario.draw(screen) for floor in floors: floor.draw(screen) pygame.display.flip() # Clean up before exiting pygame.quit()When the player falls, it teleports to the right edge of the platform. How do I fix this?