Free Friday 5-8-26

Today in class, I continued my space war game. I added a enemy, game border, and collisions.

This is the code for the enemy

class Enemy(Sprite):
    def __init__(self, spriteshape, color, startx, starty):
        Sprite.__init__(self, spriteshape, color, startx, starty)
        self.speed = 6 
        self.setheading(random.randint(0,360))       

enemy = Enemy("circle", "red", -100, 0) 

This is the code that keeps track of things that are important in the game and the game border.

class Game():
    def __init__(self):
        self.level = 1
        self.score = 0
        self.state = "playing"
        self.pen = turtle.Turtle()
        self.lives = 3 

    def draw_border(self):
        #Draw border
        self.pen.speed(0)
        self.pen.color("white")
        self.pen.pensize(3)
        self.pen.penup()
        self.pen.goto(-300, 300)
        self.pen.pendown()
        for side in range(4):
            self.pen.fd(600)
            self.pen.rt(90)
        self.pen.penup()
        self.pen.ht()

This is the code that keeps the enemy and player from going off screen

if self.xcor() > 290:
            self.setx(290)
            self.rt(60)

        if self.xcor() <-290:
            self.setx(-290)
            self.rt(60)

        if self.ycor() > 290:
            self.sety(290)
            self.rt(60)

        if self.ycor() <-290:
            self.sety(-290)
            self.rt(60)

This is the code for collisions.

 def is_collision(self, other): 
        if (self.xcor() >= (other.xcor() - 20)) and \
        (self.xcor() <= (other.xcor() + 20)) and \
        (self.xcor() >= (other.xcor() - 20)) and \
        (self.xcor() <= (other.xcor() + 20)): 
            return True
        else:
            return False    

This is the code that checks for collisions

if player.is_collision(enemy):
        x = random.randint(-250, 250)
        y = random.randint(-250, 250)
        enemy.goto(x, y)

CATEGORIES:

Tags:

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *