I have created a sketch code which should move the ball with acceleration after pressing key. The ball would be accelerated in direction of the keyboard arrow, then rebound from active edge of the window. Here is the code:
import pygame, sys
pygame.init()
def main():
clock = pygame.time.Clock()
pygame.display.set_caption('BasketBall')
icon = pygame.image.load('/home/michael/game/ballgame.png')
pygame.display.set_icon(icon)
pygame.mixer.music.load(r'/home/michael/game/soundtrack.mp3')
pygame.mixer.music.play(-1)
size = width, height = 800, 600
screen = pygame.display.set_mode(size)
speed = [0, 0]
accel = [0.1, 0.1]
image = pygame.image.load(r'/home/michael/game/background.png')
image = pygame.transform.scale(image, size)
surf_center = (
(width-image.get_width())/2,
(height-image.get_height())/2
)
screen.blit(image, surf_center)
ball = pygame.image.load('/home/michael/game/ball.png')
ball = pygame.transform.scale(ball, (ball.get_width()//10, ball.get_height()//10))
screen.blit(ball, (width/10, height/10))
ballrect = ball.get_rect(center=(width/2, height/2))
pygame.display.flip()
while True:
clock.tick(60)
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]: sys.exit()
if keys[pygame.K_UP]:
ballrect = ballrect.move([0,-50])
elif keys[pygame.K_DOWN]:
ballrect = ballrect.move([0,50])
elif keys[pygame.K_LEFT]:
ballrect = ballrect.move([-50,0])
elif keys[pygame.K_RIGHT]:
ballrect = ballrect.move([50,0])
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.blit(image,surf_center)
screen.blit(ball,ballrect)
pygame.display.flip()
if __name__ == '__main__':
main()
pygame.quit()
sys.exit()
It seems complicated, maybe because I'm still studying pygame lib, but I wanted to accelerate ball until the key is pressed. The ball should ideally elastic rebound from active window edges.