Python Forum
[PyGame] Encountered a logic problem in my project
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Encountered a logic problem in my project
#1
I wrote some codes for my ball to don't spawn border over.But my ball spawns over of border.Anyone you help me this logic problem? If you won't change my coding logic , I will happy.Also,I am sorry for my english.Now I'm sharing my code.

import pygame
import random
import time

pygame.init()

display_width = 600
display_height = 400

gameDisplay = pygame.display.set_mode((display_width,display_height))

white = (255,255,255)
red = (255,0,0)

ball_x = int(display_width/2)
ball_y = int(display_height/2)



clock = pygame.time.Clock()

gameExit = False

while not gameExit:
    ball_list = []
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            gameExit = True
      
    ball_speed_x = random.randrange(-5,5)
    ball_speed_y = random.randrange(-5,5)           
    

    
    while ball_speed_x == 0 and ball_speed_y == 0:
        print(1)
        ball_speed_x = random.randrange(-5,5)
        ball_speed_y = random.randrange(-5,5)
        
    if ball_x > display_width - 10 or ball_x < 10:
        ball_speed_x *= -1
    if ball_y > display_height - 10 or ball_y < 10:
        ball_speed_y *= -1
        
    ball_x += ball_speed_x
    ball_y += ball_speed_y


    
        
    ball_list.append([ball_x,ball_y])
    
    gameDisplay.fill(white)
    
    for ball_coordinates in ball_list:
        pygame.draw.circle(gameDisplay,red,[ball_coordinates[0],ball_coordinates[1]],10,10)
       # print("Coordinates:" + str(ball_coordinates) + "\n" + "Ball x:" + str(ball_x) + "," + "Ball y:" + str(ball_y) + "\n" + "ball speed x:" +str(ball_speed_x) + "ball speed y:"+ str(ball_speed_y))
        
    
    
    pygame.display.flip()
    clock.tick(15)
pygame.quit()
quit()
Reply
#2
I have solved my problem.
Reply
#3
That is great to hear. You are welcome to share the solution with other readers.
Reply
#4
if ball_x > display_width - 10 or ball_x < 10:
        ball_speed_x *= -1
    if ball_y > display_height - 10 or ball_y < 10:
        ball_speed_y *= -1
10 of the here,must be 10+ball_x_speed (first line), 10+speed_y_speed (second line),because ball_x + ball_x_speed and ball_y + ball_y_speed must be smaller than display width and display height => 10(radius of ball) + ball_speed_x or ball_speed_y random number of(-5,5)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Game Logic problem with a "The Game of Life" Replication Coda 2 3,139 Dec-24-2018, 09:26 AM
Last Post: Coda
  My Pygame Project's Problem **huh** osmanb06 2 3,674 Nov-06-2018, 09:27 AM
Last Post: osmanb06

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020