Skip to content

Instantly share code, notes, and snippets.

@quapka
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quapka/215f5ed5fbb90ad781a5 to your computer and use it in GitHub Desktop.
Save quapka/215f5ed5fbb90ad781a5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import pygame
import sys
import random
class Ball(object):
""" ball class, draws and moves the ball """
def __init__(self, screen, x, y):
self.screen = screen
self.x = x
self.y = y
self.pos = (self.x, self.y)
self.radius = 25
self.draw_ball()
def draw_ball(self):
pygame.draw.circle(self.screen,
(255,255,255),
(int(self.x), int(self.y)),
self.radius)
def move(self, dx, dy):
self.x += dx
self.y += dy
self.draw_ball()
pygame.init()
pygame.display.set_caption('Moving ball')
screen = pygame.display.set_mode((640, 480))
# get the pygame clock
clock = pygame.time.Clock()
speedx = 500#random.randint(0,250)
speedy = 500#random.randint(0,250)
# initialize the ball
ball = Ball(screen, 100, 200)
# the orientation of the direction
or_x = 1
or_y = 1
while True:
# check for closing
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# get seconds and change dx, dy
mils = clock.tick()
secs = mils / 1000.
dx = speedx * secs * or_x
dy = speedy * secs * or_y
# refill the black background in order
# to "delete" the last ball
screen.fill((0,0,0))
# move the ball and redraw it
ball.move(dx, dy)
# conditions if the ball hits the wall
# change the orientations accordingly
if ball.x > 640 - ball.radius:
or_x *= -1
elif ball.x < ball.radius:
or_x *= -1
elif ball.y > 480 - ball.radius:
or_y *= -1
elif ball.y < ball.radius:
or_y *= -1
pygame.display.update()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment