1

so I try to program a 2d game platform like space invaders, but the problem is in the collision, when I try to define the collision, which I use in her characteristics, the characteristics of the classes (enemy coordinates and the bullet coordinates), the code won't start. And this is the result : `

    def isc (eneemy.x, eneemy.y, Bulllet.x, Bulllet.y ):
               ^
SyntaxError: invalid syntax

this is the code if you need it :

    ############# LIBRARIES ####################
import pygame, sys, random
import math
from pygame.constants import SYSTEM_CURSOR_WAITARROW 
from pygame import mixer


pygame.init()

############ WINDOW OPTIONS ################
Swidth = 800 
Sheight =600
screen = pygame.display.set_mode((Swidth, Sheight))
pygame.display.set_caption("Space Invader By Mal4D")
icon = pygame.image.load('places/favicon.png')
pygame.display.set_icon(icon)


############# COLORS #######################
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED   = (255, 0, 0)
YELLOW = (255 , 255 , 0)

###########  VARIANTS ######################
isJumping= False
LevelJump = 0.25
rocket = pygame.image.load("rocket/rocket.png")
space = pygame.image.load("places/bg.png")
bullet = pygame.image.load("rocket/bullet.png")
Sound =  pygame.mixer.music.load("Sounds/laser.mp3")
Bgsound= pygame.mixer.music.load("Sounds/bg.mp3")
enemy = pygame.image.load("Enemy/enemy.png")
ax=random.randint(0,700)
by=random.randint(20,120)
Bgsound1 = mixer.Sound("Sounds/bg.mp3")
BullletSound = mixer.Sound("Sounds/laser.mp3")


############## Class Players ##########################
class Player():
    def __init__(self,x,y,width,height):
        self.x=x
        self.y=y
        self.width=width
        self.height=height
        self.step=10
        self.speed=10
        self.isJumping= False
        

    def drawplayer (self,screen):
        screen.blit(rocket, (rockeet.x, rockeet.y))

    def drawscreen (self,screen):
        screen.blit(space, (0,0))
    

rockeet = Player(350,500,50,50)


########### Bullet #####################
class Bullet():
    def __init__(self, x, y , y_change, x_change, state):
        self.x=x
        self.y= y
        self.y_change=y_change
        self.x_change= x_change
        self.state= state


    def fire(x,y):
        Bulllet.state = "fire"
        screen.blit(bullet,(x+16, y+10))


Bulllet=Bullet(350,500,20,0,"ready")

**def isCollision (ax1, by1, cx, dy):
    distance = math.sqrt(math.pow(ax1 - cx, 2) + (math.pow(by1- dy, 2)))

    if distance <27:
        return True
    else:
        return False**

    
################## Enemy ########################
class Enemy():
    def __init__(self, x ,y, stepx,stepy):
        self.x = x
        self.y=y
        self.stepx=stepx
        self.stepy=stepy


    def drawenemy(screen):
        screen.blit(enemy,(ax,by))


eneemy = Enemy(random.randint(0,700),random.randint(20,120),3,35)


################# Clussion#########################
score = 0


def isc (eneemy.x, eneemy.y, Bulllet.x, Bulllet.y ):
    distance = math.sqrt(math.pow(eneemy.x - Bulllet.x, 2) + (math.pow(eneemy.y- Bulllet.y, 2)))

    if distance <27:
        return True
    else:
        return False


################### Game Loop #####################################
#Bgsound1.play(180)




while 1:
    pygame.time.delay(10)
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    keys=pygame.key.get_pressed()
    rockeet.drawscreen(screen)
    Enemy.drawenemy(screen)



    if keys[pygame.K_SPACE]:
        if Bulllet.state == "ready":
            BullletSound.play()

            Bulllet.x=rockeet.x
            Bulllet.y=rockeet.y
            Bullet.fire(Bulllet.x, Bulllet.y)



    if keys[pygame.K_LEFT] and rockeet.x - rockeet.step >= 0:
        rockeet.x =rockeet.x-rockeet.step
    
    if keys[pygame.K_RIGHT] and rockeet.x + rockeet.width +rockeet.step <= Swidth :
        rockeet.x =rockeet.x+rockeet.step

    if Bulllet.y <= 0:
        Bulllet.y= 500
        Bulllet.state = "ready"


    if Bulllet.state == "fire":
        Bullet.fire(Bulllet.x, Bulllet.y)
        Bulllet.y -= Bulllet.y_change



########### Enemy Mouvement #########################################
    collision = isCollision( eneemy.x, eneemy.y, Bulllet.x, Bulllet.y)

    ax+= eneemy.stepx
    if ax<= 0:
        eneemy.stepx=3
        by+= eneemy.stepy

    elif ax >= 750:
        eneemy.stepx=-3
        by+= eneemy.stepy

    if collision:
        Bulllet.y= 500
        Bulllet.state="ready"
        eneemy.x= random.randint(0,700)
        eneemy.y=random.randint(20,)

################## Collision ######################








################## OUTRO #######################################
    rockeet.drawplayer(screen)

    pygame.display.update()

the result:

def isCollision (eneemy.x, eneemy.y, Bulllet.x, Bulllet.y ):
               ^
SyntaxError: invalid syntax

2 Answers2

0

The formal parameters of a function cannot be structure elements like eneemy.x. Either Change the names of the parameters:

def isc (enemy_x, enemy_y, bullet_x, bullet_y):
    distance = math.sqrt(math.pow(enemy_x - bullet_x, 2) + (math.pow(enemy_y- bullet_y, 2)))

    if distance <27:
        return True
    else:
        return False

Or pass the objects to the function:

def isc (enemy, bullet):
    distance = math.sqrt(math.pow(enemy.x - bullet.x, 2) + (math.pow(enemy.y- bullet.y, 2)))

    if distance <27:
        return True
    else:
        return False

collision = isCollision( eneemy.x, eneemy.y, Bulllet.x, Bulllet.y)

collision = isCollision(eneemy, Bulllet)

Note, that you can use math.hypot instead of math.sqrt and math.pow:

distance = math.sqrt(math.pow(enemy_x - bullet_x, 2) + (math.pow(enemy_y- bullet_y, 2)))

distance = math.hypot(enemy_x - bullet_x, enemy_y - bullet_y)
Rabbid76
  • 177,135
  • 25
  • 101
  • 146
0

Adding to @Rabbid76's answer for the sake of completion…


You don't want to test rectangle collisions (that is the collision between the enemy and the bullet) by simply measuring the distance between their top left corners. Consider the bellow image:

enter image description here

You can see that the rectangles overlap, even though there seem to be no collisions within the red circle, which is the distance area that you are scanning when checking for collisions.

Instead, use the Pygame's built-in Rect objects and their collision detection capabilities (for example, pygame.Rect.colliderect).


I've also noticed that you've used similar names for assets and it's corresponding game classes (enemy and eneemy, bullet and Bulllet, ...). This is a terrible idea as a typo can quickly occur and you won't even know what happened to you. It's worth investing some time into proper variable naming!


You've been using a lot of class methods where an object method (a method that has the keyword self in its argument list) would be more appropriate. You may want to spend some time refreshing your object-oriented programming knowledge.


Fully working solution:

############# LIBRARIES ####################
import pygame, sys, random
import math
from pygame.constants import SYSTEM_CURSOR_WAITARROW 
from pygame import mixer


pygame.init()

############ WINDOW OPTIONS ################
Swidth = 800 
Sheight = 600
screen = pygame.display.set_mode((Swidth, Sheight))
pygame.display.set_caption("Space Invader By Mal4D")
icon = pygame.image.load('places/favicon.png')
pygame.display.set_icon(icon)


############# COLORS #######################
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

###########  VARIANTS ######################
isJumping = False
LevelJump = 0.25
rocket = pygame.image.load("rocket/rocket.png")
space = pygame.image.load("places/bg.png")
bullet = pygame.image.load("rocket/bullet.png")
Sound = pygame.mixer.music.load("Sounds/laser.mp3")
Bgsound = mixer.Sound("Sounds/bg.mp3")
enemy = pygame.image.load("Enemy/enemy.png")
bulletObjectSound = mixer.Sound("Sounds/laser.mp3")


############## Class Players ##########################
class Player():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.step = 10
        self.speed = 10
        self.isJumping = False
        

    def drawplayer (self, screen):
        screen.blit(rocket, (rocketObject.x, rocketObject.y))

    def drawscreen (self, screen):
        screen.blit(space, (0, 0))
    

rocketObject = Player(350, 500, 50, 50)


########### Bullet #####################
class Bullet():
    def __init__(self, x, y, y_change, x_change, state):
        self.x = x
        self.y = y
        self.y_change = y_change
        self.x_change = x_change
        self.state = state


    def fire(self):
        self.state = "fire"
        screen.blit(bullet, (self.x + 16, self.y + 10))


bulletObject = Bullet(350, 500, 20, 0, "ready")

def isCollision(enemyX, enemyY, bulletX, bulletY):
    r1 = pygame.Rect(enemyX, enemyY, enemy.get_width(), enemy.get_height())
    r2 = pygame.Rect(bulletX, bulletY, bullet.get_width(), bullet.get_height())

    return r1.colliderect(r2)

    
################## Enemy ########################
class Enemy():
    def __init__(self, x, y, stepx, stepy):
        self.x = x
        self.y = y
        self.stepx = stepx
        self.stepy = stepy

    def drawenemy(self, screen):
        screen.blit(enemy, (self.x, self.y))


enemyObject = Enemy(random.randint(0, 700), 20, 3, 35)

################# Clussion#########################
score = 0

################### Game Loop #####################################
Bgsound.play(180)




while 1:
    pygame.time.delay(10)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:sys.exit()

    keys = pygame.key.get_pressed()
    rocketObject.drawscreen(screen)
    enemyObject.drawenemy(screen)



    if keys[pygame.K_SPACE]:
        if bulletObject.state == "ready":
            bulletObjectSound.play()

            bulletObject.x = rocketObject.x
            bulletObject.y = rocketObject.y
            bulletObject.fire()



    if keys[pygame.K_LEFT] and rocketObject.x - rocketObject.step >= 0:
        rocketObject.x = rocketObject.x - rocketObject.step
    
    if keys[pygame.K_RIGHT] and rocketObject.x + rocketObject.width + rocketObject.step <= Swidth:
        rocketObject.x = rocketObject.x + rocketObject.step

    if bulletObject.y <= 0:
        bulletObject.y = 500
        bulletObject.state = "ready"


    if bulletObject.state == "fire":
        bulletObject.fire()
        bulletObject.y -= bulletObject.y_change



########### Enemy Movement #########################################
    collision = isCollision(enemyObject.x, enemyObject.y, bulletObject.x, bulletObject.y)

    enemyObject.x += enemyObject.stepx
    if enemyObject.x <= 0:
        enemyObject.stepx = 3
        enemyObject.y += enemyObject.stepy

    elif enemyObject.x >= 750:
        enemyObject.stepx = -3
        enemyObject.y += enemyObject.stepy

    if collision:
        bulletObject.y = 500
        bulletObject.state = "ready"
        enemyObject.x = random.randint(0, 700)
        enemyObject.y = 20

################## Collision ######################








################## OUTRO #######################################
    rocketObject.drawplayer(screen)

    pygame.display.update()
Janez Kuhar
  • 3,096
  • 2
  • 22
  • 39