I am trying to get collision between my Player()
and my Coin()
. I have looking through SO questions and internet forums and I can't seem to find an answer that doesn't use a Sprite
.
I drew two rectangles (Player and Coin) and I just want to know how to see if they collide. Here is my code:
import pygame, sys, random
pygame.init()
display_width = 640
display_height = 480
display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Tutorial")
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
yellow = (255,255,0)
clock = pygame.time.Clock()
running = True
class Player:
def __init__(self,x,y,hspd,vspd,color,screen):
self.x = x
self.y = y
self.hspd = hspd
self.vspd = vspd
self.color = color
self.screen = screen
def draw(self):
pygame.draw.rect(self.screen,self.color,(self.x,self.y,32,32))
def move(self):
self.x += self.hspd
self.y += self.vspd
def collisionDetect(obj1,obj2):
pygame.sprite.collide_rect(obj1,obj2)
enemies = []
class Enemy:
def __init__(self,x,y,hspd,vspd,color,screen):
self.x = x
self.y = y
self.hspd = hspd
self.vspd = vspd
self.color = color
self.screen = screen
def draw(self):
pygame.draw.rect(display,red,(self.x,self.y,32,32))
def move(self):
self.x += self.hspd
self.y += self.vspd
def checkBounce(self):
if self.x > 640-32 or self.x < 0:
self.hspd = self.hspd * -1
if self.y > 480-32 or self.y < 0:
self.vspd = self.vspd * -1
class Coin:
def __init__(self,x,y,color,screen):
self.x = random.randint(0,640-32)
self.y = random.randint(0,480-32)
self.color = color
self.screen = screen
def draw(self):
pygame.draw.rect(self.screen,yellow,(self.x,self.y,32,32))
def move(self):
if collisionDetect(self,player):
self.x = random.randint(0,640-32)
self.y = random.randint(0,480-32)
coin = Coin(255,255,yellow,display)
player = Player(0,0,0,0,black,display)
def current_speed():
currently_pressed = pygame.key.get_pressed()
hdir = currently_pressed[pygame.K_RIGHT] - currently_pressed[pygame.K_LEFT]
vdir = currently_pressed[pygame.K_DOWN] - currently_pressed[pygame.K_UP]
return hdir * 4, vdir * 4
def updateEnemies():
for enemy in enemies:
enemy.move()
enemy.draw()
enemy.checkBounce()
CREATEENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(CREATEENEMY, 1000)
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == CREATEENEMY:
enemy = Enemy(0,0,random.randint(1,4),random.randint(1,4),red,display)
enemies.append(enemy)
player.hspd, player.vspd = current_speed()
display.fill(white)
player.move()
player.draw()
coin.draw()
updateEnemies()
pygame.display.flip()
print len(enemies)
pygame.quit()
sys.exit()
Thanks in advance!