Collision detection in Python(pygame) - pygame

I have been wondering how collision detection works, I have had many attempts, but can't get it to work. I am new to pygame, so if anyone is kind enough to read this, please can you add the correct lines to my code as well as explaining it. If anyone was wondering what this code did, it has 2 racecars thatare trying to hit a football and move it in the direction the car is hitting it at(I was thinking a possible way to complete this was to check the angle the car is rotated at, and move the ball by that amount, - 180 degrees to move it forward)
Thank you very much
import pygame
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((1150, 800))
clock = pygame.time.Clock()
BLUECAR_ORIGINAL = pygame.Surface((100, 30), pygame.SRCALPHA)
pygame.draw.polygon(
BLUECAR_ORIGINAL, (0, 0, 255), [(0, 0), (50, 10), (50, 20), (0, 30)])
bluecar = BLUECAR_ORIGINAL
REDCAR_ORIGINAL = pygame.Surface((50, 30), pygame.SRCALPHA)
pygame.draw.polygon(
REDCAR_ORIGINAL, (200, 0, 0), [(0, 0), (50, 10), (50, 20), (0, 30)])
redcar = REDCAR_ORIGINAL
ball = pygame.draw.circle(screen, [255,255,255],[60,60],5)
pos = Vector2(70, 70)
vel = Vector2(7, 0)
poss = Vector2(70,70)
vell = Vector2(7,0)
redrect = redcar.get_rect(center=pos)
redangle = 0
bluerect = bluecar.get_rect(center=pos)
blueangle = 0
run = True
while run:
ball = pygame.draw.circle(screen, [0,0,0],[575,400],30)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
redangle += 5
vel.rotate_ip(-5)
redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle)
redrect = redcar.get_rect(center=pos)
elif keys[pygame.K_RIGHT]:
redangle -= 5
vel.rotate_ip(5)
redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle)
redrect = redcar.get_rect(center=pos)
if keys[pygame.K_a]:
blueangle += 5
vell.rotate_ip(-5)
bluecar = pygame.transform.rotate(BLUECAR_ORIGINAL, blueangle)
bluerect = bluecar.get_rect(center=pos)
elif keys[pygame.K_d]:
blueangle -= 5
vell.rotate_ip(5)
bluecar = pygame.transform.rotate(BLUECAR_ORIGINAL, blueangle)
bluerect = bluecar.get_rect(center=poss)
hits = pygame.sprites.groupcollide(bluecar, ball, False, False)
hits = pygame.sprites.spritecollide(bluecar, ball, False)
pos += vel
redrect.center = pos
poss += vell
bluerect.center = poss
bgImg = pygame.image.load("Football_pitch.png")
screen.blit(bgImg, (0,0))
screen.blit(redcar, redrect)
screen.blit(bluecar, bluerect)
pygame.display.flip()
clock.tick(60)
pygame.quit()

There are multiple ways:
you could save the coordinates of each sprite as variables and then compare the coordinates of both sprites to each other than do whatever you need to when they are close enough, for example:
if object1_X <= object2_X+5 and object1_X>= object2_X-5 and object1_Y<= object2_Y+5 and object1_Y>=object2_X-5:
#do something
#all that above basically is just saying if the objects above are within a 10-pixel radius of each other do something
pass
or you could use the distance formula:
distance=((object2_X-object1_X)**2+(object2_Y-object1_Y)**2)**0.5
if distance <= 10:
#do something
pass
which utilises the Pythagorean theorem to find the distance between two objects
or you could use pygame's existing function:
object1=pygame.draw.rect(screen,color,[x,y1,50,30],0)
object2=pygame.draw.rect(screen,colorb,[x2,y2,7,7],0)
if object1.colliderect(object2):
#do something
pass
if you were wondering how it works, I am not 100% sure but it likely uses one of the two rudimentary methods internally to calculate this

Related

How can i move the Instances of the game on shifted y axis? [duplicate]

I'm a beginner programmer who is starting with python and I'm starting out by making a game in pygame.
The game basically spawns circles at random positions and when clicked, it gives you points.
Recently I've hit a roadblock when I want to spawn multiple instances of the same object (in this case circles) at the same time.
I've tried stuff like sleep() and some other code related to counters, but it always results in the next circle spawned overriding the previous one (i.e the program spawns circle 1, but when circle 2 comes in, circle 1 disappears).
Does anyone know a solution to this? I would really appreciate your help!
import pygame
import random
import time
pygame.init()
window = pygame.display.set_mode((800,600))
class circle():
def __init__(self, color, x, y, radius, width,):
self.color = color
self.x = x
self.y = y
self.radius = radius
self.width = width
def draw(self, win, outline=None):
pygame.draw.circle(win, self.color, (self.x, self.y, self.radius, self.width), 0)
run=True
while run:
window.fill((0, 0, 0))
pygame.draw.circle(window, (255, 255, 255), (random.randint(0, 800),random.randint(0, 600)), 20, 20)
time.sleep(1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
pygame.quit()
quit()
It does not work that way. time.sleep, pygame.time.wait() or pygame.time.delay is not the right way to control time and gameplay within an application loop. The game does not respond while you wait. The application loop runs continuously. You have to measure the time in the loop and spawn the objects according to the elapsed time.
pygame.Surface.fill clears the entire screen. Add the newly created objects to a list. Redraw all of the objects and the entire scene in each frame.
See also Time, timer event and clock
You have 2 options. Use pygame.time.get_ticks() to measure the time. Define a time interval after which a new object should appear. Create an object when the point in time is reached and calculate the point in time for the next object:
object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
next_object_time = 0
while run:
# [...]
current_time = pygame.time.get_ticks()
if current_time > next_object_time:
next_object_time += time_interval
object_list.append(Object())
Minimal example:
repl.it/#Rabbid76/PyGame-TimerSpawnObjects
import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))
class Object:
def __init__(self):
self.radius = 50
self.x = random.randrange(self.radius, window.get_width()-self.radius)
self.y = random.randrange(self.radius, window.get_height()-self.radius)
self.color = pygame.Color(0)
self.color.hsla = (random.randrange(0, 360), 100, 50, 100)
object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
next_object_time = 0
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
current_time = pygame.time.get_ticks()
if current_time > next_object_time:
next_object_time += time_interval
object_list.append(Object())
window.fill(0)
for object in object_list[:]:
pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
object.radius -= 0.2
if object.radius < 1:
object_list.remove(object)
pygame.display.flip()
pygame.quit()
exit()
The other option is to use the pygame.event module. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds. e.g.:
object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)
Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.
Receive the event in the event loop:
while run:
for event in pygame.event.get():
if event.type == timer_event:
object_list.append(Object())
The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.
Minimal example:
repl.it/#Rabbid76/PyGame-TimerEventSpawn
import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))
class Object:
def __init__(self):
self.radius = 50
self.x = random.randrange(self.radius, window.get_width()-self.radius)
self.y = random.randrange(self.radius, window.get_height()-self.radius)
self.color = pygame.Color(0)
self.color.hsla = (random.randrange(0, 360), 100, 50, 100)
object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
object_list.append(Object())
window.fill(0)
for object in object_list[:]:
pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
object.radius -= 0.2
if object.radius < 1:
object_list.remove(object)
pygame.display.flip()
pygame.quit()
exit()

How come when I use if .collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0] for a button, it only stays there while I hold it? [duplicate]

I was wondering how to write code that would detect the mouse clicking on a sprite. For example:
if #Function that checks for mouse clicked on Sprite:
print ("You have opened a chest!")
I assume your game has a main loop, and all your sprites are in a list called sprites.
In your main loop, get all events, and check for the MOUSEBUTTONDOWN or MOUSEBUTTONUP event.
while ... # your main loop
# get all events
ev = pygame.event.get()
# proceed events
for event in ev:
# handle MOUSEBUTTONUP
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
# get a list of all sprites that are under the mouse cursor
clicked_sprites = [s for s in sprites if s.rect.collidepoint(pos)]
# do something with the clicked sprites...
So basically you have to check for a click on a sprite yourself every iteration of the mainloop. You'll want to use mouse.get_pos() and rect.collidepoint().
Pygame does not offer event driven programming, as e.g. cocos2d does.
Another way would be to check the position of the mouse cursor and the state of the pressed buttons, but this approach has some issues.
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()):
print ("You have opened a chest!")
You'll have to introduce some kind of flag if you handled this case, since otherwise this code will print "You have opened a chest!" every iteration of the main loop.
handled = False
while ... // your loop
if pygame.mouse.get_pressed()[0] and mysprite.rect.collidepoint(pygame.mouse.get_pos()) and not handled:
print ("You have opened a chest!")
handled = pygame.mouse.get_pressed()[0]
Of course you can subclass Sprite and add a method called is_clicked like this:
class MySprite(Sprite):
...
def is_clicked(self):
return pygame.mouse.get_pressed()[0] and self.rect.collidepoint(pygame.mouse.get_pos())
So, it's better to use the first approach IMHO.
The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.
Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked.
Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/#Rabbid76/PyGame-MouseClick
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.click_image, color, (25, 25), 25)
pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.clicked = False
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.clicked = not self.clicked
self.image = self.click_image if self.clicked else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
See further Creating multiple sprites with different update()'s from the same sprite class in Pygame
The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ​​that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.
Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
if self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/#Rabbid76/PyGame-MouseHover
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.hover_image, color, (25, 25), 25)
pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.hover = False
def update(self):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
#self.hover = self.rect.collidepoint(mouse_pos)
self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)
self.image = self.hover_image if self.hover else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update()
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
The pygame documentation for mouse events is here.
You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed).
Remember to use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.
EDIT:
To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.
I was looking for the same answer to this question and after much head scratching this is the answer I came up with:
# Python 3.4.3 with Pygame
from sys import exit
import pygame
pygame.init()
WIDTH = HEIGHT = 300
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Crash!')
# Draw Once
rectangle = pygame.draw.rect(window, (255, 0, 0), (100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
# Mouse position and button clicking
pos = pygame.mouse.get_pos()
pressed1 = pygame.mouse.get_pressed()[0]
# Check if rectangle collided with pos and if the left mouse button was pressed
if rectangle.collidepoint(pos) and pressed1:
print("You have opened a chest!")
# Quit pygame
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()

How do I make autonomous movement in pygame?

I'm new to pygame and I'm trying to do the simplest thing ever here really, I just want to have a circle move across the screen with no input from the user. I only seem to find advice online on how to move an object using the keys which isn't what I want I just want it to move on its own and so that the user can watch it move.
Here's what I was trying to use to do this.
Code Start Here:
import pygame module in this program
import pygame
pygame.init()
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)
X = 400
Y = 400
display_surface = pygame.display.set_mode((X, Y ))
pygame.display.set_caption('Drawing')
display_surface.fill(white)
x,y=[300,50]
pygame.draw.circle(display_surface,green, (x, y), 20, 0)
clock = pygame.time.Clock()
def move():
global y
y=y+1
while True :
clock.tick(30)
move()
for event in pygame.event.get() :
# if event object type is QUIT
# then quitting the pygame
# and program both.
if event.type == pygame.QUIT :
pygame.quit()
quit()
pygame.display.update()
Code End Here:
You have to redraw the scene in every frame:
import pygame
pygame.init()
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)
X = 400
Y = 400
display_surface = pygame.display.set_mode((X, Y))
pygame.display.set_caption('Drawing')
clock = pygame.time.Clock()
x,y=[300,50]
def move():
global y
y=y+1
# application loop
run = True
while run:
# limit the frames per second
clock.tick(30)
# event loop
for event in pygame.event.get() :
if event.type == pygame.QUIT:
run = False
# update the position of the object
move()
# clear disaply
display_surface.fill(white)
# draw scene
pygame.draw.circle(display_surface,green, (x, y), 20, 0)
# update disaply
pygame.display.update()
pygame.quit()
quit()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()

Pygame sin,cos,tan caculating circular movement path

I have been struggling for few days know trying to figure out how to make for example a image move in circular path. I have looked other posts here but i just can't get it.
So how do i move image in circular path. My code only moves my image 45 degrees and stops then. I would need it to go full circle and continue doing it.
Current Code:
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
CENTER = (200, 200)
RADIUS = 100
x = 0
y = 0
satelliteCenter = (CENTER[0]+RADIUS, CENTER[1])
run = 1
while run == 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = 0
pygame.quit()
mouse = pygame.mouse.get_pos()
vector = x-CENTER[0], y-CENTER[1]
x +=1
distance = (vector[0]**2 + vector[1]**2)**0.5
if distance > 0:
scalar = RADIUS / distance
satelliteCenter = (
int(round( CENTER[0] + vector[0]*scalar )),
int(round( CENTER[1] + vector[1]*scalar )) )
screen.fill((255,255,255))
pygame.draw.circle(screen, (71,153,192), CENTER, RADIUS)
pygame.draw.circle(screen, (243,79,79), satelliteCenter, 16)
pygame.display.update()
You can just use a pygame.math.Vector2 and rotate it each frame, scale it by the radius and add it to the CENTER position to get the current center of the small circle.
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
CENTER = (200, 200)
RADIUS = 100
# A unit vector pointing to the right.
direction = pygame.math.Vector2(1, 0)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
direction.rotate_ip(4) # By 4 degrees.
# Normalize it, so that the length doesn't change because
# of floating point inaccuracies.
direction.normalize_ip()
# Scale direction vector, add it to CENTER and convert to ints.
ball_pos = [int(i) for i in CENTER+direction*RADIUS]
screen.fill((255,255,255))
pygame.draw.circle(screen, (71,153,192), CENTER, RADIUS)
pygame.draw.circle(screen, (243,79,79), ball_pos, 16)
pygame.display.update()
clock.tick(30)
Edit: If you want the red ball to follow the mouse, then your example actually works if you set x and y to the mouse pos x, y = pygame.mouse.get_pos().
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 400))
CENTER = (200, 200)
RADIUS = 100
x = 0
y = 0
satelliteCenter = (CENTER[0]+RADIUS, CENTER[1])
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
x, y = pygame.mouse.get_pos()
vector = x-CENTER[0], y-CENTER[1]
distance = (vector[0]**2 + vector[1]**2)**0.5
if distance > 0:
scalar = RADIUS / distance
satelliteCenter = (
int(round( CENTER[0] + vector[0]*scalar )),
int(round( CENTER[1] + vector[1]*scalar ))
)
screen.fill((255,255,255))
pygame.draw.circle(screen, (71,153,192), CENTER, RADIUS)
pygame.draw.circle(screen, (243,79,79), satelliteCenter, 16)
pygame.display.update()

pygame, getting a sprite to move to cursor position on click

I was trying to make a tower defense sort of game in pygame. When I click on the screen, I want it to be able to move the tower sprite to the position. Currently, when I run the program, it moves the sprite to the cursor with out clicking, then does not let me move it again.
import pygame
import time
pygame.init()
WINDOWWIDTH = 1800
WINDOWHEIGHT = 1800
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
background_colour = (188,69,80)
GAMETITLE = "Tower Defence"
def main():
pygame.display.set_caption(GAMETITLE)
clock = pygame.time.Clock()
spritegroup =pygame.sprite.Group()
sprite =pygame.sprite.Sprite()
tower = sprite.image = pygame.image.load("tower.png")
sprite.image = tower
sprite.rect = sprite.image.get_rect()
sprite.rect.x = 10
sprite.rect.y = 10
sprite.add(spritegroup)
while True:
screen.fill(background_colour)
pygame.draw.rect(screen, (255,255,255), ((0, 100), (1100, 90)))
pygame.draw.rect(screen, (255, 255,255), ((1010, 100), (100, 600)))
pygame.draw.rect(screen, (255,255,255), ((1010, 700), (2400, 90)))
spritegroup.draw(screen)
pygame.display.update()
clock.tick(30)
if pygame.mouse.get_pressed():
cursorPos = pygame.mouse.get_pos()
sprite.rect.x = cursorPos[0]
sprite.rect.y = cursorPos[1]
main()
what is happening is that pygame.mouse.get_pressed() returns a tuple. if statements return true if they are not null. this means that regardless if it is pressed it will return True. then the pygame event queue will fill with mouse events and never get processed. your event loop should look something like:
for event in pygame.event.get():
if event.type == pygame.event.QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
#stuff to do on click