how to detect if a turtle is near a different turtle - python

im trying to create a game in python where you need to shoot moving turtles above you, but i dont know how to make the attack detect the turtle and remember it. it also has a problem of when that i shoot the turtles that need to be hit stop moving.(im new to python).
##-----------Turtle setup-----------
from turtle import *
from turtle import Turtle, Screen
import random
from time import sleep
wn=Screen()
wn.setup(600,600)
wn.listen()
game=1
##-----------Player setup-----------
p=Turtle()
p.penup()
p.goto (0,-280)
p.left(90)
p.turtlesize(100)
##-----------Controls-----------
def left():
if p.distance(-280, -280) > 1.0:
p.setx( p.pos()[0] -5 )
def right():
if p.distance(280, -280) > 1.0:
p.setx( p.pos()[0] +5 )
def fire():
l=Turtle()
l.penup()
l.hideturtle()
l.goto(p.pos())
l.showturtle()
l.speed('slowest')
l.setheading(90)
l.pendown()
l.forward(1000)
l.clear()
l.penup()
if l.distance(0, 500) > 1.0:
l.hideturtle
l.goto(0,0)
wn.onkeypress(left, "a")
wn.onkeypress(right, "d")
wn.onkey(fire, "w")
##-----------Enemy setup----------
height1=random.randint(0,280)
e1=Turtle()
e1.penup()
e1.hideturtle()
e1.goto(-290,height1)
height2=random.randint(0,280)
e2=Turtle()
e2.penup()
e2.hideturtle()
e2.goto(290,height2)
height3=random.randint(0,280)
e3=Turtle()
e3.penup()
e3.hideturtle()
e3.goto(-290,height3)
height4=random.randint(0,280)
e4=Turtle()
e4.penup()
e4.hideturtle()
e4.goto(290,height4)
e1.showturtle()
e2.showturtle()
e3.showturtle()
e4.showturtle()
##-----------Enemy AI----------
def looper():
print("hello")
hp1=1
while hp1 == 1:
e1.setheading(0)
e1.speed('slowest')
e1.forward(590)
sleep(5)
e1.setheading(180)
e1.forward(590)
sleep(5)
if
if game == 1:
print("back")
looper()
looper()
(a lot of the code doesnt function properly but i started this 3 days ago)

You can achieve getting the distance between 2 turtles with e1.distance(e2), but I recommend not using turtle for games. If you want to make a game in python I recommend using pygame which you can install with pip install pygame, but pygame can be a bit more complicated to use.

Related

Python Turtle Issue

I am tryig to create a turtle game where two players can chase around a "goal" shape. I am struggling to get the program to recognize that two shapes are close to each other and therefore that one player should receive a point and then the goal should move. I have pasted my code below, any help would be greatly appreciated.
import turtle as trtl
import random as rand
#initialization / game setup
wn = trtl.Screen()
player1 = trtl.Turtle()
player1.shape('turtle')
player1.fillcolor('red')
player1.penup()
player1.goto(rand.randint(-100,100),rand.randint(-100,100))
player2 = trtl.Turtle()
player2.shape('triangle')
player2.fillcolor('blue')
player2.penup()
player2.goto(rand.randint(-100,100),rand.randint(-100,100))
goal = trtl.Turtle()
goal.shape('circle')
goal.fillcolor('yellow')
goal.penup()
goal.goto(rand.randint(-200,200),rand.randint(-150,-150))
player1_score = 0
player2_score = 0
def player1_up():
player1.setheading(90)
player1.forward(10)
def player2_up():
player2.setheading(90)
player2.forward(10)
def player1_down():
player1.setheading(270)
player1.forward(10)
def player2_down():
player2.setheading(270)
player2.forward(10)
def player1_right():
player1.setheading(0)
player1.forward(10)
def player2_right():
player2.setheading(0)
player2.forward(10)
def player1_left():
player1.setheading(180)
player1.forward(10)
def player2_left():
player2.setheading(180)
player2.forward(10)
if (abs(player1.xcor() - goal.xcor())<5):
if (abs(player1.ycor() - goal.ycor())<5):
player1_score+=1
goal.goto(rand.randint(-200,200),rand.randint(-150,150))
print(player1_score)
#events
wn.onkeypress(player1_up, "w")
wn.onkeypress(player2_up, "i")
wn.onkeypress(player1_down, "s")
wn.onkeypress(player2_down, "k")
wn.onkeypress(player1_right, "d")
wn.onkeypress(player2_right, "l")
wn.onkeypress(player1_left, "a")
wn.onkeypress(player2_left, "j")
wn.listen()
wn.mainloop()
I tried to simplify the code and I have seen this work in other programs. However, I cannot get it to work here!

Defining a function in python turtles that will change the background color depending on inputs of day, evening, night

I am a beginner and need help with Python Turtles. My school assignment is to make a function that will change a picture we make with Turtles to either day, evening, or night. I have tried the following, but can't understand why it isn't working. It also says that the specific time of day is not defined. Any help would be great.
def draw_scene(time):
screen = turtle.Screen()
if time == day:
screen.bgcolor("white")
elif time == evening:
screen.bgcolor("purple")
elif time == night:
screen.bgcolor("black")
return`
You can simply add ''around day, evening and night to make the code work.
def draw_scene(time):
screen = turtle.Screen()
if time == 'day':
screen.bgcolor("white")
elif time == 'evening':
screen.bgcolor("purple")
elif time == 'night':
screen.bgcolor("black")
return`

NameError: name 'height' is not defined on line 10

I'm currently creating a game for a school project on Python. This is what I have so far and Python's telling me NameError: name 'height' is not defined on line 10. What does this mean? I've done lots of research, but I still can't figure it out. Can someone help me?
import turtle
enter code here`import random
def main():
wn=turtle.Screen();
Gameturtle=turtle.Turtle()
Setupuser(Gameturtle,wn)
Setupcontrols(Gameturtle,wn)
Randomanglegenerator(turtle,len,height)
li = []
InsertEnemyturtleintolist(li)
while (True):
Hitchecker(Gameturtle, li)
def Setupuser(myTurtle,window):
window.bgcolor("white")
#width=x height=y
window.setup (width=400, height=400, startx=100, starty=100)
myTurtle.speed(2)
myTurtle.shape('turtle')
myTurtle.penup()
myTurtle.delay(0)
myTurtle.left(90)
myTurtle.mainloop()
window.exitonclick ()
def Hitchecker(myTurtle, enemyTurtles):
for eturtle in enemyTurtles:
distance=myTurtle.distance(eturtle)
if distance <= 1:
print("You lost a life >:^D")
def InsertEnemyturtleintolist(list):
Enemy=turtle.Turtle()
Enemy.shape=("triangle")
Enemy.speed(5)
Enemy.penup()
Enemy.left(90)
Enemy.showturtle()
list.append(Enemy)
def Setupcontrols(turtle, window):
window.onkey(lambda: turtle.goto(turtle.xcor(), turtle.ycor()+15), 'w')
window.onkey(lambda: turtle.goto(turtle.xcor()-15, turtle.ycor()), 'a')
window.onkey(lambda: turtle.goto(turtle.xcor()+15, turtle.ycor()), 'd')
window.onkey(lambda: turtle.goto(turtle.xcor(), turtle.ycor()-15), 's')
window.listen()
def Randomanglegenerator(turtle,len,height):
XYcord = random.randrange(1,5)
print(XYcord)
if XYcord==2 or 4:
Enemy.setheading(90)
main()
There are several problems with your program. First, invalid or questionable Python syntax:
if XYcord==2 or 4:
wn=turtle.Screen();
Should be something like:
if XYcord == 2 or XYcord == 4:
wn = turtle.Screen()
These are equivalent methods and you should use one or the other, not both. And mainloop() is a method of the screen or a function in the package 'turtle', not a method of a turtle instance:
myTurtle.mainloop()
window.exitonclick()
Instead do:
window.mainloop()
or:
window.exitonclick()
Redefining Python built-ins like list is a bad idea:
def InsertEnemyturtleintolist(list):
...
list.append(Enemy)
instead do:
def InsertEnemyturtleintolist(myEnemiesList):
...
myEnemiesList.append(Enemy)
Finally, an infinite loop like this has no place in an event-driven world like turtle:
while (True):
we need to replace it with a timer event. Below is my rewrite of your code to address the above issues and get it to basically function:
from turtle import Screen, Turtle
from random import randrange
def main():
screen = Screen()
turtle = Turtle()
SetupUser(turtle, screen)
SetupControls(turtle, screen)
RandomAngleGenerator(turtle)
enemies = []
for _ in range(5):
InsertEnemyTurtleIntoList(enemies, turtle)
HitChecker(turtle, screen, enemies)
screen.mainloop()
def SetupUser(myTurtle, myScreen):
myScreen.bgcolor('white')
myScreen.setup(width=400, height=400, startx=100, starty=100)
myTurtle.speed('slow')
myTurtle.shape('turtle')
myTurtle.penup()
def SetupControls(myTurtle, myScreen):
myScreen.onkey(lambda: myTurtle.sety(myTurtle.ycor() + 15), 'w')
myScreen.onkey(lambda: myTurtle.setx(myTurtle.xcor() - 15), 'a')
myScreen.onkey(lambda: myTurtle.setx(myTurtle.xcor() + 15), 'd')
myScreen.onkey(lambda: myTurtle.sety(myTurtle.ycor() - 15), 's')
myScreen.listen()
def HitChecker(myTurtle, myScreen, enemyTurtles):
dead = False
for myEnemy in enemyTurtles:
if myTurtle.distance(myEnemy) <= 10:
print("You lost a life >:^D")
dead = True
break
if dead:
myScreen.onkey(None, 'w')
myScreen.onkey(None, 'a')
myScreen.onkey(None, 'd')
myScreen.onkey(None, 's')
else:
myScreen.ontimer(lambda: HitChecker(myTurtle, myScreen, enemyTurtles), 100)
def InsertEnemyTurtleIntoList(array, myTurtle):
enemy = Turtle()
enemy.hideturtle()
enemy.shape('triangle')
enemy.speed('normal')
enemy.penup()
enemy.left(90)
enemy.showturtle()
while enemy.distance(myTurtle) < 30:
enemy.setposition(randrange(-190, 190), randrange(-190, 190))
array.append(enemy)
def RandomAngleGenerator(myTurtle):
turns = randrange(1, 3)
for _ in range(turns):
myTurtle.left(90)
main()
I'm sure it doesn't do everything you want it to do yet, but this should give you a workable starting point to finish your program.

How to stop a program once player has reached a set time on Python game

I have just gotten into python and am trying to create a quiz game. I would like to add a countdown timer of 2 minutes to my quiz so when the timer reaches zero the questions stop and says you are out of time. I also tried to do this with a stopwatch but couldn't figure out how to terminate play so if you know how to do that it would be just as good.
Note: I am NOT using pygame. Many other users have asked in previous threads.
This is the code I gathered from the other documents but it doesn't stop once it reaches 2 mins or 0 mins.
def countdown():
t = 60
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
t -= 1
print("You're out of time!\n")
sys.exit ("goodbye")
def main_game():
count_thread = threading.Thread(None, countdown)
question_4 = ("question 1?")
option_4 = (" a. 1 \n b. 5 \n c. 3 \n d. 7")
print(question_4)
print(option_4)
answer_4 = input (">")
if answer_4.lower()== "b":
score = score + 100
else:
print("Incorrect")
import time
start1 = time.time()
if start1 >= 120:
import sys
sys.exit
question_a = ("question?")
option_a = (" a. 7 \n b. 8 \n c. 2 \n d. 1")
print(question_a)
print(option_a)
answer_a = input (">")
if answer_a.lower()== "b":
score = score + 100
else:
print("Incorrect")
###rest of questions
end1 = time.time()
Both codes are two different versions I have tried. Both codes don't work. The bottom code times the play but it doesn't stop at the 2 minute mark.
Any help, advice, or feedback would be appreciated!
Since you use Pygame.
The simplest code you may have should (by good codding standards) include pygame.quit(). Like this:
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Followed by Python sys.exit function.
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
You can make the quiz game w/o explicit use of Python threads, but If you plan to use Python threads you can start by checking the quick and dirty example from here.
Hope this helps. You already can find quizzes in pygame online and possible modify that.

Progress bar in python curses

I have created a progress bar which updates itself after getting a percentage from another function but I'm having issues getting it to trail like this ############. Instead, it just move the '#' to the right until 100% is reached. Below is my code. The reason why it's this way is because I need the percentage to come externally so that the code can be reusable. please help me.
import curses
import time
curses.initscr()
def percentage():
loading = 0
while loading < 100:
loading += 1
time.sleep(0.03)
update_progress(loading)
def update_progress(progress):
win = curses.newwin(3, 32, 3, 30)
win.border(0)
rangex = (30 / float(100)) * progress
pos = int(rangex)
display = '#'
if pos != 0:
win.addstr(1, pos, "{}".format(display))
win.refresh()
percentage()
The problem is that you call newwin() every time, discarding the old win and replacing it with a new one in the same place. That new window only gets one character added to it, with the background being blank, so you see an advancing cursor instead of a bar.
One possible solution:
import curses
import time
curses.initscr()
def percentage():
win = curses.newwin(3, 32, 3, 30)
win.border(0)
loading = 0
while loading < 100:
loading += 1
time.sleep(0.03)
update_progress(win, loading)
def update_progress(win, progress):
rangex = (30 / float(100)) * progress
pos = int(rangex)
display = '#'
if pos != 0:
win.addstr(1, pos, "{}".format(display))
win.refresh()
percentage()
curses.endwin()
(Note the addition of a call to endwin() to restore the terminal to its normal mode.)
As far as leaving it onscreen after the program finishes, that's kind of outside the scope of curses. You can't really depend on any interaction between curses and stdio, sorry.
you can just switch the pos to multiply the display #:
if pos != 0:
win.addstr(1, 1, "{}".format(display*pos))
win.refresh()

Categories