Why is my 21 game code not working /u/Own-Recipe5931 Python Education

Why is my 21 game code not working /u/Own-Recipe5931 Python Education

the problem to me the try and except even when i make a integer input it still runs the except block code stopping my progress

Here’s my code

import random

startup = random.randint(1,3)

print(“My number is “, startup)

check = startup + 3

nexnum = int(input(“Enter your number n- “))

def check_round():

while nexnum > check:

print(“Your number is too highn Please try again”)

nexnum = int(input(“-“))

while nexnum or startup != 21:

try:

nexnum = int(nexnum)

check_round()

except:

print(“Please enter a whole number”)

nexnum = int(input(“-“))

continue

func1 = nexnum + 3

func2 = nexnum – 1

startup = random.randint(func2, func1)

nexnum = int(input(“Enter your next numbern-“))

continue

submitted by /u/Own-Recipe5931
[link] [comments]

​r/learnpython the problem to me the try and except even when i make a integer input it still runs the except block code stopping my progress Here’s my code import random startup = random.randint(1,3) print(“My number is “, startup) check = startup + 3 nexnum = int(input(“Enter your number n- “)) def check_round(): while nexnum > check: print(“Your number is too highn Please try again”) nexnum = int(input(“-“)) while nexnum or startup != 21: try: nexnum = int(nexnum) check_round() except: print(“Please enter a whole number”) nexnum = int(input(“-“)) continue func1 = nexnum + 3 func2 = nexnum – 1 startup = random.randint(func2, func1) nexnum = int(input(“Enter your next numbern-“)) continue submitted by /u/Own-Recipe5931 [link] [comments] 

the problem to me the try and except even when i make a integer input it still runs the except block code stopping my progress

Here’s my code

import random

startup = random.randint(1,3)

print(“My number is “, startup)

check = startup + 3

nexnum = int(input(“Enter your number n- “))

def check_round():

while nexnum > check:

print(“Your number is too highn Please try again”)

nexnum = int(input(“-“))

while nexnum or startup != 21:

try:

nexnum = int(nexnum)

check_round()

except:

print(“Please enter a whole number”)

nexnum = int(input(“-“))

continue

func1 = nexnum + 3

func2 = nexnum – 1

startup = random.randint(func2, func1)

nexnum = int(input(“Enter your next numbern-“))

continue

submitted by /u/Own-Recipe5931
[link] [comments]  the problem to me the try and except even when i make a integer input it still runs the except block code stopping my progress Here’s my code import random startup = random.randint(1,3) print(“My number is “, startup) check = startup + 3 nexnum = int(input(“Enter your number n- “)) def check_round(): while nexnum > check: print(“Your number is too highn Please try again”) nexnum = int(input(“-“)) while nexnum or startup != 21: try: nexnum = int(nexnum) check_round() except: print(“Please enter a whole number”) nexnum = int(input(“-“)) continue func1 = nexnum + 3 func2 = nexnum – 1 startup = random.randint(func2, func1) nexnum = int(input(“Enter your next numbern-“)) continue submitted by /u/Own-Recipe5931 [link] [comments]

Read more

SQLAlchemy question for polymorphic reference /u/pleides101 Python Education

SQLAlchemy question for polymorphic reference /u/pleides101 Python Education

Hi. Started to learn python and am working on a small project to build a trading system. I took help from various coding AI assistants to build up the different pieces and got it to a working state. However I was using bare SQL queries for all my data management and although I tried to minimise possibilities of error and injections, it was still looking cumbersome. So I wanted to experiment with an ORM and tried sql alchemy. But due to how my table relationships are modelled Im having difficulty figuring out how to express them in a way sql alchemy can understand, none of the AI assistants have been able to help me.

Basically it is a hierarchy of Strategy -> StrategySet -> Leg. And the Strategy and Leg entities have indirect StopLoss and TrailingStopLoss relationships. I’m not using a dedicated column on the Strategy and Leg entities to reference the StopLoss and TrailingStopLoss as it wouldn’t work out. A Strategy or Leg can have multiple stop losses or Trailing Stop losses defined and hence it would be a one to many relationship. So I modelled the StopLoss and TrailingStopLoss to hold a polymorphic reference called entity type. Depending on the entity type(Strategy or Leg) the entity id could hold reference to a Strategy or Leg id. So now whenever a new StopLoss or TrailingStopLoss is to be created I want to ensure the entity type is validated to be Strategy or Leg and then ensure the corresponding entity id actually exists in Strategy or Leg. I was able to do all of this manually when I wrote the SQL queries myself but now having trouble modelling all of this in SQL alchemy. Any help or advice on what to do? Should I just create dedicated StopLoss and TrailingStopLoss entities for Strategy and Leg separately? I wanted to keep redundant columns or tables to a minimum.

Here’s the complete code(not working) for more details in case you need it – https://gist.github.com/karthik448/cd5bafb8e4cd5e37d5dfdffe26643d76

The only working code that any of the AIs could do was to add in a stop loss and trailing stop loss reference id into the strategy and leg entities and use the relationship and back-populates to add it in when a stop loss entry is created. This is obviously not going to work out for me as I want to have one to many relationship here.

submitted by /u/pleides101
[link] [comments]

​r/learnpython Hi. Started to learn python and am working on a small project to build a trading system. I took help from various coding AI assistants to build up the different pieces and got it to a working state. However I was using bare SQL queries for all my data management and although I tried to minimise possibilities of error and injections, it was still looking cumbersome. So I wanted to experiment with an ORM and tried sql alchemy. But due to how my table relationships are modelled Im having difficulty figuring out how to express them in a way sql alchemy can understand, none of the AI assistants have been able to help me. Basically it is a hierarchy of Strategy -> StrategySet -> Leg. And the Strategy and Leg entities have indirect StopLoss and TrailingStopLoss relationships. I’m not using a dedicated column on the Strategy and Leg entities to reference the StopLoss and TrailingStopLoss as it wouldn’t work out. A Strategy or Leg can have multiple stop losses or Trailing Stop losses defined and hence it would be a one to many relationship. So I modelled the StopLoss and TrailingStopLoss to hold a polymorphic reference called entity type. Depending on the entity type(Strategy or Leg) the entity id could hold reference to a Strategy or Leg id. So now whenever a new StopLoss or TrailingStopLoss is to be created I want to ensure the entity type is validated to be Strategy or Leg and then ensure the corresponding entity id actually exists in Strategy or Leg. I was able to do all of this manually when I wrote the SQL queries myself but now having trouble modelling all of this in SQL alchemy. Any help or advice on what to do? Should I just create dedicated StopLoss and TrailingStopLoss entities for Strategy and Leg separately? I wanted to keep redundant columns or tables to a minimum. Here’s the complete code(not working) for more details in case you need it – https://gist.github.com/karthik448/cd5bafb8e4cd5e37d5dfdffe26643d76 The only working code that any of the AIs could do was to add in a stop loss and trailing stop loss reference id into the strategy and leg entities and use the relationship and back-populates to add it in when a stop loss entry is created. This is obviously not going to work out for me as I want to have one to many relationship here. submitted by /u/pleides101 [link] [comments] 

Hi. Started to learn python and am working on a small project to build a trading system. I took help from various coding AI assistants to build up the different pieces and got it to a working state. However I was using bare SQL queries for all my data management and although I tried to minimise possibilities of error and injections, it was still looking cumbersome. So I wanted to experiment with an ORM and tried sql alchemy. But due to how my table relationships are modelled Im having difficulty figuring out how to express them in a way sql alchemy can understand, none of the AI assistants have been able to help me.

Basically it is a hierarchy of Strategy -> StrategySet -> Leg. And the Strategy and Leg entities have indirect StopLoss and TrailingStopLoss relationships. I’m not using a dedicated column on the Strategy and Leg entities to reference the StopLoss and TrailingStopLoss as it wouldn’t work out. A Strategy or Leg can have multiple stop losses or Trailing Stop losses defined and hence it would be a one to many relationship. So I modelled the StopLoss and TrailingStopLoss to hold a polymorphic reference called entity type. Depending on the entity type(Strategy or Leg) the entity id could hold reference to a Strategy or Leg id. So now whenever a new StopLoss or TrailingStopLoss is to be created I want to ensure the entity type is validated to be Strategy or Leg and then ensure the corresponding entity id actually exists in Strategy or Leg. I was able to do all of this manually when I wrote the SQL queries myself but now having trouble modelling all of this in SQL alchemy. Any help or advice on what to do? Should I just create dedicated StopLoss and TrailingStopLoss entities for Strategy and Leg separately? I wanted to keep redundant columns or tables to a minimum.

Here’s the complete code(not working) for more details in case you need it – https://gist.github.com/karthik448/cd5bafb8e4cd5e37d5dfdffe26643d76

The only working code that any of the AIs could do was to add in a stop loss and trailing stop loss reference id into the strategy and leg entities and use the relationship and back-populates to add it in when a stop loss entry is created. This is obviously not going to work out for me as I want to have one to many relationship here.

submitted by /u/pleides101
[link] [comments]  Hi. Started to learn python and am working on a small project to build a trading system. I took help from various coding AI assistants to build up the different pieces and got it to a working state. However I was using bare SQL queries for all my data management and although I tried to minimise possibilities of error and injections, it was still looking cumbersome. So I wanted to experiment with an ORM and tried sql alchemy. But due to how my table relationships are modelled Im having difficulty figuring out how to express them in a way sql alchemy can understand, none of the AI assistants have been able to help me. Basically it is a hierarchy of Strategy -> StrategySet -> Leg. And the Strategy and Leg entities have indirect StopLoss and TrailingStopLoss relationships. I’m not using a dedicated column on the Strategy and Leg entities to reference the StopLoss and TrailingStopLoss as it wouldn’t work out. A Strategy or Leg can have multiple stop losses or Trailing Stop losses defined and hence it would be a one to many relationship. So I modelled the StopLoss and TrailingStopLoss to hold a polymorphic reference called entity type. Depending on the entity type(Strategy or Leg) the entity id could hold reference to a Strategy or Leg id. So now whenever a new StopLoss or TrailingStopLoss is to be created I want to ensure the entity type is validated to be Strategy or Leg and then ensure the corresponding entity id actually exists in Strategy or Leg. I was able to do all of this manually when I wrote the SQL queries myself but now having trouble modelling all of this in SQL alchemy. Any help or advice on what to do? Should I just create dedicated StopLoss and TrailingStopLoss entities for Strategy and Leg separately? I wanted to keep redundant columns or tables to a minimum. Here’s the complete code(not working) for more details in case you need it – https://gist.github.com/karthik448/cd5bafb8e4cd5e37d5dfdffe26643d76 The only working code that any of the AIs could do was to add in a stop loss and trailing stop loss reference id into the strategy and leg entities and use the relationship and back-populates to add it in when a stop loss entry is created. This is obviously not going to work out for me as I want to have one to many relationship here. submitted by /u/pleides101 [link] [comments]

Read more

need help with basics /u/ah_ahaa Python Education

need help with basics /u/ah_ahaa Python Education

hey , started to learn python i am a complete beginner in code writing) and right now im on “if” , “else”,”elife”, part

i practice on all the basics and i came across an issue with this part

num1 = int(input("what is your lucky nubmer? ")) num2 = int(input("what is your age? ")) num3 = num1+num2 ques1 = int(input("please enter a number above " +num3 , )) 

in “ques1” i want the user to be asked to put number above “num3” so from there i can keep add more stuff just to mess around and test myself. issue is , no matter where i tried to put “num3” in the “ques” input i get error.
where should i put it?
thanks!

submitted by /u/ah_ahaa
[link] [comments]

​r/learnpython hey , started to learn python i am a complete beginner in code writing) and right now im on “if” , “else”,”elife”, part i practice on all the basics and i came across an issue with this part num1 = int(input(“what is your lucky nubmer? “)) num2 = int(input(“what is your age? “)) num3 = num1+num2 ques1 = int(input(“please enter a number above ” +num3 , )) in “ques1” i want the user to be asked to put number above “num3” so from there i can keep add more stuff just to mess around and test myself. issue is , no matter where i tried to put “num3” in the “ques” input i get error. where should i put it? thanks! submitted by /u/ah_ahaa [link] [comments] 

hey , started to learn python i am a complete beginner in code writing) and right now im on “if” , “else”,”elife”, part

i practice on all the basics and i came across an issue with this part

num1 = int(input("what is your lucky nubmer? ")) num2 = int(input("what is your age? ")) num3 = num1+num2 ques1 = int(input("please enter a number above " +num3 , )) 

in “ques1” i want the user to be asked to put number above “num3” so from there i can keep add more stuff just to mess around and test myself. issue is , no matter where i tried to put “num3” in the “ques” input i get error.
where should i put it?
thanks!

submitted by /u/ah_ahaa
[link] [comments]  hey , started to learn python i am a complete beginner in code writing) and right now im on “if” , “else”,”elife”, part i practice on all the basics and i came across an issue with this part num1 = int(input(“what is your lucky nubmer? “)) num2 = int(input(“what is your age? “)) num3 = num1+num2 ques1 = int(input(“please enter a number above ” +num3 , )) in “ques1” i want the user to be asked to put number above “num3” so from there i can keep add more stuff just to mess around and test myself. issue is , no matter where i tried to put “num3” in the “ques” input i get error. where should i put it? thanks! submitted by /u/ah_ahaa [link] [comments]

Read more

Does celery works with Async functions /u/John-Doe-99 Python Education

Does celery works with Async functions /u/John-Doe-99 Python Education

I recently started working with celery and quickly started facing issue using this with async function like ‘Coroutines are not JSON serialisation’

My task includes a batch processing task with runs based on the client input. And i was using asyncio with semaphore. But was not able to use retry with that.

So Does celery works well with async functions or synchronous functions are generally used with celery?

submitted by /u/John-Doe-99
[link] [comments]

​r/learnpython I recently started working with celery and quickly started facing issue using this with async function like ‘Coroutines are not JSON serialisation’ My task includes a batch processing task with runs based on the client input. And i was using asyncio with semaphore. But was not able to use retry with that. So Does celery works well with async functions or synchronous functions are generally used with celery? submitted by /u/John-Doe-99 [link] [comments] 

I recently started working with celery and quickly started facing issue using this with async function like ‘Coroutines are not JSON serialisation’

My task includes a batch processing task with runs based on the client input. And i was using asyncio with semaphore. But was not able to use retry with that.

So Does celery works well with async functions or synchronous functions are generally used with celery?

submitted by /u/John-Doe-99
[link] [comments]  I recently started working with celery and quickly started facing issue using this with async function like ‘Coroutines are not JSON serialisation’ My task includes a batch processing task with runs based on the client input. And i was using asyncio with semaphore. But was not able to use retry with that. So Does celery works well with async functions or synchronous functions are generally used with celery? submitted by /u/John-Doe-99 [link] [comments]

Read more

Help if you want /u/Granite900 Python Education

Help if you want /u/Granite900 Python Education

So, I wanted to make a python game and I used chat gpt for some parts and now I can’t get the respawn button to work, I tried but all it does is put up the pause menu and break the ui. What I want it to do is neatly close and respawn the player at the spawning platform. Feal free to neaten up, but it’s good enough.

Sprits (if needed, and the folder is needed because that’s the directory, tell me if you need it and it doesn’t work): https://www.mediafire.com/folder/6u0qlyyr0cfpt/img

Code:

import pygame import os import sys import random import time # Initialize Pygame pygame.init() import pdb # Set up fullscreen display screen_info = pygame.display.Info() WIDTH, HEIGHT = screen_info.current_w, screen_info.current_h screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) pygame.display.set_caption("ChronoShift Player Controller with Flipping") # Colors WHITE = (255, 255, 255) # FPS settings FPS = 60 # Load images from the img folder image_folder = "img" frame1 = pygame.image.load(os.path.join(image_folder, "Chronoshift_char1.png")).convert_alpha() frame2 = pygame.image.load(os.path.join(image_folder, "Chronoshift_char2.png")).convert_alpha() ground_tile_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_ground1.png")).convert_alpha() pause_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_pausebutton.png")).convert_alpha() pause_screen_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_pausescreen.png")).convert_alpha() dead_screen_img = pygame.image.load(os.path.join(image_folder, "Chronoshift-deadscreen.png")).convert_alpha() resume_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_resumebutton.png")).convert_alpha() quit_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_quitbutton.png")).convert_alpha() respawn_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_respawnbutton.png")).convert_alpha() # Scale images to a consistent size (optional) CHARACTER_WIDTH, CHARACTER_HEIGHT = 64, 64 frame1 = pygame.transform.scale(frame1, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) frame2 = pygame.transform.scale(frame2, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT = 64, 64 ground_tile_img = pygame.transform.scale(ground_tile_img, (GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT)) # Respawn button setting RESPAWN_BUTTON_SIZE = 325 respawn_button_img = pygame.transform.scale(respawn_button_img, (RESPAWN_BUTTON_SIZE, RESPAWN_BUTTON_SIZE)) # Pause button settings PAUSE_BUTTON_SIZE = 100 # Increased button size pause_button_img = pygame.transform.scale(pause_button_img, (PAUSE_BUTTON_SIZE, PAUSE_BUTTON_SIZE)) # Resume and Quit button settings (larger buttons) BUTTON_SIZE = 325 # 325x325 buttons resume_button_img = pygame.transform.scale(resume_button_img, (BUTTON_SIZE, BUTTON_SIZE)) quit_button_img = pygame.transform.scale(quit_button_img, (BUTTON_SIZE, BUTTON_SIZE)) # Create a list of frames for animation frames = [frame1, frame2] # Clock for controlling FPS clock = pygame.time.Clock() # Gravity settings GRAVITY = 0.8 JUMP_STRENGTH = -18 # Player class class Player(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.images = frames self.current_frame = 0 self.image = self.images[self.current_frame] self.rect = self.image.get_rect(topleft=(x, y)) self.velocity_x = 5 self.velocity_y = 0 self.is_walking = False self.is_jumping = False self.facing_right = True self.animation_timer = 0 self.animation_speed = 200 self.respawned = False # Flag to track if the player respawned def update(self, ground_tiles): keys = pygame.key.get_pressed() self.is_walking = False if keys[pygame.K_LEFT]: self.rect.x -= self.velocity_x self.is_walking = True self.facing_right = False if keys[pygame.K_RIGHT]: self.rect.x += self.velocity_x self.is_walking = True self.facing_right = True if keys[pygame.K_SPACE] and not self.is_jumping: self.velocity_y = JUMP_STRENGTH self.is_jumping = True # Apply gravity self.velocity_y += GRAVITY self.rect.y += self.velocity_y # Respawn if the player falls too far down # Skip collision check if the player has respawned if self.respawned: self.respawned = False # Reset the flag after one update cycle else: # Only check for collisions if the player has not respawned self.check_collisions(ground_tiles) # Handle animation if self.is_walking: self.animate() else: self.current_frame = 0 self.image = self.images[self.current_frame] if not self.facing_right: self.image = pygame.transform.flip(self.images[self.current_frame], True, False) else: self.image = self.images[self.current_frame] def check_collisions(self, ground_tiles): # Check for collisions with ground tiles collided = pygame.sprite.spritecollide(self, ground_tiles, False) if collided: # Set the player on top of the ground tile self.rect.bottom = collided[0].rect.top self.velocity_y = 0 self.is_jumping = False def animate(self): # Handle animation timing self.animation_timer += clock.get_time() if self.animation_timer >= self.animation_speed: self.animation_timer = 0 self.current_frame = (self.current_frame + 1) % len(self.images) for tile in ground_tiles: # Calculate the distance from the player's current x-position to each ground tile distance = abs(self.rect.centerx - tile.rect.centerx) # Ground tile class class GroundTile(pygame.sprite.Sprite): def __init__(self, x, y, width=GROUND_TILE_WIDTH, height=GROUND_TILE_HEIGHT): super().__init__() self.image = pygame.transform.scale(ground_tile_img, (width, height)) # Allow dynamic scaling self.rect = self.image.get_rect(topleft=(x, y)) def respawn_player(): global paused player.rect.topleft = player.spawn_platform.rect.topleft # Reset player position player.velocity_y = 0 # Reset velocity player.respawned = True # Set respawn flag toggle_pause() # Unpause the game after respawn ui_sprites.remove(dead_screen) # Remove dead screen ui_sprites.remove(respawn_button) # Remove respawn button after respawn ui_sprites.add(resume_button) # Show the resume button after respawn # Pause button class class PauseButton(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_button_img self.rect = self.image.get_rect(topleft=(WIDTH - PAUSE_BUTTON_SIZE - 10, 10)) # Top-right corner self.original_image = self.image # Keep the original image for restoring after press self.press_effect_duration = 200 # Duration of the press effect in milliseconds self.press_timer = 0 self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed self.button_pressed = False # Track whether the button has been pressed in this frame def update(self, mouse_buttons): if self.is_pressed: self.press_timer += clock.get_time() if self.press_timer > self.press_effect_duration: self.is_pressed = False self.press_timer = 0 # Restore original size after pressing self.image = self.original_image # If mouse is not pressed anymore, return to original size if not self.is_pressed and mouse_buttons[0] == 0: self.image = self.original_image self.button_pressed = False # Reset button pressed state def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): if not self.button_pressed: self.button_pressed = True return True return False # Resume and Quit button classes class Button(pygame.sprite.Sprite): def __init__(self, image, x, y, action=None): super().__init__() self.image = image self.rect = self.image.get_rect(topleft=(x, y)) self.original_image = self.image self.action = action self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed def update(self, mouse_buttons): if self.is_pressed: self.is_pressed = False if self.action: self.action() # Call the action when the button is pressed # If mouse is not pressed anymore, return to original size if mouse_buttons[0] == 0: self.image = self.original_image def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): return self.rect.collidepoint(pygame.mouse.get_pos()) # Pause screen class class PauseScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_screen_img # Make the pause screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) class DeadScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = dead_screen_img # Make the dead screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) # Instantiate player further to the right player = Player(400, HEIGHT - 300) # Spawn player much further to the right # Create ground tiles (Parkour course with random heights and wider gaps) ground_tiles = pygame.sprite.Group() # Create the spawning platform (beginning of the course) spawn_platform = GroundTile(-300, HEIGHT - 150, width=600) # Set a larger width (600 pixels) ground_tiles.add(spawn_platform) # Create the player and assign the spawn platform player = Player(400, HEIGHT - 300) player.spawn_platform = spawn_platform # Assign the spawn platform to the player # Add player and other elements to sprite groups all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) #all_sprites.add(pause_button) # Add the pause button to the sprite group # Additional ground tiles, use default size ground_tile1 = GroundTile(0, HEIGHT - 150) ground_tile2 = GroundTile(50, HEIGHT - 150) ground_tile3 = GroundTile(100 , HEIGHT - 150) ground_tiles.add(ground_tile1, ground_tile2, ground_tile3) # Create 15 parkour platforms with random heights and wider gaps x_pos = 600 # Start a lot further to the right of the screen y_pos_base = HEIGHT - 250 # Base y position for platforms for i in range(15): x = x_pos + i * (GROUND_TILE_WIDTH + random.randint(80, 150)) # Wider gaps with random distances y = y_pos_base + random.randint(-100, 100) # Random height variation between -100 and +100 ground_tile = GroundTile(x, y) ground_tiles.add(ground_tile) # Create pause button pause_button = PauseButton() # Create pause screen (initially hidden) pause_screen = PauseScreen() dead_screen = DeadScreen() # Create Resume and Quit buttons resume_button = Button(resume_button_img, WIDTH // 2 - BUTTON_SIZE // 2, HEIGHT // 2 - BUTTON_SIZE // 2, action=lambda: toggle_pause()) quit_button = Button(quit_button_img, WIDTH // 2 - BUTTON_SIZE // 2, HEIGHT // 2 + BUTTON_SIZE // 2, action=lambda: quit_game()) respawn_button = Button(respawn_button_img, WIDTH // 2 - BUTTON_SIZE // 2, HEIGHT // 2 - BUTTON_SIZE // 2 - 15, action=lambda: respawn_player()) # Group for all sprites all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) all_sprites.add(pause_button) # Group for UI elements (Pause menu and buttons) ui_sprites = pygame.sprite.Group() ui_sprites.add(pause_button) # Camera scrolling variables camera_x = 0 # Camera x-position camera_y = 0 # Camera y-position camera_speed = 5 # Camera speed # Game loop running = True paused = False # Game starts in a non-paused state def toggle_pause(): global paused paused = not paused if paused: # Show the pause screen and buttons ui_sprites.add(pause_screen) ui_sprites.add(resume_button) ui_sprites.add(quit_button) else: # Hide the pause screen and buttons but don't delete them ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) # If the player is alive, remove the respawn button when unpausing if player.rect.bottom > HEIGHT: ui_sprites.remove(respawn_button) # Remove respawn button when game resumes def dead_screen(): global paused paused = True # Pause the game when dead screen is active if player.rect.bottom > HEIGHT: # Create an instance of the DeadScreen class dead_screen_instance = DeadScreen() # Instantiate the DeadScreen class ui_sprites.add(dead_screen_instance) # Add the instance to ui_sprites ui_sprites.add(quit_button) # Add quit button ui_sprites.add(respawn_button) # Show respawn button when player dies # Ensure the resume button is removed when the player is dead ui_sprites.remove(resume_button) # Remove the resume button def quit_game(): pygame.quit() sys.exit() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Get mouse buttons mouse_buttons = pygame.mouse.get_pressed() if player.rect.bottom > HEIGHT: dead_screen() if mouse_buttons[0] == 1: # Left mouse button is pressed # Check if the pause button is clicked if pause_button.rect.collidepoint(pygame.mouse.get_pos()) and pause_button.toggle(): pause_button.press() # Add the press effect toggle_pause() # Toggle pause state # Check if the resume button is clicked if resume_button.toggle(): resume_button.press() ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) time.sleep(0.25) # Check if the quit button is clicked if quit_button.toggle(): quit_button.press() quit_game() if respawn_button.toggle(): respawn_button.press() # Update the pause button, which will return to normal after the mouse is not pressed pause_button.update(mouse_buttons) if not paused: # Update the game (only if not paused) player.update(ground_tiles) # Camera follows player camera_x = (player.rect.centerx - WIDTH // 2) * 0.1 # Smooth following on X axis camera_y = (player.rect.centery - HEIGHT // 2) * 0.1 # Smooth following on Y axis # Update ground tiles' positions based on the camera for tile in ground_tiles: tile.rect.x -= camera_x tile.rect.y -= camera_y # Update Resume and Quit buttons resume_button.update(mouse_buttons) quit_button.update(mouse_buttons) # Draw everything screen.fill(WHITE) # Move all game sprites based on the camera for sprite in all_sprites: if not isinstance(sprite, PauseButton): # Skip the pause button and other UI elements sprite.rect.x -= camera_x sprite.rect.y -= camera_y all_sprites.draw(screen) # Draw UI elements last (UI is unaffected by camera) ui_sprites.draw(screen) # Refresh display pygame.display.flip() # Tick the clock clock.tick(FPS) # Quit Pygame pygame.QUIT() pdb.set_trace() sys.exit() 

submitted by /u/Granite900
[link] [comments]

​r/learnpython So, I wanted to make a python game and I used chat gpt for some parts and now I can’t get the respawn button to work, I tried but all it does is put up the pause menu and break the ui. What I want it to do is neatly close and respawn the player at the spawning platform. Feal free to neaten up, but it’s good enough. Sprits (if needed, and the folder is needed because that’s the directory, tell me if you need it and it doesn’t work): https://www.mediafire.com/folder/6u0qlyyr0cfpt/img Code: import pygame import os import sys import random import time # Initialize Pygame pygame.init() import pdb # Set up fullscreen display screen_info = pygame.display.Info() WIDTH, HEIGHT = screen_info.current_w, screen_info.current_h screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) pygame.display.set_caption(“ChronoShift Player Controller with Flipping”) # Colors WHITE = (255, 255, 255) # FPS settings FPS = 60 # Load images from the img folder image_folder = “img” frame1 = pygame.image.load(os.path.join(image_folder, “Chronoshift_char1.png”)).convert_alpha() frame2 = pygame.image.load(os.path.join(image_folder, “Chronoshift_char2.png”)).convert_alpha() ground_tile_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_ground1.png”)).convert_alpha() pause_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_pausebutton.png”)).convert_alpha() pause_screen_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_pausescreen.png”)).convert_alpha() dead_screen_img = pygame.image.load(os.path.join(image_folder, “Chronoshift-deadscreen.png”)).convert_alpha() resume_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_resumebutton.png”)).convert_alpha() quit_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_quitbutton.png”)).convert_alpha() respawn_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_respawnbutton.png”)).convert_alpha() # Scale images to a consistent size (optional) CHARACTER_WIDTH, CHARACTER_HEIGHT = 64, 64 frame1 = pygame.transform.scale(frame1, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) frame2 = pygame.transform.scale(frame2, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT = 64, 64 ground_tile_img = pygame.transform.scale(ground_tile_img, (GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT)) # Respawn button setting RESPAWN_BUTTON_SIZE = 325 respawn_button_img = pygame.transform.scale(respawn_button_img, (RESPAWN_BUTTON_SIZE, RESPAWN_BUTTON_SIZE)) # Pause button settings PAUSE_BUTTON_SIZE = 100 # Increased button size pause_button_img = pygame.transform.scale(pause_button_img, (PAUSE_BUTTON_SIZE, PAUSE_BUTTON_SIZE)) # Resume and Quit button settings (larger buttons) BUTTON_SIZE = 325 # 325×325 buttons resume_button_img = pygame.transform.scale(resume_button_img, (BUTTON_SIZE, BUTTON_SIZE)) quit_button_img = pygame.transform.scale(quit_button_img, (BUTTON_SIZE, BUTTON_SIZE)) # Create a list of frames for animation frames = [frame1, frame2] # Clock for controlling FPS clock = pygame.time.Clock() # Gravity settings GRAVITY = 0.8 JUMP_STRENGTH = -18 # Player class class Player(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.images = frames self.current_frame = 0 self.image = self.images[self.current_frame] self.rect = self.image.get_rect(topleft=(x, y)) self.velocity_x = 5 self.velocity_y = 0 self.is_walking = False self.is_jumping = False self.facing_right = True self.animation_timer = 0 self.animation_speed = 200 self.respawned = False # Flag to track if the player respawned def update(self, ground_tiles): keys = pygame.key.get_pressed() self.is_walking = False if keys[pygame.K_LEFT]: self.rect.x -= self.velocity_x self.is_walking = True self.facing_right = False if keys[pygame.K_RIGHT]: self.rect.x += self.velocity_x self.is_walking = True self.facing_right = True if keys[pygame.K_SPACE] and not self.is_jumping: self.velocity_y = JUMP_STRENGTH self.is_jumping = True # Apply gravity self.velocity_y += GRAVITY self.rect.y += self.velocity_y # Respawn if the player falls too far down # Skip collision check if the player has respawned if self.respawned: self.respawned = False # Reset the flag after one update cycle else: # Only check for collisions if the player has not respawned self.check_collisions(ground_tiles) # Handle animation if self.is_walking: self.animate() else: self.current_frame = 0 self.image = self.images[self.current_frame] if not self.facing_right: self.image = pygame.transform.flip(self.images[self.current_frame], True, False) else: self.image = self.images[self.current_frame] def check_collisions(self, ground_tiles): # Check for collisions with ground tiles collided = pygame.sprite.spritecollide(self, ground_tiles, False) if collided: # Set the player on top of the ground tile self.rect.bottom = collided[0].rect.top self.velocity_y = 0 self.is_jumping = False def animate(self): # Handle animation timing self.animation_timer += clock.get_time() if self.animation_timer >= self.animation_speed: self.animation_timer = 0 self.current_frame = (self.current_frame + 1) % len(self.images) for tile in ground_tiles: # Calculate the distance from the player’s current x-position to each ground tile distance = abs(self.rect.centerx – tile.rect.centerx) # Ground tile class class GroundTile(pygame.sprite.Sprite): def __init__(self, x, y, width=GROUND_TILE_WIDTH, height=GROUND_TILE_HEIGHT): super().__init__() self.image = pygame.transform.scale(ground_tile_img, (width, height)) # Allow dynamic scaling self.rect = self.image.get_rect(topleft=(x, y)) def respawn_player(): global paused player.rect.topleft = player.spawn_platform.rect.topleft # Reset player position player.velocity_y = 0 # Reset velocity player.respawned = True # Set respawn flag toggle_pause() # Unpause the game after respawn ui_sprites.remove(dead_screen) # Remove dead screen ui_sprites.remove(respawn_button) # Remove respawn button after respawn ui_sprites.add(resume_button) # Show the resume button after respawn # Pause button class class PauseButton(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_button_img self.rect = self.image.get_rect(topleft=(WIDTH – PAUSE_BUTTON_SIZE – 10, 10)) # Top-right corner self.original_image = self.image # Keep the original image for restoring after press self.press_effect_duration = 200 # Duration of the press effect in milliseconds self.press_timer = 0 self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed self.button_pressed = False # Track whether the button has been pressed in this frame def update(self, mouse_buttons): if self.is_pressed: self.press_timer += clock.get_time() if self.press_timer > self.press_effect_duration: self.is_pressed = False self.press_timer = 0 # Restore original size after pressing self.image = self.original_image # If mouse is not pressed anymore, return to original size if not self.is_pressed and mouse_buttons[0] == 0: self.image = self.original_image self.button_pressed = False # Reset button pressed state def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): if not self.button_pressed: self.button_pressed = True return True return False # Resume and Quit button classes class Button(pygame.sprite.Sprite): def __init__(self, image, x, y, action=None): super().__init__() self.image = image self.rect = self.image.get_rect(topleft=(x, y)) self.original_image = self.image self.action = action self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed def update(self, mouse_buttons): if self.is_pressed: self.is_pressed = False if self.action: self.action() # Call the action when the button is pressed # If mouse is not pressed anymore, return to original size if mouse_buttons[0] == 0: self.image = self.original_image def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): return self.rect.collidepoint(pygame.mouse.get_pos()) # Pause screen class class PauseScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_screen_img # Make the pause screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) class DeadScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = dead_screen_img # Make the dead screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) # Instantiate player further to the right player = Player(400, HEIGHT – 300) # Spawn player much further to the right # Create ground tiles (Parkour course with random heights and wider gaps) ground_tiles = pygame.sprite.Group() # Create the spawning platform (beginning of the course) spawn_platform = GroundTile(-300, HEIGHT – 150, width=600) # Set a larger width (600 pixels) ground_tiles.add(spawn_platform) # Create the player and assign the spawn platform player = Player(400, HEIGHT – 300) player.spawn_platform = spawn_platform # Assign the spawn platform to the player # Add player and other elements to sprite groups all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) #all_sprites.add(pause_button) # Add the pause button to the sprite group # Additional ground tiles, use default size ground_tile1 = GroundTile(0, HEIGHT – 150) ground_tile2 = GroundTile(50, HEIGHT – 150) ground_tile3 = GroundTile(100 , HEIGHT – 150) ground_tiles.add(ground_tile1, ground_tile2, ground_tile3) # Create 15 parkour platforms with random heights and wider gaps x_pos = 600 # Start a lot further to the right of the screen y_pos_base = HEIGHT – 250 # Base y position for platforms for i in range(15): x = x_pos + i * (GROUND_TILE_WIDTH + random.randint(80, 150)) # Wider gaps with random distances y = y_pos_base + random.randint(-100, 100) # Random height variation between -100 and +100 ground_tile = GroundTile(x, y) ground_tiles.add(ground_tile) # Create pause button pause_button = PauseButton() # Create pause screen (initially hidden) pause_screen = PauseScreen() dead_screen = DeadScreen() # Create Resume and Quit buttons resume_button = Button(resume_button_img, WIDTH // 2 – BUTTON_SIZE // 2, HEIGHT // 2 – BUTTON_SIZE // 2, action=lambda: toggle_pause()) quit_button = Button(quit_button_img, WIDTH // 2 – BUTTON_SIZE // 2, HEIGHT // 2 + BUTTON_SIZE // 2, action=lambda: quit_game()) respawn_button = Button(respawn_button_img, WIDTH // 2 – BUTTON_SIZE // 2, HEIGHT // 2 – BUTTON_SIZE // 2 – 15, action=lambda: respawn_player()) # Group for all sprites all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) all_sprites.add(pause_button) # Group for UI elements (Pause menu and buttons) ui_sprites = pygame.sprite.Group() ui_sprites.add(pause_button) # Camera scrolling variables camera_x = 0 # Camera x-position camera_y = 0 # Camera y-position camera_speed = 5 # Camera speed # Game loop running = True paused = False # Game starts in a non-paused state def toggle_pause(): global paused paused = not paused if paused: # Show the pause screen and buttons ui_sprites.add(pause_screen) ui_sprites.add(resume_button) ui_sprites.add(quit_button) else: # Hide the pause screen and buttons but don’t delete them ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) # If the player is alive, remove the respawn button when unpausing if player.rect.bottom > HEIGHT: ui_sprites.remove(respawn_button) # Remove respawn button when game resumes def dead_screen(): global paused paused = True # Pause the game when dead screen is active if player.rect.bottom > HEIGHT: # Create an instance of the DeadScreen class dead_screen_instance = DeadScreen() # Instantiate the DeadScreen class ui_sprites.add(dead_screen_instance) # Add the instance to ui_sprites ui_sprites.add(quit_button) # Add quit button ui_sprites.add(respawn_button) # Show respawn button when player dies # Ensure the resume button is removed when the player is dead ui_sprites.remove(resume_button) # Remove the resume button def quit_game(): pygame.quit() sys.exit() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Get mouse buttons mouse_buttons = pygame.mouse.get_pressed() if player.rect.bottom > HEIGHT: dead_screen() if mouse_buttons[0] == 1: # Left mouse button is pressed # Check if the pause button is clicked if pause_button.rect.collidepoint(pygame.mouse.get_pos()) and pause_button.toggle(): pause_button.press() # Add the press effect toggle_pause() # Toggle pause state # Check if the resume button is clicked if resume_button.toggle(): resume_button.press() ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) time.sleep(0.25) # Check if the quit button is clicked if quit_button.toggle(): quit_button.press() quit_game() if respawn_button.toggle(): respawn_button.press() # Update the pause button, which will return to normal after the mouse is not pressed pause_button.update(mouse_buttons) if not paused: # Update the game (only if not paused) player.update(ground_tiles) # Camera follows player camera_x = (player.rect.centerx – WIDTH // 2) * 0.1 # Smooth following on X axis camera_y = (player.rect.centery – HEIGHT // 2) * 0.1 # Smooth following on Y axis # Update ground tiles’ positions based on the camera for tile in ground_tiles: tile.rect.x -= camera_x tile.rect.y -= camera_y # Update Resume and Quit buttons resume_button.update(mouse_buttons) quit_button.update(mouse_buttons) # Draw everything screen.fill(WHITE) # Move all game sprites based on the camera for sprite in all_sprites: if not isinstance(sprite, PauseButton): # Skip the pause button and other UI elements sprite.rect.x -= camera_x sprite.rect.y -= camera_y all_sprites.draw(screen) # Draw UI elements last (UI is unaffected by camera) ui_sprites.draw(screen) # Refresh display pygame.display.flip() # Tick the clock clock.tick(FPS) # Quit Pygame pygame.QUIT() pdb.set_trace() sys.exit() submitted by /u/Granite900 [link] [comments] 

So, I wanted to make a python game and I used chat gpt for some parts and now I can’t get the respawn button to work, I tried but all it does is put up the pause menu and break the ui. What I want it to do is neatly close and respawn the player at the spawning platform. Feal free to neaten up, but it’s good enough.

Sprits (if needed, and the folder is needed because that’s the directory, tell me if you need it and it doesn’t work): https://www.mediafire.com/folder/6u0qlyyr0cfpt/img

Code:

import pygame import os import sys import random import time # Initialize Pygame pygame.init() import pdb # Set up fullscreen display screen_info = pygame.display.Info() WIDTH, HEIGHT = screen_info.current_w, screen_info.current_h screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) pygame.display.set_caption("ChronoShift Player Controller with Flipping") # Colors WHITE = (255, 255, 255) # FPS settings FPS = 60 # Load images from the img folder image_folder = "img" frame1 = pygame.image.load(os.path.join(image_folder, "Chronoshift_char1.png")).convert_alpha() frame2 = pygame.image.load(os.path.join(image_folder, "Chronoshift_char2.png")).convert_alpha() ground_tile_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_ground1.png")).convert_alpha() pause_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_pausebutton.png")).convert_alpha() pause_screen_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_pausescreen.png")).convert_alpha() dead_screen_img = pygame.image.load(os.path.join(image_folder, "Chronoshift-deadscreen.png")).convert_alpha() resume_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_resumebutton.png")).convert_alpha() quit_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_quitbutton.png")).convert_alpha() respawn_button_img = pygame.image.load(os.path.join(image_folder, "Chronoshift_respawnbutton.png")).convert_alpha() # Scale images to a consistent size (optional) CHARACTER_WIDTH, CHARACTER_HEIGHT = 64, 64 frame1 = pygame.transform.scale(frame1, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) frame2 = pygame.transform.scale(frame2, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT = 64, 64 ground_tile_img = pygame.transform.scale(ground_tile_img, (GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT)) # Respawn button setting RESPAWN_BUTTON_SIZE = 325 respawn_button_img = pygame.transform.scale(respawn_button_img, (RESPAWN_BUTTON_SIZE, RESPAWN_BUTTON_SIZE)) # Pause button settings PAUSE_BUTTON_SIZE = 100 # Increased button size pause_button_img = pygame.transform.scale(pause_button_img, (PAUSE_BUTTON_SIZE, PAUSE_BUTTON_SIZE)) # Resume and Quit button settings (larger buttons) BUTTON_SIZE = 325 # 325x325 buttons resume_button_img = pygame.transform.scale(resume_button_img, (BUTTON_SIZE, BUTTON_SIZE)) quit_button_img = pygame.transform.scale(quit_button_img, (BUTTON_SIZE, BUTTON_SIZE)) # Create a list of frames for animation frames = [frame1, frame2] # Clock for controlling FPS clock = pygame.time.Clock() # Gravity settings GRAVITY = 0.8 JUMP_STRENGTH = -18 # Player class class Player(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.images = frames self.current_frame = 0 self.image = self.images[self.current_frame] self.rect = self.image.get_rect(topleft=(x, y)) self.velocity_x = 5 self.velocity_y = 0 self.is_walking = False self.is_jumping = False self.facing_right = True self.animation_timer = 0 self.animation_speed = 200 self.respawned = False # Flag to track if the player respawned def update(self, ground_tiles): keys = pygame.key.get_pressed() self.is_walking = False if keys[pygame.K_LEFT]: self.rect.x -= self.velocity_x self.is_walking = True self.facing_right = False if keys[pygame.K_RIGHT]: self.rect.x += self.velocity_x self.is_walking = True self.facing_right = True if keys[pygame.K_SPACE] and not self.is_jumping: self.velocity_y = JUMP_STRENGTH self.is_jumping = True # Apply gravity self.velocity_y += GRAVITY self.rect.y += self.velocity_y # Respawn if the player falls too far down # Skip collision check if the player has respawned if self.respawned: self.respawned = False # Reset the flag after one update cycle else: # Only check for collisions if the player has not respawned self.check_collisions(ground_tiles) # Handle animation if self.is_walking: self.animate() else: self.current_frame = 0 self.image = self.images[self.current_frame] if not self.facing_right: self.image = pygame.transform.flip(self.images[self.current_frame], True, False) else: self.image = self.images[self.current_frame] def check_collisions(self, ground_tiles): # Check for collisions with ground tiles collided = pygame.sprite.spritecollide(self, ground_tiles, False) if collided: # Set the player on top of the ground tile self.rect.bottom = collided[0].rect.top self.velocity_y = 0 self.is_jumping = False def animate(self): # Handle animation timing self.animation_timer += clock.get_time() if self.animation_timer >= self.animation_speed: self.animation_timer = 0 self.current_frame = (self.current_frame + 1) % len(self.images) for tile in ground_tiles: # Calculate the distance from the player's current x-position to each ground tile distance = abs(self.rect.centerx - tile.rect.centerx) # Ground tile class class GroundTile(pygame.sprite.Sprite): def __init__(self, x, y, width=GROUND_TILE_WIDTH, height=GROUND_TILE_HEIGHT): super().__init__() self.image = pygame.transform.scale(ground_tile_img, (width, height)) # Allow dynamic scaling self.rect = self.image.get_rect(topleft=(x, y)) def respawn_player(): global paused player.rect.topleft = player.spawn_platform.rect.topleft # Reset player position player.velocity_y = 0 # Reset velocity player.respawned = True # Set respawn flag toggle_pause() # Unpause the game after respawn ui_sprites.remove(dead_screen) # Remove dead screen ui_sprites.remove(respawn_button) # Remove respawn button after respawn ui_sprites.add(resume_button) # Show the resume button after respawn # Pause button class class PauseButton(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_button_img self.rect = self.image.get_rect(topleft=(WIDTH - PAUSE_BUTTON_SIZE - 10, 10)) # Top-right corner self.original_image = self.image # Keep the original image for restoring after press self.press_effect_duration = 200 # Duration of the press effect in milliseconds self.press_timer = 0 self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed self.button_pressed = False # Track whether the button has been pressed in this frame def update(self, mouse_buttons): if self.is_pressed: self.press_timer += clock.get_time() if self.press_timer > self.press_effect_duration: self.is_pressed = False self.press_timer = 0 # Restore original size after pressing self.image = self.original_image # If mouse is not pressed anymore, return to original size if not self.is_pressed and mouse_buttons[0] == 0: self.image = self.original_image self.button_pressed = False # Reset button pressed state def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): if not self.button_pressed: self.button_pressed = True return True return False # Resume and Quit button classes class Button(pygame.sprite.Sprite): def __init__(self, image, x, y, action=None): super().__init__() self.image = image self.rect = self.image.get_rect(topleft=(x, y)) self.original_image = self.image self.action = action self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed def update(self, mouse_buttons): if self.is_pressed: self.is_pressed = False if self.action: self.action() # Call the action when the button is pressed # If mouse is not pressed anymore, return to original size if mouse_buttons[0] == 0: self.image = self.original_image def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): return self.rect.collidepoint(pygame.mouse.get_pos()) # Pause screen class class PauseScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_screen_img # Make the pause screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) class DeadScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = dead_screen_img # Make the dead screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) # Instantiate player further to the right player = Player(400, HEIGHT - 300) # Spawn player much further to the right # Create ground tiles (Parkour course with random heights and wider gaps) ground_tiles = pygame.sprite.Group() # Create the spawning platform (beginning of the course) spawn_platform = GroundTile(-300, HEIGHT - 150, width=600) # Set a larger width (600 pixels) ground_tiles.add(spawn_platform) # Create the player and assign the spawn platform player = Player(400, HEIGHT - 300) player.spawn_platform = spawn_platform # Assign the spawn platform to the player # Add player and other elements to sprite groups all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) #all_sprites.add(pause_button) # Add the pause button to the sprite group # Additional ground tiles, use default size ground_tile1 = GroundTile(0, HEIGHT - 150) ground_tile2 = GroundTile(50, HEIGHT - 150) ground_tile3 = GroundTile(100 , HEIGHT - 150) ground_tiles.add(ground_tile1, ground_tile2, ground_tile3) # Create 15 parkour platforms with random heights and wider gaps x_pos = 600 # Start a lot further to the right of the screen y_pos_base = HEIGHT - 250 # Base y position for platforms for i in range(15): x = x_pos + i * (GROUND_TILE_WIDTH + random.randint(80, 150)) # Wider gaps with random distances y = y_pos_base + random.randint(-100, 100) # Random height variation between -100 and +100 ground_tile = GroundTile(x, y) ground_tiles.add(ground_tile) # Create pause button pause_button = PauseButton() # Create pause screen (initially hidden) pause_screen = PauseScreen() dead_screen = DeadScreen() # Create Resume and Quit buttons resume_button = Button(resume_button_img, WIDTH // 2 - BUTTON_SIZE // 2, HEIGHT // 2 - BUTTON_SIZE // 2, action=lambda: toggle_pause()) quit_button = Button(quit_button_img, WIDTH // 2 - BUTTON_SIZE // 2, HEIGHT // 2 + BUTTON_SIZE // 2, action=lambda: quit_game()) respawn_button = Button(respawn_button_img, WIDTH // 2 - BUTTON_SIZE // 2, HEIGHT // 2 - BUTTON_SIZE // 2 - 15, action=lambda: respawn_player()) # Group for all sprites all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) all_sprites.add(pause_button) # Group for UI elements (Pause menu and buttons) ui_sprites = pygame.sprite.Group() ui_sprites.add(pause_button) # Camera scrolling variables camera_x = 0 # Camera x-position camera_y = 0 # Camera y-position camera_speed = 5 # Camera speed # Game loop running = True paused = False # Game starts in a non-paused state def toggle_pause(): global paused paused = not paused if paused: # Show the pause screen and buttons ui_sprites.add(pause_screen) ui_sprites.add(resume_button) ui_sprites.add(quit_button) else: # Hide the pause screen and buttons but don't delete them ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) # If the player is alive, remove the respawn button when unpausing if player.rect.bottom > HEIGHT: ui_sprites.remove(respawn_button) # Remove respawn button when game resumes def dead_screen(): global paused paused = True # Pause the game when dead screen is active if player.rect.bottom > HEIGHT: # Create an instance of the DeadScreen class dead_screen_instance = DeadScreen() # Instantiate the DeadScreen class ui_sprites.add(dead_screen_instance) # Add the instance to ui_sprites ui_sprites.add(quit_button) # Add quit button ui_sprites.add(respawn_button) # Show respawn button when player dies # Ensure the resume button is removed when the player is dead ui_sprites.remove(resume_button) # Remove the resume button def quit_game(): pygame.quit() sys.exit() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Get mouse buttons mouse_buttons = pygame.mouse.get_pressed() if player.rect.bottom > HEIGHT: dead_screen() if mouse_buttons[0] == 1: # Left mouse button is pressed # Check if the pause button is clicked if pause_button.rect.collidepoint(pygame.mouse.get_pos()) and pause_button.toggle(): pause_button.press() # Add the press effect toggle_pause() # Toggle pause state # Check if the resume button is clicked if resume_button.toggle(): resume_button.press() ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) time.sleep(0.25) # Check if the quit button is clicked if quit_button.toggle(): quit_button.press() quit_game() if respawn_button.toggle(): respawn_button.press() # Update the pause button, which will return to normal after the mouse is not pressed pause_button.update(mouse_buttons) if not paused: # Update the game (only if not paused) player.update(ground_tiles) # Camera follows player camera_x = (player.rect.centerx - WIDTH // 2) * 0.1 # Smooth following on X axis camera_y = (player.rect.centery - HEIGHT // 2) * 0.1 # Smooth following on Y axis # Update ground tiles' positions based on the camera for tile in ground_tiles: tile.rect.x -= camera_x tile.rect.y -= camera_y # Update Resume and Quit buttons resume_button.update(mouse_buttons) quit_button.update(mouse_buttons) # Draw everything screen.fill(WHITE) # Move all game sprites based on the camera for sprite in all_sprites: if not isinstance(sprite, PauseButton): # Skip the pause button and other UI elements sprite.rect.x -= camera_x sprite.rect.y -= camera_y all_sprites.draw(screen) # Draw UI elements last (UI is unaffected by camera) ui_sprites.draw(screen) # Refresh display pygame.display.flip() # Tick the clock clock.tick(FPS) # Quit Pygame pygame.QUIT() pdb.set_trace() sys.exit() 

submitted by /u/Granite900
[link] [comments]  So, I wanted to make a python game and I used chat gpt for some parts and now I can’t get the respawn button to work, I tried but all it does is put up the pause menu and break the ui. What I want it to do is neatly close and respawn the player at the spawning platform. Feal free to neaten up, but it’s good enough. Sprits (if needed, and the folder is needed because that’s the directory, tell me if you need it and it doesn’t work): https://www.mediafire.com/folder/6u0qlyyr0cfpt/img Code: import pygame import os import sys import random import time # Initialize Pygame pygame.init() import pdb # Set up fullscreen display screen_info = pygame.display.Info() WIDTH, HEIGHT = screen_info.current_w, screen_info.current_h screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) pygame.display.set_caption(“ChronoShift Player Controller with Flipping”) # Colors WHITE = (255, 255, 255) # FPS settings FPS = 60 # Load images from the img folder image_folder = “img” frame1 = pygame.image.load(os.path.join(image_folder, “Chronoshift_char1.png”)).convert_alpha() frame2 = pygame.image.load(os.path.join(image_folder, “Chronoshift_char2.png”)).convert_alpha() ground_tile_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_ground1.png”)).convert_alpha() pause_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_pausebutton.png”)).convert_alpha() pause_screen_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_pausescreen.png”)).convert_alpha() dead_screen_img = pygame.image.load(os.path.join(image_folder, “Chronoshift-deadscreen.png”)).convert_alpha() resume_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_resumebutton.png”)).convert_alpha() quit_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_quitbutton.png”)).convert_alpha() respawn_button_img = pygame.image.load(os.path.join(image_folder, “Chronoshift_respawnbutton.png”)).convert_alpha() # Scale images to a consistent size (optional) CHARACTER_WIDTH, CHARACTER_HEIGHT = 64, 64 frame1 = pygame.transform.scale(frame1, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) frame2 = pygame.transform.scale(frame2, (CHARACTER_WIDTH, CHARACTER_HEIGHT)) GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT = 64, 64 ground_tile_img = pygame.transform.scale(ground_tile_img, (GROUND_TILE_WIDTH, GROUND_TILE_HEIGHT)) # Respawn button setting RESPAWN_BUTTON_SIZE = 325 respawn_button_img = pygame.transform.scale(respawn_button_img, (RESPAWN_BUTTON_SIZE, RESPAWN_BUTTON_SIZE)) # Pause button settings PAUSE_BUTTON_SIZE = 100 # Increased button size pause_button_img = pygame.transform.scale(pause_button_img, (PAUSE_BUTTON_SIZE, PAUSE_BUTTON_SIZE)) # Resume and Quit button settings (larger buttons) BUTTON_SIZE = 325 # 325×325 buttons resume_button_img = pygame.transform.scale(resume_button_img, (BUTTON_SIZE, BUTTON_SIZE)) quit_button_img = pygame.transform.scale(quit_button_img, (BUTTON_SIZE, BUTTON_SIZE)) # Create a list of frames for animation frames = [frame1, frame2] # Clock for controlling FPS clock = pygame.time.Clock() # Gravity settings GRAVITY = 0.8 JUMP_STRENGTH = -18 # Player class class Player(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.images = frames self.current_frame = 0 self.image = self.images[self.current_frame] self.rect = self.image.get_rect(topleft=(x, y)) self.velocity_x = 5 self.velocity_y = 0 self.is_walking = False self.is_jumping = False self.facing_right = True self.animation_timer = 0 self.animation_speed = 200 self.respawned = False # Flag to track if the player respawned def update(self, ground_tiles): keys = pygame.key.get_pressed() self.is_walking = False if keys[pygame.K_LEFT]: self.rect.x -= self.velocity_x self.is_walking = True self.facing_right = False if keys[pygame.K_RIGHT]: self.rect.x += self.velocity_x self.is_walking = True self.facing_right = True if keys[pygame.K_SPACE] and not self.is_jumping: self.velocity_y = JUMP_STRENGTH self.is_jumping = True # Apply gravity self.velocity_y += GRAVITY self.rect.y += self.velocity_y # Respawn if the player falls too far down # Skip collision check if the player has respawned if self.respawned: self.respawned = False # Reset the flag after one update cycle else: # Only check for collisions if the player has not respawned self.check_collisions(ground_tiles) # Handle animation if self.is_walking: self.animate() else: self.current_frame = 0 self.image = self.images[self.current_frame] if not self.facing_right: self.image = pygame.transform.flip(self.images[self.current_frame], True, False) else: self.image = self.images[self.current_frame] def check_collisions(self, ground_tiles): # Check for collisions with ground tiles collided = pygame.sprite.spritecollide(self, ground_tiles, False) if collided: # Set the player on top of the ground tile self.rect.bottom = collided[0].rect.top self.velocity_y = 0 self.is_jumping = False def animate(self): # Handle animation timing self.animation_timer += clock.get_time() if self.animation_timer >= self.animation_speed: self.animation_timer = 0 self.current_frame = (self.current_frame + 1) % len(self.images) for tile in ground_tiles: # Calculate the distance from the player’s current x-position to each ground tile distance = abs(self.rect.centerx – tile.rect.centerx) # Ground tile class class GroundTile(pygame.sprite.Sprite): def __init__(self, x, y, width=GROUND_TILE_WIDTH, height=GROUND_TILE_HEIGHT): super().__init__() self.image = pygame.transform.scale(ground_tile_img, (width, height)) # Allow dynamic scaling self.rect = self.image.get_rect(topleft=(x, y)) def respawn_player(): global paused player.rect.topleft = player.spawn_platform.rect.topleft # Reset player position player.velocity_y = 0 # Reset velocity player.respawned = True # Set respawn flag toggle_pause() # Unpause the game after respawn ui_sprites.remove(dead_screen) # Remove dead screen ui_sprites.remove(respawn_button) # Remove respawn button after respawn ui_sprites.add(resume_button) # Show the resume button after respawn # Pause button class class PauseButton(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_button_img self.rect = self.image.get_rect(topleft=(WIDTH – PAUSE_BUTTON_SIZE – 10, 10)) # Top-right corner self.original_image = self.image # Keep the original image for restoring after press self.press_effect_duration = 200 # Duration of the press effect in milliseconds self.press_timer = 0 self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed self.button_pressed = False # Track whether the button has been pressed in this frame def update(self, mouse_buttons): if self.is_pressed: self.press_timer += clock.get_time() if self.press_timer > self.press_effect_duration: self.is_pressed = False self.press_timer = 0 # Restore original size after pressing self.image = self.original_image # If mouse is not pressed anymore, return to original size if not self.is_pressed and mouse_buttons[0] == 0: self.image = self.original_image self.button_pressed = False # Reset button pressed state def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): if not self.button_pressed: self.button_pressed = True return True return False # Resume and Quit button classes class Button(pygame.sprite.Sprite): def __init__(self, image, x, y, action=None): super().__init__() self.image = image self.rect = self.image.get_rect(topleft=(x, y)) self.original_image = self.image self.action = action self.is_pressed = False self.scale_factor = 0.8 # Shrink the button to 80% of its size when pressed def update(self, mouse_buttons): if self.is_pressed: self.is_pressed = False if self.action: self.action() # Call the action when the button is pressed # If mouse is not pressed anymore, return to original size if mouse_buttons[0] == 0: self.image = self.original_image def press(self): # Shrink the button to simulate a press new_width = int(self.original_image.get_width() * self.scale_factor) new_height = int(self.original_image.get_height() * self.scale_factor) self.image = pygame.transform.scale(self.original_image, (new_width, new_height)) self.is_pressed = True def toggle(self): return self.rect.collidepoint(pygame.mouse.get_pos()) # Pause screen class class PauseScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pause_screen_img # Make the pause screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) class DeadScreen(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = dead_screen_img # Make the dead screen moderately big (75% of screen width/height) self.image = pygame.transform.scale(self.image, (int(WIDTH * 0.75), int(HEIGHT * 0.75))) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT // 2)) # Instantiate player further to the right player = Player(400, HEIGHT – 300) # Spawn player much further to the right # Create ground tiles (Parkour course with random heights and wider gaps) ground_tiles = pygame.sprite.Group() # Create the spawning platform (beginning of the course) spawn_platform = GroundTile(-300, HEIGHT – 150, width=600) # Set a larger width (600 pixels) ground_tiles.add(spawn_platform) # Create the player and assign the spawn platform player = Player(400, HEIGHT – 300) player.spawn_platform = spawn_platform # Assign the spawn platform to the player # Add player and other elements to sprite groups all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) #all_sprites.add(pause_button) # Add the pause button to the sprite group # Additional ground tiles, use default size ground_tile1 = GroundTile(0, HEIGHT – 150) ground_tile2 = GroundTile(50, HEIGHT – 150) ground_tile3 = GroundTile(100 , HEIGHT – 150) ground_tiles.add(ground_tile1, ground_tile2, ground_tile3) # Create 15 parkour platforms with random heights and wider gaps x_pos = 600 # Start a lot further to the right of the screen y_pos_base = HEIGHT – 250 # Base y position for platforms for i in range(15): x = x_pos + i * (GROUND_TILE_WIDTH + random.randint(80, 150)) # Wider gaps with random distances y = y_pos_base + random.randint(-100, 100) # Random height variation between -100 and +100 ground_tile = GroundTile(x, y) ground_tiles.add(ground_tile) # Create pause button pause_button = PauseButton() # Create pause screen (initially hidden) pause_screen = PauseScreen() dead_screen = DeadScreen() # Create Resume and Quit buttons resume_button = Button(resume_button_img, WIDTH // 2 – BUTTON_SIZE // 2, HEIGHT // 2 – BUTTON_SIZE // 2, action=lambda: toggle_pause()) quit_button = Button(quit_button_img, WIDTH // 2 – BUTTON_SIZE // 2, HEIGHT // 2 + BUTTON_SIZE // 2, action=lambda: quit_game()) respawn_button = Button(respawn_button_img, WIDTH // 2 – BUTTON_SIZE // 2, HEIGHT // 2 – BUTTON_SIZE // 2 – 15, action=lambda: respawn_player()) # Group for all sprites all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(ground_tiles) all_sprites.add(pause_button) # Group for UI elements (Pause menu and buttons) ui_sprites = pygame.sprite.Group() ui_sprites.add(pause_button) # Camera scrolling variables camera_x = 0 # Camera x-position camera_y = 0 # Camera y-position camera_speed = 5 # Camera speed # Game loop running = True paused = False # Game starts in a non-paused state def toggle_pause(): global paused paused = not paused if paused: # Show the pause screen and buttons ui_sprites.add(pause_screen) ui_sprites.add(resume_button) ui_sprites.add(quit_button) else: # Hide the pause screen and buttons but don’t delete them ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) # If the player is alive, remove the respawn button when unpausing if player.rect.bottom > HEIGHT: ui_sprites.remove(respawn_button) # Remove respawn button when game resumes def dead_screen(): global paused paused = True # Pause the game when dead screen is active if player.rect.bottom > HEIGHT: # Create an instance of the DeadScreen class dead_screen_instance = DeadScreen() # Instantiate the DeadScreen class ui_sprites.add(dead_screen_instance) # Add the instance to ui_sprites ui_sprites.add(quit_button) # Add quit button ui_sprites.add(respawn_button) # Show respawn button when player dies # Ensure the resume button is removed when the player is dead ui_sprites.remove(resume_button) # Remove the resume button def quit_game(): pygame.quit() sys.exit() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Get mouse buttons mouse_buttons = pygame.mouse.get_pressed() if player.rect.bottom > HEIGHT: dead_screen() if mouse_buttons[0] == 1: # Left mouse button is pressed # Check if the pause button is clicked if pause_button.rect.collidepoint(pygame.mouse.get_pos()) and pause_button.toggle(): pause_button.press() # Add the press effect toggle_pause() # Toggle pause state # Check if the resume button is clicked if resume_button.toggle(): resume_button.press() ui_sprites.remove(pause_screen) ui_sprites.remove(resume_button) ui_sprites.remove(quit_button) time.sleep(0.25) # Check if the quit button is clicked if quit_button.toggle(): quit_button.press() quit_game() if respawn_button.toggle(): respawn_button.press() # Update the pause button, which will return to normal after the mouse is not pressed pause_button.update(mouse_buttons) if not paused: # Update the game (only if not paused) player.update(ground_tiles) # Camera follows player camera_x = (player.rect.centerx – WIDTH // 2) * 0.1 # Smooth following on X axis camera_y = (player.rect.centery – HEIGHT // 2) * 0.1 # Smooth following on Y axis # Update ground tiles’ positions based on the camera for tile in ground_tiles: tile.rect.x -= camera_x tile.rect.y -= camera_y # Update Resume and Quit buttons resume_button.update(mouse_buttons) quit_button.update(mouse_buttons) # Draw everything screen.fill(WHITE) # Move all game sprites based on the camera for sprite in all_sprites: if not isinstance(sprite, PauseButton): # Skip the pause button and other UI elements sprite.rect.x -= camera_x sprite.rect.y -= camera_y all_sprites.draw(screen) # Draw UI elements last (UI is unaffected by camera) ui_sprites.draw(screen) # Refresh display pygame.display.flip() # Tick the clock clock.tick(FPS) # Quit Pygame pygame.QUIT() pdb.set_trace() sys.exit() submitted by /u/Granite900 [link] [comments]

Read more

help with code for lab /u/No_Air834 Python Education

help with code for lab /u/No_Air834 Python Education

ok i’m going to say i’m sorry in advance – the code i’m working with is chatgpt generated, i know it’s horrible for coding, but i have literally 0 experience with python and i need it for this specific thing for my lab.

i need it to run to load an excel file, calculate the averages for values in a column titled “plddt” for each protein. so, for example, with the data in the image below, it would find that the average “plddt” value for protein 1 would be the average of the values in column I for rows 2 through 9.

the problem i’m having is that i don’t know if the code chatgpt generated even works, and i don’t know how to put it in a new file and execute it to test in the first place. please explain this to me like i’m 4, i’ve been looking all over the internet for guides for hours and somehow still haven’t figured it out. i would greatly appreciate it, thank you all so much:) and please let me know if i’ve explained something poorly or done something wrong u_u

import pandas as pd

import os

# Load the Excel file

file_path = '/mnt/data/HTT_data.xlsx'

try:

data = pd.read_excel(file_path)

except FileNotFoundError:

raise FileNotFoundError(f"The file at {file_path} does not exist. Please check the path and try again.")

except Exception as e:

raise Exception(f"An error occurred while reading the Excel file: {e}")

# Check if required columns exist

if 'residue' not in data.columns or 'plddt' not in data.columns:

raise ValueError("The Excel file must contain 'residue' and 'plddt' columns.")

# Group by 'residue' and calculate the average of 'plddt'

average_plddt = data.groupby('residue')['plddt'].mean().reset_index()

# Rename columns for clarity

average_plddt.columns = ['residue', 'average_plddt']

# Save the results to a new Excel file

output_file = '/mnt/data/average_plddt_results.xlsx'

if not os.access(os.path.dirname(output_file), os.W_OK):

raise PermissionError(f"The directory {os.path.dirname(output_file)} is not writable. Please check permissions.")

average_plddt.to_excel(output_file, index=False)

print(f"The averages have been calculated and saved to: {output_file}")

https://preview.redd.it/79wk9qebma7e1.png?width=918&format=png&auto=webp&s=27985ed9eeff1c680d54661b228fe6fab30a80d6

submitted by /u/No_Air834
[link] [comments]

​r/learnpython ok i’m going to say i’m sorry in advance – the code i’m working with is chatgpt generated, i know it’s horrible for coding, but i have literally 0 experience with python and i need it for this specific thing for my lab. i need it to run to load an excel file, calculate the averages for values in a column titled “plddt” for each protein. so, for example, with the data in the image below, it would find that the average “plddt” value for protein 1 would be the average of the values in column I for rows 2 through 9. the problem i’m having is that i don’t know if the code chatgpt generated even works, and i don’t know how to put it in a new file and execute it to test in the first place. please explain this to me like i’m 4, i’ve been looking all over the internet for guides for hours and somehow still haven’t figured it out. i would greatly appreciate it, thank you all so much:) and please let me know if i’ve explained something poorly or done something wrong u_u import pandas as pd import os # Load the Excel file file_path = ‘/mnt/data/HTT_data.xlsx’ try: data = pd.read_excel(file_path) except FileNotFoundError: raise FileNotFoundError(f”The file at {file_path} does not exist. Please check the path and try again.”) except Exception as e: raise Exception(f”An error occurred while reading the Excel file: {e}”) # Check if required columns exist if ‘residue’ not in data.columns or ‘plddt’ not in data.columns: raise ValueError(“The Excel file must contain ‘residue’ and ‘plddt’ columns.”) # Group by ‘residue’ and calculate the average of ‘plddt’ average_plddt = data.groupby(‘residue’)[‘plddt’].mean().reset_index() # Rename columns for clarity average_plddt.columns = [‘residue’, ‘average_plddt’] # Save the results to a new Excel file output_file = ‘/mnt/data/average_plddt_results.xlsx’ if not os.access(os.path.dirname(output_file), os.W_OK): raise PermissionError(f”The directory {os.path.dirname(output_file)} is not writable. Please check permissions.”) average_plddt.to_excel(output_file, index=False) print(f”The averages have been calculated and saved to: {output_file}”) https://preview.redd.it/79wk9qebma7e1.png?width=918&format=png&auto=webp&s=27985ed9eeff1c680d54661b228fe6fab30a80d6 submitted by /u/No_Air834 [link] [comments] 

ok i’m going to say i’m sorry in advance – the code i’m working with is chatgpt generated, i know it’s horrible for coding, but i have literally 0 experience with python and i need it for this specific thing for my lab.

i need it to run to load an excel file, calculate the averages for values in a column titled “plddt” for each protein. so, for example, with the data in the image below, it would find that the average “plddt” value for protein 1 would be the average of the values in column I for rows 2 through 9.

the problem i’m having is that i don’t know if the code chatgpt generated even works, and i don’t know how to put it in a new file and execute it to test in the first place. please explain this to me like i’m 4, i’ve been looking all over the internet for guides for hours and somehow still haven’t figured it out. i would greatly appreciate it, thank you all so much:) and please let me know if i’ve explained something poorly or done something wrong u_u

import pandas as pd

import os

# Load the Excel file

file_path = '/mnt/data/HTT_data.xlsx'

try:

data = pd.read_excel(file_path)

except FileNotFoundError:

raise FileNotFoundError(f"The file at {file_path} does not exist. Please check the path and try again.")

except Exception as e:

raise Exception(f"An error occurred while reading the Excel file: {e}")

# Check if required columns exist

if 'residue' not in data.columns or 'plddt' not in data.columns:

raise ValueError("The Excel file must contain 'residue' and 'plddt' columns.")

# Group by 'residue' and calculate the average of 'plddt'

average_plddt = data.groupby('residue')['plddt'].mean().reset_index()

# Rename columns for clarity

average_plddt.columns = ['residue', 'average_plddt']

# Save the results to a new Excel file

output_file = '/mnt/data/average_plddt_results.xlsx'

if not os.access(os.path.dirname(output_file), os.W_OK):

raise PermissionError(f"The directory {os.path.dirname(output_file)} is not writable. Please check permissions.")

average_plddt.to_excel(output_file, index=False)

print(f"The averages have been calculated and saved to: {output_file}")

https://preview.redd.it/79wk9qebma7e1.png?width=918&format=png&auto=webp&s=27985ed9eeff1c680d54661b228fe6fab30a80d6

submitted by /u/No_Air834
[link] [comments]  ok i’m going to say i’m sorry in advance – the code i’m working with is chatgpt generated, i know it’s horrible for coding, but i have literally 0 experience with python and i need it for this specific thing for my lab. i need it to run to load an excel file, calculate the averages for values in a column titled “plddt” for each protein. so, for example, with the data in the image below, it would find that the average “plddt” value for protein 1 would be the average of the values in column I for rows 2 through 9. the problem i’m having is that i don’t know if the code chatgpt generated even works, and i don’t know how to put it in a new file and execute it to test in the first place. please explain this to me like i’m 4, i’ve been looking all over the internet for guides for hours and somehow still haven’t figured it out. i would greatly appreciate it, thank you all so much:) and please let me know if i’ve explained something poorly or done something wrong u_u import pandas as pd import os # Load the Excel file file_path = ‘/mnt/data/HTT_data.xlsx’ try: data = pd.read_excel(file_path) except FileNotFoundError: raise FileNotFoundError(f”The file at {file_path} does not exist. Please check the path and try again.”) except Exception as e: raise Exception(f”An error occurred while reading the Excel file: {e}”) # Check if required columns exist if ‘residue’ not in data.columns or ‘plddt’ not in data.columns: raise ValueError(“The Excel file must contain ‘residue’ and ‘plddt’ columns.”) # Group by ‘residue’ and calculate the average of ‘plddt’ average_plddt = data.groupby(‘residue’)[‘plddt’].mean().reset_index() # Rename columns for clarity average_plddt.columns = [‘residue’, ‘average_plddt’] # Save the results to a new Excel file output_file = ‘/mnt/data/average_plddt_results.xlsx’ if not os.access(os.path.dirname(output_file), os.W_OK): raise PermissionError(f”The directory {os.path.dirname(output_file)} is not writable. Please check permissions.”) average_plddt.to_excel(output_file, index=False) print(f”The averages have been calculated and saved to: {output_file}”) https://preview.redd.it/79wk9qebma7e1.png?width=918&format=png&auto=webp&s=27985ed9eeff1c680d54661b228fe6fab30a80d6 submitted by /u/No_Air834 [link] [comments]

Read more

Extracting some data from a website? /u/agent_wolfe Python Education

Extracting some data from a website? /u/agent_wolfe Python Education

I’m having some difficulty with this python program to extract some data from a website.

import requests from bs4 import BeautifulSoup import re import json import csv def extract_data_from_url(url): try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') script_tags = soup.find_all('script') print(f"Number of script tags found: {len(script_tags)}") prompt = "Not Found" date = "Not Found" for index, script in enumerate(script_tags): print(f"Checking script {index+1}...") if "metadata" in script.text: # Look for the presence of 'metadata' print (script.text) # PRINTS OUT SCRIPT CHUNK HERE else: print(f"Script {index+1} does not contain 'metadata'.") return { 'URL': url, 'Prompt': prompt, 'Date': date, 'Lyrics': prompt } except Exception as e: print(f"Error processing {url}: {e}") return { 'URL': url, 'Prompt': 'Error', 'Date': 'Error', 'Lyrics': 'Error' } def main(): # Input: List of URLs input_file = 'urls.txt' # File containing one URL per line output_file = 'extracted_data.csv' # File to save the extracted data try: with open(input_file, 'r') as file: urls = [line.strip() for line in file if line.strip()] # Extract data from each URL extracted_data = [] for url in urls: print(f"Processing: {url}") data = extract_data_from_url(url) extracted_data.append(data) # Save the extracted data to a CSV file with open(output_file, 'w', newline='', encoding='utf-8') as csvfile: fieldnames = ['URL', 'Title', 'Prompt', 'Date', 'Lyrics'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(extracted_data) print(f"Data extraction complete. Saved to {output_file}") except FileNotFoundError: print(f"Error: The file {input_file} was not found.") except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == '__main__': main() 

What’s happening:

  • I have each URL in the urls.txt on a separate line.
  • I am looking for “Title”, “Prompt”, “Date”, and “Tags” which are stored in a <script> as "metadata"
  • When I run the python program, it goes to each webpage and tries to locate each <script> section. There are 49 of them.
  • (The data ends up as HTML, but I think the program loads the page before that happens.)
  • The script with the metadata is Script 46.
  • When it finds the correct one, it # PRINTS OUT SCRIPT CHUNK HERE

That’s where I’ve gotten stuck. I’m not sure how to get the correct details out of this chunk of data? Here’s what it’s printing out:

Checking script 46... self.__next_f.push([1,"16:I[some stuff...,[(some stuff.....],some stuff...]n6:[some stuff..."metadata":{"tags":"TAGS","prompt":"PROMPT",some stuff...},some stuff...,"created_at":"DATE"]) 

(It contained 2250 characters but I tried to simplify it to just the parts I need.)

TLDR:

The program is finding the right script section with Metadata. I’m just not sure how to get the Tags, Prompt, and Date so they can be saved to the CSV file.

submitted by /u/agent_wolfe
[link] [comments]

​r/learnpython I’m having some difficulty with this python program to extract some data from a website. import requests from bs4 import BeautifulSoup import re import json import csv def extract_data_from_url(url): try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, ‘html.parser’) script_tags = soup.find_all(‘script’) print(f”Number of script tags found: {len(script_tags)}”) prompt = “Not Found” date = “Not Found” for index, script in enumerate(script_tags): print(f”Checking script {index+1}…”) if “metadata” in script.text: # Look for the presence of ‘metadata’ print (script.text) # PRINTS OUT SCRIPT CHUNK HERE else: print(f”Script {index+1} does not contain ‘metadata’.”) return { ‘URL’: url, ‘Prompt’: prompt, ‘Date’: date, ‘Lyrics’: prompt } except Exception as e: print(f”Error processing {url}: {e}”) return { ‘URL’: url, ‘Prompt’: ‘Error’, ‘Date’: ‘Error’, ‘Lyrics’: ‘Error’ } def main(): # Input: List of URLs input_file = ‘urls.txt’ # File containing one URL per line output_file = ‘extracted_data.csv’ # File to save the extracted data try: with open(input_file, ‘r’) as file: urls = [line.strip() for line in file if line.strip()] # Extract data from each URL extracted_data = [] for url in urls: print(f”Processing: {url}”) data = extract_data_from_url(url) extracted_data.append(data) # Save the extracted data to a CSV file with open(output_file, ‘w’, newline=”, encoding=’utf-8′) as csvfile: fieldnames = [‘URL’, ‘Title’, ‘Prompt’, ‘Date’, ‘Lyrics’] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(extracted_data) print(f”Data extraction complete. Saved to {output_file}”) except FileNotFoundError: print(f”Error: The file {input_file} was not found.”) except Exception as e: print(f”An unexpected error occurred: {e}”) if __name__ == ‘__main__’: main() What’s happening: I have each URL in the urls.txt on a separate line. I am looking for “Title”, “Prompt”, “Date”, and “Tags” which are stored in a <script> as “metadata” When I run the python program, it goes to each webpage and tries to locate each <script> section. There are 49 of them. (The data ends up as HTML, but I think the program loads the page before that happens.) The script with the metadata is Script 46. When it finds the correct one, it # PRINTS OUT SCRIPT CHUNK HERE That’s where I’ve gotten stuck. I’m not sure how to get the correct details out of this chunk of data? Here’s what it’s printing out: Checking script 46… self.__next_f.push([1,”16:I[some stuff…,[(some stuff…..],some stuff…]n6:[some stuff…”metadata”:{“tags”:”TAGS”,”prompt”:”PROMPT”,some stuff…},some stuff…,”created_at”:”DATE”]) (It contained 2250 characters but I tried to simplify it to just the parts I need.) TLDR: The program is finding the right script section with Metadata. I’m just not sure how to get the Tags, Prompt, and Date so they can be saved to the CSV file. submitted by /u/agent_wolfe [link] [comments] 

I’m having some difficulty with this python program to extract some data from a website.

import requests from bs4 import BeautifulSoup import re import json import csv def extract_data_from_url(url): try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') script_tags = soup.find_all('script') print(f"Number of script tags found: {len(script_tags)}") prompt = "Not Found" date = "Not Found" for index, script in enumerate(script_tags): print(f"Checking script {index+1}...") if "metadata" in script.text: # Look for the presence of 'metadata' print (script.text) # PRINTS OUT SCRIPT CHUNK HERE else: print(f"Script {index+1} does not contain 'metadata'.") return { 'URL': url, 'Prompt': prompt, 'Date': date, 'Lyrics': prompt } except Exception as e: print(f"Error processing {url}: {e}") return { 'URL': url, 'Prompt': 'Error', 'Date': 'Error', 'Lyrics': 'Error' } def main(): # Input: List of URLs input_file = 'urls.txt' # File containing one URL per line output_file = 'extracted_data.csv' # File to save the extracted data try: with open(input_file, 'r') as file: urls = [line.strip() for line in file if line.strip()] # Extract data from each URL extracted_data = [] for url in urls: print(f"Processing: {url}") data = extract_data_from_url(url) extracted_data.append(data) # Save the extracted data to a CSV file with open(output_file, 'w', newline='', encoding='utf-8') as csvfile: fieldnames = ['URL', 'Title', 'Prompt', 'Date', 'Lyrics'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(extracted_data) print(f"Data extraction complete. Saved to {output_file}") except FileNotFoundError: print(f"Error: The file {input_file} was not found.") except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == '__main__': main() 

What’s happening:

  • I have each URL in the urls.txt on a separate line.
  • I am looking for “Title”, “Prompt”, “Date”, and “Tags” which are stored in a <script> as "metadata"
  • When I run the python program, it goes to each webpage and tries to locate each <script> section. There are 49 of them.
  • (The data ends up as HTML, but I think the program loads the page before that happens.)
  • The script with the metadata is Script 46.
  • When it finds the correct one, it # PRINTS OUT SCRIPT CHUNK HERE

That’s where I’ve gotten stuck. I’m not sure how to get the correct details out of this chunk of data? Here’s what it’s printing out:

Checking script 46... self.__next_f.push([1,"16:I[some stuff...,[(some stuff.....],some stuff...]n6:[some stuff..."metadata":{"tags":"TAGS","prompt":"PROMPT",some stuff...},some stuff...,"created_at":"DATE"]) 

(It contained 2250 characters but I tried to simplify it to just the parts I need.)

TLDR:

The program is finding the right script section with Metadata. I’m just not sure how to get the Tags, Prompt, and Date so they can be saved to the CSV file.

submitted by /u/agent_wolfe
[link] [comments]  I’m having some difficulty with this python program to extract some data from a website. import requests from bs4 import BeautifulSoup import re import json import csv def extract_data_from_url(url): try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, ‘html.parser’) script_tags = soup.find_all(‘script’) print(f”Number of script tags found: {len(script_tags)}”) prompt = “Not Found” date = “Not Found” for index, script in enumerate(script_tags): print(f”Checking script {index+1}…”) if “metadata” in script.text: # Look for the presence of ‘metadata’ print (script.text) # PRINTS OUT SCRIPT CHUNK HERE else: print(f”Script {index+1} does not contain ‘metadata’.”) return { ‘URL’: url, ‘Prompt’: prompt, ‘Date’: date, ‘Lyrics’: prompt } except Exception as e: print(f”Error processing {url}: {e}”) return { ‘URL’: url, ‘Prompt’: ‘Error’, ‘Date’: ‘Error’, ‘Lyrics’: ‘Error’ } def main(): # Input: List of URLs input_file = ‘urls.txt’ # File containing one URL per line output_file = ‘extracted_data.csv’ # File to save the extracted data try: with open(input_file, ‘r’) as file: urls = [line.strip() for line in file if line.strip()] # Extract data from each URL extracted_data = [] for url in urls: print(f”Processing: {url}”) data = extract_data_from_url(url) extracted_data.append(data) # Save the extracted data to a CSV file with open(output_file, ‘w’, newline=”, encoding=’utf-8′) as csvfile: fieldnames = [‘URL’, ‘Title’, ‘Prompt’, ‘Date’, ‘Lyrics’] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(extracted_data) print(f”Data extraction complete. Saved to {output_file}”) except FileNotFoundError: print(f”Error: The file {input_file} was not found.”) except Exception as e: print(f”An unexpected error occurred: {e}”) if __name__ == ‘__main__’: main() What’s happening: I have each URL in the urls.txt on a separate line. I am looking for “Title”, “Prompt”, “Date”, and “Tags” which are stored in a <script> as “metadata” When I run the python program, it goes to each webpage and tries to locate each <script> section. There are 49 of them. (The data ends up as HTML, but I think the program loads the page before that happens.) The script with the metadata is Script 46. When it finds the correct one, it # PRINTS OUT SCRIPT CHUNK HERE That’s where I’ve gotten stuck. I’m not sure how to get the correct details out of this chunk of data? Here’s what it’s printing out: Checking script 46… self.__next_f.push([1,”16:I[some stuff…,[(some stuff…..],some stuff…]n6:[some stuff…”metadata”:{“tags”:”TAGS”,”prompt”:”PROMPT”,some stuff…},some stuff…,”created_at”:”DATE”]) (It contained 2250 characters but I tried to simplify it to just the parts I need.) TLDR: The program is finding the right script section with Metadata. I’m just not sure how to get the Tags, Prompt, and Date so they can be saved to the CSV file. submitted by /u/agent_wolfe [link] [comments]

Read more

Can someone review my code? /u/-not_a_knife Python Education

Can someone review my code? /u/-not_a_knife Python Education

I wrote a function for Curses that takes a 2D array and returns a window layout.

This is the first time I wrote something that I’d use and required more than a couple hours of work. I’d really appreciate any feedback, from the code, the comments, and the docstrings. I’m self taught so I don’t have a senior dev to tell me my code sucks.

https://github.com/BrickEater/python-curses-grid

submitted by /u/-not_a_knife
[link] [comments]

​r/learnpython I wrote a function for Curses that takes a 2D array and returns a window layout. This is the first time I wrote something that I’d use and required more than a couple hours of work. I’d really appreciate any feedback, from the code, the comments, and the docstrings. I’m self taught so I don’t have a senior dev to tell me my code sucks. https://github.com/BrickEater/python-curses-grid submitted by /u/-not_a_knife [link] [comments] 

I wrote a function for Curses that takes a 2D array and returns a window layout.

This is the first time I wrote something that I’d use and required more than a couple hours of work. I’d really appreciate any feedback, from the code, the comments, and the docstrings. I’m self taught so I don’t have a senior dev to tell me my code sucks.

https://github.com/BrickEater/python-curses-grid

submitted by /u/-not_a_knife
[link] [comments]  I wrote a function for Curses that takes a 2D array and returns a window layout. This is the first time I wrote something that I’d use and required more than a couple hours of work. I’d really appreciate any feedback, from the code, the comments, and the docstrings. I’m self taught so I don’t have a senior dev to tell me my code sucks. https://github.com/BrickEater/python-curses-grid submitted by /u/-not_a_knife [link] [comments]

Read more