0
\$\begingroup\$

I cannot figure out how to apply collision to a turtle. I am in need of help for collision with pen lines and turtles. I want the two to hit and restart the game but I can't get collision on either.

import turtle
import pygame



wn = turtle.Screen()
wn.bgcolor("black")

#Draw border
mypen = turtle.Turtle()
mypen.penup()
mypen.pencolor('white')
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
for side in range (4):
    mypen.forward(600)
    mypen.left(90)
mypen.hideturtle()

#Create player 1
player = turtle.Turtle()
player.setposition(240,240)
player.setheading(180)
player.color("red")
player.shape("classic")

player.speed(0)

#Create player 2
player2 = turtle.Turtle()
player2.setposition(-240,-240)
player2.color("aqua")
player2.shape("triangle")

player2.speed(0)

#Set speed variable
speed = 3

#Define functions
def turnleft():
    player.left(30)

def turnright():
    player.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for p1ayer 1

turtle.listen()
turtle.onkey(turnleft,"Left")
turtle.onkey(turnright,"Right")

#Define player 2 functions

def turnleft():
    player2.left(30)

def turnright():
    player2.right(30)

def increasespeed():
    global speed
    speed += 3

#Set keyboard bindings for player 2
turtle.listen()
turtle.onkey(turnleft,"a")
turtle.onkey(turnright,"d")

#turtle.onkey(increasespeed,"Up")

while True:
    player.forward(speed)
    player2.forward(speed)

    #Bouandary
    if player.xcor() > 300 or player.xcor() < -300:
        player.right(100)
    #Boundary
    if player.ycor() > 300 or player.ycor() < -300:
        player.right(100)
    #Bouandary2
    if player2.xcor() > 300 or player2.xcor() < -300:
        player2.right(100)
    #Boundary2
    if player2.ycor() > 300 or player2.ycor() < -300:
        player2.right(100)
\$\endgroup\$
0
\$\begingroup\$

You can put the coordinates of the two objects in a variable like:

PlayerPosX = 240
PlayerPosY = 240

Player2PosX = -240
Player2PosY = -240

Then do an if in a while True: that saying if the two PosX and the two PosY matches, the game restarts. Hope you serve.

\$\endgroup\$
  • \$\begingroup\$ In this case they are not objects. The turtles aren't stationary. To apply coordinates it mustn't move, but in the case of my code they move. Your answer "did not serve". Thank you for the attempt though. \$\endgroup\$ – SuperPolyCarp CARP May 3 '19 at 13:29
  • \$\begingroup\$ For solving you can try to add: player.setposition(PlayerPosX, PlayerPosY) and player2.setposition(Player2PosX, Player2PosY) in a while True: \$\endgroup\$ – ArnauBG May 3 '19 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.