import turtle
# Make the play screen
wn = turtle.Screen()
wn.bgcolor("red")
# Make the play field
mypen = turtle.Turtle()
mypen.penup()
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(5)
for side in range(4):
mypen.forward(600)
mypen.left(90)
mypen.hideturtle()
# Make the object
player = turtle.Turtle()
player.color("black")
player.shape("circle")
player.penup()
# define directions( East, West , South , Nord )
def west():
player.setheading(180)
def east():
player.setheading(0)
def north():
player.setheading(90)
def south():
player.setheading(270)
# define forward
def forward():
player.forward(20)
# Wait for input
turtle.listen()
turtle.onkey(west, "a")
turtle.onkey(east, "d")
turtle.onkey(forward,"w")
turtle.onkey(north,"q")
turtle.onkey(south,"s")
if player.xcor() > 300 or player.xcor() < -300:
print("Game over")
if player.ycor() > 300 or player.ycor() < -300:
print("Game over")
So everything is working fine, till the If statements. When i go trough the play field it should give me a print " Game over ". The coordinates are right but it doesnt check the coordinates! What am i doing wrong ?
The problem is that your logic to test if the player has gone out of bounds is at the top level of your code -- it doesn't belong there. You should turn control over to the turtle listener, via mainloop() and handle the bounds detection in one of your callback methods, namely forward().
A demonstration of the above in a rework of your code:
import turtle
QUADRANT = 250
# Make the play screen
screen = turtle.Screen()
screen.bgcolor("red")
# Make the play field
play_pen = turtle.Turtle()
play_pen.pensize(5)
play_pen.speed("fastest")
play_pen.penup()
play_pen.setposition(-QUADRANT, -QUADRANT)
play_pen.pendown()
for _ in range(4):
play_pen.forward(QUADRANT * 2)
play_pen.left(90)
play_pen.hideturtle()
# Make the object
player = turtle.Turtle()
player.color("black")
player.shape("circle")
player.penup()
# define forward
def forward():
player.forward(20)
if player.xcor() > QUADRANT or player.xcor() < -QUADRANT or player.ycor() > QUADRANT or player.ycor() < -QUADRANT:
player.hideturtle()
player.setposition((0, 0))
player.write("Game over", False, align="center", font=("Arial", 24, "normal"))
# define directions(East, West, North, South)
turtle.onkey(lambda: player.setheading(180), "a") # west
turtle.onkey(lambda: player.setheading(0), "d") # east
turtle.onkey(lambda: player.setheading(90), "q") # north
turtle.onkey(lambda: player.setheading(270), "s") # south
turtle.onkey(forward, "w")
# Wait for input
turtle.listen()
turtle.mainloop()
Related
I am making a simple jump game in python, and so far have a player and a spike. The spike moves infinitely to the left of the screen and then immediately goes back to the right side. The player jumps when you press space. My issue is that I cannot have the player jumping and the sprite moving at the same time.
#Imports and other setup
import turtle
import time
turtle.speed(5)
air = 0
#Window customization
wn = turtle.Screen()
wn.title('Jump Game')
wn.bgcolor('black')
wn.setup(width=600, height=600)
#Player creation
player = turtle.Turtle()
player.penup()
player.ht()
player.shape('square')
player.color('blue')
player.goto(-200, -200)
player.st()
player.down()
#Floor creation
floorCors = ((210, -300), (210, 300), (300, 300), (300, -300))
wn.register_shape('rectangle', floorCors)
floor = turtle.Turtle()
floor.shape('rectangle')
floor.color('white')
#Obstacle creation
obstacle = turtle.Turtle()
obstacle.penup()
obstacle.ht()
obstacle.shape('triangle')
obstacle.color('red')
obstacle.goto(200, -202)
obstacle.tilt(90)
obstacle.st()
obstacle.down()
turtle.update()
#Player jump
def jump():
global air
if air == 0:
air = 1
player.penup()
player.speed(1)
y = player.ycor()
player.sety(y+100)
player.sety(y-0)
air = 0
wn.listen()
wn.onkeypress(jump, 'space')
#Obstacle movement
while True:
obstacle.penup()
obstacle.speed(3)
x = obstacle.xcor()
if x > -300:
obstacle.goto(x-10, -202)
else:
obstacle.ht()
obstacle.speed(0)
obstacle.goto(300, -202)
obstacle.speed(3)
obstacle.st()
I thought about combining the two movement chunks but I have no idea how to approach that.
I have got a problem with how to end my turtle python game. The code seems to function if I place the turtles at the starting/ending point from the beginning of the code, but it does not register when the turtle reaches the endpoint in gameplay. From what I know I think my maths for the end function is right. I am new and appreciate the help. I am currently offline though.
CODE:
import time
import turtle
from turtle import *
wn = turtle.Screen()
name=textinput("Question", "what is your name")
#display
pencolor("white")
penup()
goto(0,170)
write("hello " +name,align='center',font=('Comic Sans', 20))
#wn = turtle.screen() if the code doesn't work
#diffrent turtles here
t1 = turtle.Turtle()
t2 = turtle.Turtle()
t3 = turtle.Turtle()
#starting psoition
turtle.penup()
t1.penup()
turtle.goto(-1, -230)
t1.goto(-1, -170)
#starting line postion
def f():
fd(10)
def b():
bk(10)
def l():
left(10)
def r():
right(10)
#testing
def fo():
t1.fd(10)
def ba():
t1.bk(10)
def le():
t1.left(10)
def ri():
t1.right(10)
#turtle coordinates
first=turtle.ycor()
second=turtle.xcor()
third=t1.ycor()
fourth=t1.xcor()
#when to end the game
if (turtle.ycor()>= (-160)) and (turtle.ycor()<= (-240)):
if (turtle.xcor()>= (0)) and (turtle.xcor()<= (11)):
print("Finally working")
#replaced with write who the winner is later
if (t1.ycor()>= (-160)) and (t1.ycor()<= (-240)):
if (t1.xcor()>= (0)) and (t1.xcor()<= (11)):
print("Finally")
# onkey creates the key board = turtle.onkey("function, key") You have to keep pressing keys for it to move
turtle.onkey(f, "w")
turtle.onkey(b, "s")
turtle.onkey(l, "a")
turtle.onkey(r, "d")
wn.onkey(fo, "Up")
wn.onkey(ba, "Down")
wn.onkey(le, "Left")
wn.onkey(ri, "Right")
listen()
#WINDOW SETUP
window = Screen()
window.setup(800, 800)
window.title("Turtle game")
turtle.bgcolor("forestgreen")
t3.color("black")
t3.speed(0)
t3.penup()
t3.setpos(-140, 250)
t3.write("THE TURTLE RACE", font=("Comic Sans", 30, "bold"))
t3.penup()
#turtle ask name
#add images here
#turtle controls
# def creates a function. : means opperation f means move turtle foward. fd push turtle forward
# onkey creates the key board = turtle.onkey("function, key") You have to keep pressing keys for it to move
t2.speed(0)
t2.color("grey")
t2.pensize(100)
t2.penup()
t2.goto(-200, -200)
t2.left(90)
t2.pendown()
t2.forward(300)
t2.right(90)
t2.forward(500)
t2.right(90)
t2.forward(300)
t2.right(90)
t2.forward(500)
turtle.penup()
Firstly, your maths is not quite right - a coordinate can never be both <= -240 and >= -160. It should be t.ycor() >= -240 and t.ycor() <= -160, or more briefly, -240 <= t.ycor() <= -160.
Secondly, the condition as it stands is only checked once, when the code is first run. Instead, you need to get the program to check it regularly. You can do this by adding a general onkeypress event handler which is checked every time any key is pressed.
def check_status():
for player, t in enumerate([turtle, t1]):
if 0 <= t.xcor() <= 11 and -240 <= t.ycor() <= -160:
print(f"Player {player} is at the endpoint")
...
wn.onkeypress(check_status)
listen()
I'm not sure how to get rid of the black arrow, if you could help that would be great! Thanks, also if you have any other modifications to make the game better that would be awesome as well! Thanks again!
It says I need to write more detail, so I m just going to keep typing fora bit and hope that I have enough words to write. It should be good right around here.
import math
import random
score = 0
print ("\n" * 40)
print("Welcome Player, I Hope You Have What it Takes to be the Next WARLORD BOSS")
print("Enemies Killed:\n0")
#Title
t=turtle.Pen()
t.pencolor("magenta")
t.hideturtle()
t.penup()
t.setposition(-300,350)
t.write("Catch 40 turtles for a suprise ( ͡° ͜ʖ ͡°)", font=("Verdana", 18))
#Tip
text=turtle.Pen()
t.pencolor("magenta")
t.hideturtle()
turtle.clear()
t.penup()
t.setposition(-100, -350)
t.write("TOUCH THE EDGES, I DARE YOU", font=("Verdana", 18))```
#Set up screen
wn = turtle.Screen()
wn.bgcolor("dim gray")
wn.title("EXEXEXEXEEXXEXEXE HACK COMMENCING␀␀␀␀␀")
#Draw border
mypen = turtle.Turtle()
mypen.penup()
mypen.speed(10)
mypen.hideturtle()
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
for side in range(4):
mypen.color("crimson")
mypen.forward(300)
mypen.color("gold")
mypen.forward(300)
mypen.left(90)
mypen.hideturtle()
#Create player turtle
player = turtle.Turtle()
player.color("powder blue")
player.shape("arrow")
player.penup()
player.speed(0)
#Create goal
goal = turtle.Turtle()
goal.color("red")
goal.shape("turtle")
goal.penup()
goal.speed(0)
goal.setposition(-100, -100)
#Set speed
speed = 1
#Define functions
def turnleft():
player.left(30)
def turnright():
player.right(30)
def increasespeed():
global speed
speed +=0.5
def decreasespeed():
global speed
speed -= 1
#Set keyboard binding
turtle.listen()
turtle.onkey(turnleft, "Left")
turtle.onkey(turnright, "Right")
turtle.onkey(increasespeed, "Up")
turtle.onkey(decreasespeed, "Down")
while True:
player.forward(speed)
#Boundary check
if player.xcor() > 300 or player.xcor() < -300:
print("I Knew you could never be a WARLORD... Try Again")
quit()
if player.ycor() > 300 or player.ycor() < -300:
print("I Knew you could never be a WARLORD... Try Again")
quit()
#Collision checking
d= math.sqrt(math.pow(player.xcor()-goal.xcor(),2) + math.pow(player.ycor()-goal.ycor(),2))
if d < 20 :
goal.setposition(random.randint(-300,300), random.randint(-300, 300))
score = score + 1
print ("\n" * 40)
print("Wow, You Actually got one!")
print("I think you Might Have What it Takes to be the Next WARLORD BOSS")
print("Enemies Killed")
print (score)
This code is your problem:
text=turtle.Pen()
t.pencolor("magenta")
t.hideturtle()
turtle.clear()
t.penup()
t.setposition(-100, -350)
t.write("TOUCH THE EDGES, I DARE YOU", font=("Verdana", 18))
You copied and pasted but forgot to update t. to instead be text. Also, turtle.clear() doesn't make sense as that refers to a different turtle altogether:
text = turtle.Pen()
text.hideturtle()
text.pencolor("magenta")
text.penup()
text.setposition(-100, -350)
text.write("TOUCH THE EDGES, I DARE YOU", font=("Verdana", 18))
I am new to Python 3 and I am currently making a turtle game where if you hit a red turtle, you go to the start. I do not know how to make the player move to make them collide. My code:
from turtle import Turtle, Screen
wn = Screen()
wn.bgcolor("black")
artist = Turtle()
artist.color('white')
artist.speed(0)
artist.penup()
artist.setposition(-300, -300)
artist.pendown()
artist.pensize(4)
for side in range(4):
artist.fd(600)
artist.lt(90)
artist.hideturtle()
player = Turtle()
player.color("white")
player.penup()
player.setposition(260, 260)
player.speed(10)
enemy = Turtle('circle')
enemy.color('red')
enemy.penup()
enemy.speed(9)
if player.distance(enemy) < 5:
player.hideturtle()
player.setposition(260, 260)
player.showturtle()
I do not know how to make them collide and move the player, it won't
move.
Since the OP used a proper turtle import (for turtle's Object-Oriented API) and used the distance() method instead of reimplementing one like many folks, +1!
Below I've reworked the code to provide player movement, so that it can finally collide with the enemy. To keep this example minimalist, I've made the boundary circular instead of rectangular as in the original:
from turtle import Screen, Turtle
RADIUS = 300
CURSOR_RADIUS = 10
CURSOR_DIAMETER = CURSOR_RADIUS * 2
START = RADIUS / 2 ** 0.5 - CURSOR_DIAMETER
def move_forward():
screen.onkey(None, 'Up') # disable handler inside handler
player.forward(CURSOR_RADIUS)
if player.distance(0, 0) >= RADIUS:
player.undo()
if player.distance(enemy) < CURSOR_RADIUS:
player.hideturtle()
player.setposition(START, START)
player.showturtle()
screen.onkey(move_forward, 'Up') # reenable handler
screen = Screen()
screen.bgcolor('black')
artist = Turtle(visible=False)
artist.color('white')
artist.speed('fastest')
artist.pensize(4)
artist.penup()
artist.sety(-RADIUS)
artist.pendown()
artist.circle(RADIUS)
artist.penup()
artist.setposition(START, START)
artist.pendown()
artist.dot(CURSOR_DIAMETER, 'green')
enemy = Turtle('circle')
enemy.color('red')
enemy.penup()
player = Turtle()
player.speed('fastest')
player.color('white')
player.penup()
player.setposition(START, START)
player.setheading(player.towards(enemy))
screen.onkey(lambda: player.right(45), 'Right')
screen.onkey(lambda: player.left(45), 'Left')
screen.onkey(move_forward, 'Up')
screen.listen()
screen.mainloop()
You can control the player with the arrow keys. Now the enemy needs to be made to do something other than just sit in the middle.
Basically what I'm trying to do is create a two player game using Python's turtle module. There are two turtles at the bottom which are the players and two circles at the top which act as checkpoints. One turtle is supposed to go back and forth between the two checkpoints—this turtle is the target. The bottom turtles shoot circles at the target.
My issues:
The target turtle moves way too rapidly.
The bullets for the turtles at the bottom spawn from the middle of the screen.
Note: There may be some parts of the code which are confusing and/or not needed.
Here's the code:
from turtle import*
import math
def k1():#Enemy Key Commands
enemy.left(90)
enemy.forward(10)
enemy.right(90)
def k2():
enemy.left(90)
enemy.backward(10)
enemy.right(90)
def k3():#Yertle Key Commands
yertle.left(90)
yertle.forward(10)
yertle.right(90)
def k4():
yertle.left(90)
yertle.backward(10)
yertle.right(90)
def k5():
a=bullet_red()
a.speed(10)
a.forward(400)
collision= math.sqrt(math.pow(a.xcor()-yertle.xcor(),2)+math.pow(a.ycor()-yertle.ycor(),2))
if(collision<10):
text=enemy.write("Game Over", align="center" , font=("Arial", 16, "normal"))
a.hideturtle()
def k6():
a=bullet_blue()
a.speed(10)
a.forward(400)
collision= math.sqrt(math.pow(a.xcor()-yertle.xcor(),2)+math.pow(a.ycor()-yertle.ycor(),2))
if(collision<10):
text=enemy.write("Game Over", align="center" , font=("Arial", 16, "normal"))
a.hideturtle()
def collision(a, b):
collision= math.sqrt(math.pow(a.xcor()-b.xcor(),2)+math.pow(a.ycor()-b.ycor(),2))
if(collision<5):
print("Bottom Player Wins")
print("Game Over")
def bullet_red():
bullet=Turtle("circle")#Description For Bullet
bullet.color("red")
bullet.penup()
bullet.goto(enemy.pos())
bullet.setheading(180)
bullet.right(90)
return bullet
def bullet_blue():
bullet=Turtle("circle")#Description For Bullet
bullet.color("blue")
bullet.penup()
bullet.goto(yertle.pos())
bullet.setheading(180)
bullet.right(90)
return bullet
ops = Screen()
ops.setup(500, 500)
ops.onkey(k1, "a")#Enemy
ops.onkey(k2, "d")#Enemy
ops.onkey(k3, "Left")#Yertle
ops.onkey(k4, "Right")#Yertle
ops.onkey(k5, "w")#Shoot(Enemy)
ops.onkey(k6, "Up")#Shoot(Enemy)
ops.listen()
checkpoint_1=Turtle(shape="circle")#Turtle Description for Checkpoint 1
checkpoint_1.color("red")
checkpoint_1.setheading(180)
checkpoint_1.right(90)
checkpoint_1.penup()
checkpoint_1.setx(-220)
checkpoint_1.sety(230)
checkpoint_1.speed(0)
#_____________________________
checkpoint_2=Turtle(shape="circle")#Turtle Description for Checkpoint 2
checkpoint_2.color("red")
checkpoint_2.setheading(180)
checkpoint_2.right(90)
checkpoint_2.penup()
checkpoint_2.setx(220)
checkpoint_2.sety(230)
checkpoint_2.speed(0)
#____________________________
runner=Turtle(shape="turtle")#Turtle Description for Checkpoint 2
runner.color("yellow")
while(runner!=collision):
runner.penup()
runner.goto(checkpoint_1.pos())
runner.goto(checkpoint_2.pos())
runner.speed(0)
#_____________________________
enemy=Turtle(shape="turtle")#Turtle Description for Player 1
enemy.color("red")
enemy.setheading(180)
enemy.right(90)
enemy.penup()
enemy.setx(-20)
enemy.sety(-200)
enemy.speed(0)
#_____________________________
yertle = Turtle(shape="turtle")#Turtle Description for Player 2
yertle.color("blue")
yertle.setheading(180)
yertle.right(90)
yertle.penup()
yertle.setx(20)
yertle.sety(-200)
yertle.speed(0)
#_____________________________
Below is my rework of your code to get it to just basically play the game -- it still needs work to become a finished program.
from turtle import Turtle, Screen
FONT = ("Arial", 32, "bold")
def k1(): # Enemy Key Commands
enemy.backward(10)
def k2():
enemy.forward(10)
def k3(): # Yertle Key Commands
yertle.backward(10)
def k4():
yertle.forward(10)
def k5(): # enemy shoot
bullet.color("red")
bullet.goto(enemy.position())
bullet.showturtle()
bullet.forward(430)
if bullet.distance(runner) < 10:
magic_marker.write("Game Over", align="center", font=FONT)
bullet.hideturtle()
def k6(): # yertle shoot
bullet.color("blue")
bullet.goto(yertle.position())
bullet.showturtle()
bullet.forward(430)
if bullet.distance(runner) < 10:
magic_marker.write("Game Over", align="center", font=FONT)
bullet.hideturtle()
def move_runner():
if runner.distance(checkpoint_1) < 5 or runner.distance(checkpoint_2) < 5:
runner.left(180)
runner.forward(2)
screen.ontimer(move_runner, 50)
screen = Screen()
screen.setup(500, 500)
bullet = Turtle("circle", visible=False) # Description For Bullet
bullet.speed('normal')
bullet.penup()
bullet.setheading(90)
checkpoint_1 = Turtle("circle", visible=False) # Turtle Description for Checkpoint 1
checkpoint_1.color("red")
checkpoint_1.penup()
checkpoint_1.goto(-220, 230)
checkpoint_2 = checkpoint_1.clone() # Turtle Description for Checkpoint 2
checkpoint_2.goto(220, 230)
runner = Turtle("turtle", visible=False)
runner.color("orange")
runner.speed('fastest')
runner.penup()
runner.sety(230)
yertle = Turtle(shape="turtle", visible=False) # Turtle Description for Player 1
yertle.tiltangle(90) # face one way but move another!
yertle.speed('fastest')
yertle.penup()
yertle.color("blue")
yertle.goto(20, -200)
enemy = yertle.clone() # Turtle Description for Player 2
enemy.color("red")
enemy.goto(-20, -200)
checkpoint_1.showturtle()
checkpoint_2.showturtle()
runner.showturtle()
yertle.showturtle()
enemy.showturtle()
magic_marker = Turtle(visible=False) # for writing text
screen.onkey(k1, "a") # Enemy
screen.onkey(k2, "d") # Enemy
screen.onkey(k3, "Left") # Yertle
screen.onkey(k4, "Right") # Yertle
screen.onkey(k5, "w") # Shoot(Enemy)
screen.onkey(k6, "Up") # Shoot(Yertle)
screen.listen()
move_runner()
screen.mainloop()
Your code had errors (as did your comments) but my primary advice is to review the turtle documentation to see all the features available to you -- when writing a game, you need to know what a turtle can do.
I changed the bullets into a single shared bullet -- turtles don't go away when you're finished with them so this seemed better resource-wise. But it's also buggy, however. If you continue with a single bullet model, you'll want to interlock the firing events to prevent overlap. If you instead go with multiple bullets firing at the same, you'll want to add more ontimer events like the runner uses to control their motion.