A function to replace circle when it's out of the screen - python

The problem is that I need to write a function which will move the drawn circle around the field, an when the circle is going to leave the field it must appear from the opposite side of it (like that snake game on nokia phones, you know)
My progress at this:
def move_wrap(canvas, obj, move):
canvas.move(obj, move[0], move[1])
# if <left the field>:
# <move to the opposite edge>
I am sorry for such a question, UI is really not my thing. But I'm asked to write a game on tkinter, and I have to learn how it all works

Related

Pygame : How to continously move character and view?

I'm not sure how to explain, but I'm trying to make game where player can walk on window and meet enemies etc.
I have code with one window. Like this:
window = pygame.display.set_mode((500, 480))
And my character can move left, right and jump on this window, but when he gets to the corner he stops. So my question is how to make him move further and, for example, change background, meet another enemies etc. when he walks?
Do I have to make a class and call her when character touch corner maybe?
I hope you understand.
Thanks.
You need to understand when your character touch / is close enough to the border of the screen and then take appropriate action.
In a game I'm writing for fun, the class representing the main character has a method to check when the character is inside a surface sface. I copy-paste its skeleton here to show an example:
def insidesurf(self, sface):
if sface.get_rect().contains(self.rect):
return None
else:
if self.rect.top < sface.get_rect().top:
#the character is going out from the screen from the top-side
elif self.rect.left < sface.get_rect().left:
#the character is going out from the screen from the left-side
elif self.rect.bottom > sface.get_rect().bottom:
#the character is going out from the screen from the bottom-side
elif self.rect.right > sface.get_rect().right:
#the character is going out from the screen from the right-side
This method is called at each iteration of the main loop after the character is moved (after a key press). The argument sface is your window.
What to do exactly in the various if statements is up to you. In my case, it redraws the screen replacing the character at the opposite side of the screen. If the character is exiting from left side, it's redrawn at right side, to give the impression that the camera is showing the next room and the character is at the same position.
You may also wish to not pass your window but a smaller surface in order to scroll the scenario instead of redrawing it all.

How to shade a box when mouse hovers in pygame?

I am making a game, with pygame, and i want it to be that when the mouse hovers over my text, the box gets shaded.
here is what I have so far:
in the event-handling loop:
(tuples in CheckToUnshadeBoxes are pairs of text-surfaces and their boxes (from get_rect method))
elif event.type == MOUSEMOTION:
CheckToShadeBoxes(event, LERect, LoadRect, PlayRect)
CheckToUnshadeBoxes(event, (LERect, LESurf),
(LoadRect, LoadSurf), (PlayRect, PlaySurf))
here is CheckToShadeBoxes:
def CheckToShadeBoxes(event, *args):
'''
shade the box the mouse is over
'''
for rect in args:
s = pg.Surface((rect.width, rect.height))
s.set_alpha(50)
print(rect.x, rect.y)
s.fill(COLOURS['gray'])
x, y = event.pos
if rect.collidepoint(x, y):
SURFACE.blit(s, (rect.x, rect.y))
and CheckToUnshadeBoxes:
def CheckToUnshadeBoxes(event, *args):
''' if the mouse moves out of the box, the box will become unshaded.'''
for (rect, TextSurf) in args:
x, y = event.pos
if not rect.collidepoint(x, y):
SURFACE.blit(TextSurf, (rect.x, rect.y))
This works fine! except that when I move the mouse inside of the box, the box will continue to get darker and darker until you cant even see the text! I know it is a small detail, but it has been bugging me for a long time and I don't know how to fix it.
by the way, if it is not evident enough, COLOURS is a dictionary with string keys and RGB tuple values, and SURFACE is my main drawing surface.
If you have any questions about my code, or anything I have done just comment!
If the rects you are passing are your own derived class, then I recommend making a .is_shaded class variable and checking to make sure the variable is false before shading it.
If these rects aren't your own class extending another, then I recommend you make one, as it would make it much simpler
The problem with your code is that you keep adding in dark rectangles when the mouse is hovered over. No wonder it gets darker and darker.
All that is needed is for your code to be shuffled around a little.
Inside your event handling, you should call a function to check if it should shade the text. This should return a Boolean value. Store this in a variable. Most of the code from the CheckToShadeBoxes function will do the trick.
In your render section, you should render just one surface on top of your text, based on whether the Boolean value is true or not. The code that creates a gray surface in the CheckToShadeBoxes function will work but make sure it is only one surface. Don't create a new surface in every iteration. Define it outside once and blit it to the screen inside the loop.
This should fix your problem!
I hope this answer helps you! If you have any further questions please feel free to post a comment below!

Python Turtle Graphics - Bring A Turtle To The Front

I have two turtles in my program. An animation happened where they collide together, but I would like one turtle to be on top of the other like this:
So, my question is - how can I make this happen - is there a simple line of code such as: turtle.front(), if not what is it?
I discuss this briefly in my response to Make one turtle object always above another where the rule of thumb for this simple situation is:
last to arrive is on top
Since Python turtle doesn't optimize away zero motion, a simple approach is to move the turtle you want on top by a zero amount:
import turtle
def tofront(t):
t.forward(0)
gold = turtle.Turtle("square")
gold.turtlesize(5)
gold.color("gold")
gold.setx(-10)
blue = turtle.Turtle("square")
blue.turtlesize(5)
blue.color("blue")
blue.setx(10)
turtle.onscreenclick(lambda x, y: tofront(gold))
turtle.done()
The blue turtle overlaps the gold one. Click anywhere and the situation will be reversed.
Although #Bally's solution works, my issue with it is that it creates a new turtle everytime you adjust the layering. And these turtles don't go away. Watch turtle.turtles() grow. Even my solution leaves footprints in the turtle undo buffer but I have to believe it consumes less resources.
Just add this to turtle.py file
def tofront(self, tobring):
newfront = tobring.clone()
tobring.ht()
return newfront
works correct,
so method - sould return you new clone of turtle, on the top of all other turtles.
parameter tobring - it's your current turtle (the one you want to bring to front)
you can use this def in your program or put it into turtle.py file
if so, don't forget to add it to list of commands, - _tg_turtle_functions
_tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',
'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'tofront', 'color',
I did it after clone command
Hope this will help you

Pygame Line of Sight from Fixed Position

I am currently working on a 2D game in which the player has to sneak up on a still person within a certain amount of time. There are various crates in the way (depending on which level it is), and I would like to make it so that the player can hide behind crates to sneak up on the still person.
I thought that I could use a cone-type vision for the person looking, but I'm not exactly sure how I would accomplish that. The player doesn't have to see the vision cone of the person looking either.
A similar effect to what I would like is in this sample code on github.
NOTE: The player cannot pass through the crates, and the people and crates are sprites.
You have to calculate the if the player is in line with the person, if it is you can check for every box if the 3 objects are ate the same position, if not you are in vision field person_looking. concidere player and person a list with coords.
def isInLine(player, person):
deltaX = person[0] - player[0]
deltaY = person[1] - player[1]
if (person[0] == player[0]) or (person[1] == player[1]) or (abs(deltaX) == abs(deltaY)):
return true
Like in a chess game, imagine you ahve to check if the king is in check by a queen. Its the same logic here.
I think you can create an invisible projectile of a size of one pixel which you launch at desired angle towards player. You make it have some travel speed (say 2 pixels at a time) but instead of actually allowing the projectile to travel every frame you just loop for its travel untill it collides with something (either player or crate or end of level). So the whole emmision and collision process is done outside of while True main game loop in some function. You can emit it every second or something instead of every frame. And also you can emmit it in a cone shape either by scailing it's size every loop or emiting new one at different angle. If any of those collide with player mask or rect -> you have established a line of sight. This idea actually came to me right now out of the blue...
;)
On the second thought... maybe not 1 pixel size projectile but just collidepoint function. Just move your point from emmision origin to target at desired resolution.

Creating DampedRotarySpring in pymunk between a dynamic body and a moving static body

I'm trying to do what the title says. I have a character with a gun constrained to its hand, and I'm trying to get the gun to point at the cursor. I figured that a DampedRotarySpring would be a nice way to do it, but it turns out not to be as simple as that. The gun is a dynamic body with a Segment shape, and for the cursor I create a static body whose position I set to the mouse location with pygame each step.
When I run the program, the gun simply does not move at all except for the effect of gravity or collisions.
Here is the relevant code:
# add crosshairs at the location of the mouse
pointer_body = pymunk.Body()
pointer_shape1 = pymunk.Segment(pointer_body, (0,CROSSHAIRS_SIZE), (0,-CROSSHAIRS_SIZE), 1) # vertical segment
pointer_shape2 = pymunk.Segment(pointer_body, (-CROSSHAIRS_SIZE,0), (CROSSHAIRS_SIZE,0), 1) # horizontal segment
# add a spring that will angle the gun toward the mouse
spring = pymunk.DampedRotarySpring(me.gun.body, pointer_body, 0, 0.01, 1)
space.add(pointer_shape1, pointer_shape2, spring)
while True:
# handle event queue
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
from math import atan2
# update location of pointer
pointer_body.position = flipy(pygame.mouse.get_pos())
pointer_body.angle = atan2( (pointer_body.position.y - me.gun.body.position.y), (pointer_body.position.x - me.gun.body.position.x) )
Edit:
Here is a Gist repository of all my code: https://gist.github.com/4470807.
The main loop is in ragdoll.py.
The problem with the code in the gist is that you have attached the gun to the hand with two joints to keep them in the same place and same rotation. However, the the hand is a rouge body and wont rotate. Therefor the gun wont rotate when its pulled by the spring between it and the cursor, because that other joint is stronger.
Im not sure exactly how you want the setup, but you can see that it all works if you remove the RotaryLimitJoint from the gun-hand.
Take a look at a fixed fork of the code for the exact details: https://gist.github.com/4505219
Some tips for future troubleshooting that I did to find the problem:
Make everything 10x bigger so its easy to see what happens. I know pymunk only draws in one size, but it was easy to just add a 0 on the end of all sizes in the code.
Make the hand not move so its easier to see how it rotates (removed all stuff in the update_hand_position method)
Disable collisions between all shapes in the scene so that the rotating gun is not hindered by some body part. (did a simple loop of space.shapes and ran shape.group=1)
Maybe your problem is with the spring parameters? The stiffness and damping looks very low unless the gun is extremely light.
Check out this code example I added to pymunk yesterday: http://code.google.com/p/pymunk/source/browse/trunk/examples/damped_rotary_spring_pointer.py
(There is one thing going on with the rotation when it flip over between positive and negative pi that I will look at)

Categories

Resources