#MonthOfCode day 20 - play
import random | |
import pygame | |
from pygame.locals import * | |
SCREEN_W = 640 | |
SCREEN_H = 480 | |
def refeshFunction(): | |
DISPLAYSURF.fill( pygame.Color('antiquewhite3') ) | |
# draws the paddle | |
rect_rep_paddle =\ | |
pygame.Rect( (pos_x_paddle-(PADDLE_X_SIZE/2), pos_y_paddle), | |
(PADDLE_X_SIZE, PADDLE_Y_SIZE)) # format: (left,top) , (width,height) | |
pygame.draw.rect( DISPLAYSURF, pygame.Color('black'), rect_rep_paddle ) | |
# draws the ball | |
pygame.draw.circle( DISPLAYSURF, pygame.Color('black'), | |
(ball_x, ball_y), BALL_RAD ) | |
pygame.display.update() | |
# init. pygame libr; create the screen | |
pygame.init() | |
DISPLAYSURF = pygame.display.set_mode( (SCREEN_W, SCREEN_H)) | |
PADDLE_X_SIZE, PADDLE_Y_SIZE = 128, 32 | |
BALL_RAD = 16 | |
started_playing= False | |
ball_x = pos_x_paddle = SCREEN_W/2 | |
ball_y = pos_y_paddle = SCREEN_H - 2*PADDLE_Y_SIZE | |
ball_y -= BALL_RAD | |
program_done = False | |
ball_delay = 11 | |
counter = 0 | |
#main loop | |
while not program_done: | |
for event in pygame.event.get(): | |
if event.type == QUIT: | |
program_done = True | |
break | |
if event.type == pygame.MOUSEMOTION: | |
pos_x_paddle = pygame.mouse.get_pos()[0] | |
#blocking the paddle if it gets out of the screen | |
if( pos_x_paddle-(PADDLE_X_SIZE/2) <0): | |
pos_x_paddle = (PADDLE_X_SIZE/2) | |
if (pos_x_paddle+(PADDLE_X_SIZE/2)>=SCREEN_W): | |
pos_x_paddle=SCREEN_W -(PADDLE_X_SIZE/2)-1 | |
#copying the new position to the ball if not playing yet | |
if(not started_playing): | |
ball_x = pos_x_paddle | |
if event.type == pygame.MOUSEBUTTONDOWN : | |
if not started_playing: | |
started_playing = True | |
vx,vy = 2, -2 | |
# physics of the ball | |
if(started_playing and counter==0 ): | |
ball_x+=vx | |
ball_y+=vy | |
if(ball_x-BALL_RAD<0): | |
ball_x=0+BALL_RAD | |
vx*=-1 | |
if(ball_x+BALL_RAD>=SCREEN_W): | |
ball_x=SCREEN_W-BALL_RAD-1 | |
vx*=-1 | |
if(ball_y-BALL_RAD<0): | |
ball_y=0+BALL_RAD | |
vy*=-1 | |
if(ball_y+BALL_RAD>=SCREEN_H): | |
ball_y=SCREEN_H-BALL_RAD-1 | |
vy*=-1 | |
if(ball_y > pos_y_paddle-(PADDLE_Y_SIZE/2) and | |
ball_x > pos_x_paddle-(PADDLE_X_SIZE/2) and | |
ball_x < pos_x_paddle+(PADDLE_X_SIZE/2) ): | |
vy*=-1 | |
#accelerating the ball on every good hit | |
ball_delay-=1 | |
if(ball_delay<3): | |
ball_delay=3 | |
counter+=1 | |
counter=counter%ball_delay #we move the ball only every ball_delay iterations | |
refeshFunction() | |
pygame.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment