I'm trying to make a game using turtle in python. I'm trying to code some sort of collision. My original idea is to have a variable be the location of a turtle so, for example, if turtle 1's location/coordinates are equal to that of turtle 2's the game ends. So in layman's terms I want to know if there is a way to turn the location of a turtle into a variable.
Use the pos method or other methods defined here to get the location of the turtle.
pos returns the position as a Vec2D vector. xcor and ycor return the current x and y coordinates of turtle as float.
Related
I dont know how to change the size of a turtle hitbox in python turtle graphics
I haven't tried anything yet because I'm new, and know very little about this. I've tried googling it, though, but nothing popped up.
from turtle import *
import turtle
from random import randint
import time
screen = turtle.Screen()
screen.setup(1920, 1080)
player = turtle.Turtle()
I want to add a button that you have to click to start right here
The game starts right here :
wn = turtle.Screen()
last_pressed = 'up'
def setup(col, x, y, w, s, shape):
player.penup()
player.up()
player.goto(x,y)
player.width(w)
player.turtlesize(s)
player.color(col)
player.lt(90)
player.down()
wn.onkey(up, "s")
wn.onkey(left, "d")
wn.onkey(right, "a")
wn.onkey(back, "w")
wn.onkey(quitTurtles, "Escape")
wn.listen()
wn.mainloop()
This may not be exactly what you are looking for, but this might work in your situation.
Detecting collision in Python turtle game
This is a thread on collision detection between objects and with some tweaking of numbers you could increase the hitbox of the turtle using the abs() function
I dont know how to change the size of a turtle hitbox in python turtle graphics
What do you mean by "hitbox"? I'm not sure what you mean by that (and neither does Google, apparently).
Do you mean that you want a rectangular button to click on? If that's the case, you could use the tkinter module together with the turtle module to create a button to click. (But be aware that it's not always easy to get the tkinter and turtle modules to work together to do what you want.)
If you want a button to click on, but don't need a Tkinter button, you could just try creating a new turtle in the shape of a rectangle that intercepts mouse clicks with onclick(). You can see an example of this if you run:
python3 -m turtledemo
and select Examples >> colormixer from the main menubar.
Or, if by "hitbox" you mean how to detect when one turtle has intercepted another turtle (as in, one has come close enough to the other to be considered a "hit"), I suggest querying each turtle's location, then using the Pythagorean Theorem to calculate the distance from each other. If this distance is within a predetermined threshold, consider the hitbox as being "hit."
You can see an example of this by typing:
python3 -m turtle
(Pay attention to the yellow turtle as he tries to catch up to the other turtle.)
I apologize if this answer isn't quite what you're looking for, but I'm just not sure what you mean by "hitbox." Maybe you could clarify?
I just saw this question today (2 years too late i know), and was having a similar problem / question.
What I ended up doing was running 3 distance checks (as i had increased my object size by 3) which differed along the x-axis (width). So it would check the distance between the ball(turtle) and the paddle (any 3 points and if it was shorter than X it would trigger the collision mechanic.
so it was something like :
check the ball class' ball object, and see how far away it is from the paddle,
and if its either in the center, or 30 pixels to the left or right of the center then hit.
if
ball.ball.distance(pad.paddle(), pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() - 30, pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() + 30, pad.paddle.ycor()) < 30
Is there a way in pygame for sprites, when dragged, to snap to an invisible (or visible) grid? Kinda like drag 'n drop? If so, how? I've been trying to do some sprite overlap, but it's too tedious to make an if-statement for each of the grid-lines. So how can I make a snap-to-grid drag-n-drop sprite? This is for a chess program. I'll appreciate your help.
Make an array of corners of the chess board using for loops.
corners = []
for x in range(edgeRight, edgeLeft, interval):
for y in range(edgeTop, edgeBottom, interval):
corners.append((x,y))
Then, make an event listener. When the piece is being dragged around, insert this code into whatever while statement you have:
px, py = Piece.Rect.topleft //using tuples to assign multiple vars
for cx, cy in corners:
if math.hypot(cx-px, cy-py) < distToSnap:
Piece.setPos((cx,cy))
break
I have no idea what your actual code is, but this should give you an idea. Again, pygame has no snap-to-grid functionality.
So this can be done quite simply by using the round function in python.
sprite.rect.x = ((round(sprite.rect.x/gridSquareSize))*gridSquareSize)
sprite.rect.y = ((round(sprite.rect.y/gridSquareSize))*gridSquareSize)
This manipulates the round function, by rounding your sprite's coordinates to the nearest grid square.
I'm creating a function that will cause a giraffe to move in a certain direction and distance (don't ask).
If the user types "west" in the parameters, the turtle should move west however the direction is. But the turtle's angle changes every time, I can't fix a value for my turtle to turn to go a certain direction.
I need to set the angle to, say, 90 so that it can move East. I can't find useful functions for this purpose. I tried to use Pen().degrees(90) but that didn't work. Does anyone know how I can do this?
You're looking for turtle.setheading()
>>> turtle.setheading(90)
>>> turtle.heading()
90.0
You can combine this with a simple dict to get exactly the result you are after.
turtle.right(90)
this will turn the turtle 90
I'm trying to get the mouse position through Python turtle. Everything works except that I cannot get the turtle to jump to the position of the mouse click.
import turtle
def startmap(): #the next methods pertain to drawing the map
screen.bgcolor("#101010")
screen.title("Welcome, Commadore.")
screen.setup(1000,600,1,-1)
screen.setworldcoordinates(0,600,1000,0)
drawcontinents() #draws a bunch of stuff, works as it should but not really important to the question
turtle.pu()
turtle.onclick(turtle.goto)
print(turtle.xcor(),turtle.ycor())
screen.listen()
As I understand, the line that says 'turtle.onclick(turtle.goto)' should send the turtle to wherever I click the mouse, but it does not. The print line is a test, but it only ever returns the position that I sent the turtle last, nominally (0, 650) although this does not have major significance.
I tried looking up tutorials and in the pydoc, but so far I have not been able to write this successfully.
I appreciate your help. Thank you.
Edit: I need the turtle to go to the click position(done) but I also need it to print the coordinates.
You are looking for onscreenclick(). It is a method of TurtleScreen. The onclick() method of a Turtle refers to mouse clicks on the turtle itself. Confusingly, the onclick() method of TurtleScreen is the same thing as its onscreenclick() method.
24.5.4.3. Using screen events¶
turtle.onclick(fun, btn=1, add=None)
turtle.onscreenclick(fun, btn=1, add=None)¶
Parameters:
fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas
num – number of the mouse-button, defaults to 1 (left mouse button)
add – True or False – if True, a new binding will be added, otherwise it will replace a former binding
Bind fun to mouse-click events on this screen. If fun is None, existing bindings are removed.
Example for a TurtleScreen instance named screen and a Turtle instance named turtle:
>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>> # make the turtle move to the clicked point.
>>> screen.onclick(None) # remove event binding again
Note: This TurtleScreen method is available as a global function only under the name onscreenclick. The global function onclick is another one derived from the Turtle method onclick.
Cutting to the quick...
So, just invoke the method of screen and not turtle. It is as simple as changing it to:
screen.onscreenclick(turtle.goto)
If you had typed turtle.onclick(lambda x, y: fd(100)) (or something like that) you would probably have seen the turtle move forward when you clicked on it. With goto as the fun argument, you would see the turtle go to... its own location.
Printing every time you move
If you want to print every time you move, you should define your own function which will do that as well as tell the turtle to go somewhere. I think this will work because turtle is a singleton.
def gotoandprint(x, y):
gotoresult = turtle.goto(x, y)
print(turtle.xcor(), turtle.ycor())
return gotoresult
screen.onscreenclick(gotoandprint)
If turtle.goto() returns None (I wouldn't know), then you can actually do this:
screen.onscreenclick(lambda x, y: turtle.goto(x, y) or print(turtle.xcor(), turtle.ycor())
Let me know if this works. I don't have tk on my computer so I can't test this.
Again this question is on PyParticles4.
Link to last question for reference
Comment if unclear...
I am working on a Shooter game, much like this, but on a flat land with a wall that varies it's height on every turn(something for fun in the game) and with 2 players,each with a cannon that can move some distance (there's a limit, and they can't move beyond a certain amount from their start position) on each turn(the player decides if he wishes to move).
My code so far(for the Bullet and Shooter)
class Bullet(PyParticles.Particle):
def hit(self,shooterlist):
for shoot in shooterlist:
#confusion
dist = math.hypot(dx,dy)
# other funcs to added
class Shooter:
def __init__(self,pos,size):
self.rect = pygame.Rect(pos,size)
# other funcs to added
My Problems
Collision of the bullet with the Shooter. Any Ideas on how to know when the bullet collides with the rect?
I have been advised by someone to look at all the points on the edge of the rect, and see if it is within the circle but it seems to be very slow.
I think something faster would be better..
..
..
Update:
The circle can have a rect around it, which if collides with the rect, I now know when the rect is close to the circle, maybe even touching it.. How do i move forward??(Thx to PygameNerd)
I am not sure what you mean by your question, but I thingk that you need the colliderect function.
rect.colliderect(rect): Return bool
Put this in the code somewhere, and if it returns true, have the ball explode.
You can run another test every time colliderect returns true. There are a few options for what that test can be. One is similar to the advice you already received but with the wall and circle switched. Check the points on the circumference of the circle to see if one of them collides with the wall using Rect.collidepoint. In pygame, you can get a list of circumference points by creating a Mask from the circle surface and running Mask.outline. You probably won't need every point, so you could get just every Nth point. In fact, you may only need the midpoints of the edges of the circle's rect, which you can get from the Rect object itself.
You're asking for precise collision, and that would give you pixel perfect collision detection between a circle and a rectangle. You may not need it in your game, though, so I suggest trying with just colliderect first. If you're interested in collision detection in pygame in general, there are a lot of options that are directly implemented in or based on functions described in the Mask and Sprite documentation.
You can use Rect.collidepoint with the center of the circle but make rect bigger
collide_rect = Rect(x - p.radius,y - p.radius,w + 2 * p.radius,h + 2 * p.radius)
if collide_rect.collide_point(p.pos):
# Collision Resolution