Python

FbCadCam community discussion

Moderators: yajra1219, Jayem, kitty_webb, Ywsp, joanCruz03, shela

Post Reply
owen
Site Admin
Posts: 657
Joined: Thu Apr 13, 2017 12:14 pm

Python

Post by owen » Wed Jul 01, 2020 1:10 am

I'm having fun learning python
here's my first program: a ping pong game

Code: Select all

import pygame
import time

pad_x=10
pad_width=20
pad_height=100

ball_x=320
ball_y=240
ball_direction_x=1
ball_direction_y=0
ball_radius=20

by_py=0

screen=pygame.display.set_mode([640, 480])
pygame.mouse.set_visible(False)
def update_screen(mouse_y):
    screen.fill([255, 255, 255])
    paddle_y=mouse_y-50
    pygame.draw.rect(screen, [255, 0, 0], [pad_x, paddle_y, pad_width, pad_height], 0)
    pygame.draw.circle(screen, [0, 0, 255], (ball_x,ball_y), ball_radius)
    pygame.display.flip()

t=time.time()
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    if time.time()>t+.005:
        t = time.time()
        pad_x, pad_y = pygame.mouse.get_pos()
        ball_x+=ball_direction_x
        ball_y+=ball_direction_y
        if ball_x>640-ball_radius:ball_direction_x=-1
        if ball_x<ball_radius:ball_direction_x=1
        if ball_y>480-ball_radius or ball_y<ball_radius:ball_direction_y*=-1
        update_screen(pad_y)
        by_py = ball_y-pad_y
        if by_py> -50 and by_py<50 and ball_direction_x<0:
            if ball_x-ball_radius < pad_x+pad_width and ball_x > pad_x:
                ball_direction_x=1
                ball_direction_y=int(by_py/25)

pygame.quit()

Post Reply