I'm stuck with this rect.collision()
thing in pygame
. I'm trying to create a simple pong game but it's not working fine. There are still a lot errors but half of the game is done, ball is bouncing and paddles are moving accordingly. But collision is a problem. Can someone fix it.
You need to keep in mind that i'm not a professional coder not even a computer science student. I'm a physics student so please be nice with coding jargon. But I have a good knowledge of python though. Here is my code, just copy it, run it and soon you will find errors. And one more thing, i don't want to code in object oriented way, making classes or things like this but just want to make this code work.
import pygame
import math
from pygame.locals import*
pygame.init()
width,height=680,450
screen=pygame.display.set_mode((width,height))
pygame.display.set_caption("PONG GAME")
xoffset,yoffset=30,50
vel=7
radius=12
cir_x,cir_y=width/2,height/2
xvel=yvel=5
w=20
p1_x,p1_y=xoffset,height//2-yoffset
p2_x,p2_y=width-w-xoffset,height//2-yoffset
h=2*(yoffset)
leftPaddle=pygame.Rect(p1_x,p1_y,w,h)
rightPaddle=pygame.Rect(p2_x,p2_y,w,h)
clock=pygame.time.Clock()
count=0
run=True
while run:
for i in pygame.event.get():
if i.type==pygame.QUIT:
run=False
screen.fill(1)
pygame.draw.rect(screen,(225,225,255),(p1_x,p1_y,w,h))
pygame.draw.rect(screen,(225,225,255),(p2_x,p2_y,w,h))
pygame.draw.circle(screen,(255,255,255),(cir_x,cir_y),radius)
keys=pygame.key.get_pressed()
if keys[K_UP] and p2_y > vel:
p2_y -= vel
if keys[K_DOWN] and p2_y < height - h - vel:
p2_y += vel
if keys[K_w] and p1_y > vel:
p1_y -= vel
if keys[K_s] and p1_y < height - h - vel:
p1_y += vel
cir_x+=xvel
cir_y+=yvel
if (cir_x+radius>width or cir_x<radius):
xvel*=-1
if (cir_y+radius>height or cir_y<radius):
yvel*=-1
if (leftPaddle.collidepoint(cir_x,cir_y)):
xvel*=-1
if (rightPaddle.collidepoint(cir_x,cir_y)):
xvel*=-1
clock.tick(50)
pygame.display.update()
pygame.quit()