Python - Pygame - Handling angles and speeds of animations - python

I'm learning Pygame, and like most people (I think) am writing a little game to get a handle on it. That being said, feel free to answer my questions as well as critique anything else if it sucks.
So, the issue is with my "boss" object. It's supposed to drop into the game from above, and then start firing a random number of shots in a 360deg circle. It works sometimes, but I am noticing a few things going on that I didn't expect. 1) The bullets should be moving at a constant speed, but they seem to slow down over time, and move faster along the Y plane than the X. 2) Despite there being minimum 8 shots, I often only see 3-4 (pretty sure some are overlapping as I often see one shot that looks a little bigger), and some will shoot down and to the right and one will shoot in the opposite direction. It shouldn't do that. So, here's the code. I'll post the shooting calculations, and then the bullet (Fireball) instance. The rest is pretty typical from what I've seen. I update and draw by calling the sprite group they're in, which are called at the bottom of my main loop.
def shoot (self, shots, time_passed):
angle = (math.pi*2)/shots
for i in xrange(shots):
bullet = Fireball("fireball.png", self.direction, 100)
bullet.angle = angle
bullet.pos = ((math.sin(bullet.angle) * bullet.speed) * time_passed,
(math.cos(bullet.angle) * bullet.speed) * time_passed)
Fireball.container.remove(bullet)
EnemyFireball.container.add(bullet)
bullet.rect.center = self.rect.center
angle += angle
And this is the bullet:
class Fireball (pygame.sprite.Sprite):
container = pygame.sprite.Group()
def __init__ (self, image, direction, speed):
pygame.sprite.Sprite.__init__ (self, self.container)
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
self.radias = ((self.rect.width/2 + self.rect.height/2)/2)
self.speed = speed
self.direction = direction
self.angle = -1
def update (self, time_passed):
if self.angle != -1:
self.rect.move_ip(self.pos)
else:
self.rect.move_ip(0, (self.speed*time_passed) * self.direction)
if self.rect.bottom < 0: self.kill()
if self.rect.top > 2000: self.kill()
If I may draw a picture... 0 <-- boss, and lines for bullets.
What I expect:
\|/
-0-
/|\
What I am seeing:
\
0-
|\
... and the bullet down straight down always looks larger, so I think there's some overlapping, but I can't see why. Time_passed is just the time calculated between Clock.tick(60), and the shots argument is a randint between 8-16.
I hope that all makes sense. If not, let me know. I'll try to clarify. Thanks in advance for the help.
Here's a link to the the source if more context is needed. Don't worry, there's not much. http://code.google.com/p/scroller-practice/source/browse/

you need to keep angle in two variables.
The right way to do it would be
curr_angle = 0
angle_step = (math.pi*2)/shots
and then at the end of each loop
curr_angle += angle_step
the way you do it, you end up with angles angle, then 2*angle, then 4*angle and so forth.
if you take away all the other parts and just have a loop that is
angle = (math.pi*2)/shots
for i in xrange(shots):
angle += angle
it should be clear that you're doubling angle each time instead of incrementing it.

Related

Speed up AI obstacle detection in python pygame

I am trying to train a NEAT algorithm to play a simple game called 'curvefever'.
I was able to create a pygame version of curvefever and now I want to train the AI to play it.
Therefore, the AI has to learn to avoid obstacles: borders surrounding the game and tracks that each player leaves behind, like in Snake.
At the moment I am doing this in the following way:
Each player has a set of 'sensors' reaching forward that detect if and how far away an obstacle is.
Each 'sensor' is a straight line consisting of several pygame rectangles.
For each sensor it will detect if a collision with one of the obstacle rectangles occurred and calculate the distance of the collision to the player.
Which sensor detected the collision and the distance of the collision is the information that goes to the neural network.
The problem is that this is very slow! Running 'python -m cProfile -s cumtime ai.py' I figured that it is the detection of obstacles that is slowing the script down, taking up about 50% of the total runtime.
Please see some code below how I create the lines of sight:
posx = x-position of player
posy = y-position of player
dir = direction the player is going
dangle = is the degree-spacing between lines of sight
angle = total range (in degrees) of lines of sight
def create_lines_of_sight(posx, posy, dir, dangle, angle, length):
dirs = [xdir for xdir in np.ceil(np.arange(dir-angle,dir+angle,dangle))]
d_posx = np.cos(np.deg2rad(dir))
d_posy = np.sin(np.deg2rad(dir))
return list(map(functools.partial(f_lrects,posx,posy,length), dirs))
def create_rects(posx, posy, d_posx, d_posy, i):
return f_rect(posx+i*d_posx,posy+i*d_posy,1,1,0,curvefever.WHITE)
f_create_rect = create_rects
def create_line_of_rects(posx, posy, length,dir):
l = pygame.sprite.Group()
ladd = l.add
d_posx = np.cos(np.deg2rad(dir))
d_posy = np.sin(np.deg2rad(dir))
i = [i for i in range(2,length,8)]
ladd(map(functools.partial(f_create_rect,posx,posy,d_posx,d_posy),i))
return l
f_lrects = create_line_of_rects
All obstacles are rectangles defined as:
class Rect(pygame.sprite.Sprite):
def __init__(self,x,y,width,height,dir,color):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
and are saved in a sprite group.
What I tried
I tried adding a map command to get rid of the for loop, that did not speed it up much.
I tried adding the function names to remove the function lookup, I read this makes it faster, but it didn't.
I tried detecting an obstacle using 'Bresenham's Line Algorithm' and checking if an obstacle (x,y) position overlaps with the line of sight. Although this was a faster it did not work as it often missed obstacles. This happened because the line of sight did not exactly match the obstacle centre (rectx,recty) although it did overlap with the rectangle itself.
What do other people use to detect obstacles (maybe in pygame)? Any tips on how I can make this faster or more efficient are very welcome.
Thank you very much for your help!
I've been working on a similar project.
In the end I've used the pygame.Rect.clipline() and pygame.Vector2.distance_to() methods of pygame:
def intersect_rect(self,other) -> tuple[float,float]:
cl=other.clipline(self.a.x,self.a.y,self.b.x,self.b.y)
if cl:
return cl[0] if self.a.distance_to(cl[0]) <self.a.distance_to(cl[1]) else cl[1]
else:
return
self and other are both of a class, that inherited form the pygame.Rect class. self.a and self.b are two pygame.Vector2 objects. Where self.a is in the origin of the player and self.b the LoS.
This resulted in a speedup of 100x, compared to a pure python function.

How do i restrict the players movement without stopping them from moving entirely

i am trying to do some basic collision detection in pygame, so far I have it set up so if one sprite comes into contact with another they both stop, what I want to know is if my player hits the sprite how can I allow it to go any other way apart from further in the sprite.
How I have it set up now I just have a function that detects whether or not they have collided which changes a global variable that disables movement altogether.
Sprites should have a xVel and yVel variables. These variables will change the x and y variables every frame. The sprite is then drawn to the screen at the respective x and y variables.
class Sprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.xVel = 0
self.yVel = 0
self.x = 100
self.y = 100
# Continue method
def update(self):
self.x += xVel
self.y += yVel
# Continue method
Here's what the sprite collision handling code would look like.
if sprite1.yVel == 0 and sprite2.yVel == 0:
# This is when the sprites are not travelling up or down the y axis
sprite1.xVel = -sprite1.xVel
sprite2.xVel = -sprite2.xVel
if sprite1.xVel == 0 and sprite2.xVel == 0:
# This is when the sprites are not travelling left or right on the x
# axis
sprite1.yVel = -sprite1.yVel
sprite2.yVel = -sprite2.yVel
This code is for 4-way movement. Setting the xVel variable equal to -xVel will make it travel the opposite direction. The same applies to the yVel variable. There is no need to change any global variables as long as you are using objects.
Also when a player is traveling left or right then yVel == 0. If the player is traveling up or down then xVel == 0.
Please note the speed of the sprite's movement will vary according to the framerate. The way you fix this is to use deltatime which is a concept for another question.
Hope this helped!

PyGame Angle between ball(rect) and rectangle

I'm making a simple game,you know,you move with rectangle at the bottom and you are destroying rectangles at the top with ball what is coming up and down and if you miss the ball you lose..I don't know name of that game..The only one problem is angle,I dont have any idea how to calculate the angle,thanks you a lot!!
you can get the angle in radians between any two points with
angle_in_rads = Math.atan2(p1.y-p2.y,p1.x-p2.x)
this formula should work in pretty much any language (I think pretty much all of them have an equivalent of atan2)
you can easily convert this to degrees if you want (you probably dont want it in degrees)
angle_in_deg = angle_in_rads*180/Math.PI
for bounce you really dont need to calculate any angles you just need to invert the bounce axis
if rect.p0.x < ball.x < rect.p1.x and ball.y > rect.p0.y:
ball.vy = ball.vy * -1 # bounce off paddle
if ball.x + ball.vx > game.width or ball.x + ball.vx < 0:
ball.vx = ball.vx * -1 # bounce off the side walls
You mean like Breakout?
I think Pygame is a good place to start, check out their examples, they even have already some Breakout clones.
If you have the movement vector of the ball, you can calculate the angle with pygame.math.Vector2 (even a rotate method is provided, for calculating how the ball bounces back from the bar the player controls).

Frame-independent movement issue in PyGame with Rect class

I'm writing a simple game with PyGame, and I've run into a problem getting things moving properly. I'm not experienced with game programming, so I'm not sure if my approach is even correct..
I have a class Ball, which extends PyGame's Sprite class. Each frame, the Ball object is supposed to move around the screen. I'm using frame-independent(?)/time-based movement with the time delta returned by PyGame's Clock object each time around. Such as,
class Ball(pygame.sprite.Sprite):
# . . .
def update(self, delta):
self.rect.x += delta * self.speed # speed is pixels per second
self.rect.y += delta * self.speed # ... or supposed to be, anyway
... and ...
class Game(object):
# . . .
def play(self):
self.clock = pygame.time.Clock()
while not self.done:
delta = self.clock.tick(self.fps) / 1000.0 # time is seconds
self.ball.update(delta)
PyGame's Sprite class is backed by a Rect object (rect) that tracks the sprite's position. And Rect's coordinates are automatically converted to integers whenever a value is updated. So, my problem is that each time update() is called, any extra fraction-of-a-pixel movement is lost, instead of being accumulated over time as it should. Speed in "pixels per second" isn't accurate this way. Even worse, if the amount of movement per frame is less than one pixel, the ball doesn't move at all for those frames, because it's always rounded down to zero. (i.e., no movement if pps < fps)
I'm not sure how to deal with this. I tried adding separate x and y values to Ball which aren't forced to be integers and updating the rect every time those change. That way the x and y values accumulate the fractions of a pixel as normal. As in,
class Ball(pygame.sprite.Sprite):
# . . .
def update(self, delta):
self.x += delta * self.speed
self.y += delta * self.speed
def getx(self):
return self._x
def setx(self, val):
self._x = val # this can be a float
self.rect.x = val # this is converted to int
def gety(self):
return self._y
def sety(self, val):
self._y = val # this can be a float
self.rect.y = val # this is converted to int
x = property(getx,setx)
y = property(gety,sety)
But that ends up being messy: it's easy to update the rect object when x and y change, but not the other way around. Not to mention the Rect object has lots of other useful coordinates that can be manipulated (like centerx, top, bottomleft, etc. -- which is why one would still want to move the rect directly). I'd more or less end up having to re-implement the whole Rect class in Ball, to store floats before it passes them down to the rect object, or else do everything based on just x and y, sacrificing some of the convenience of the Rect class either way.
Is there a smarter way to handle this?
I don't know if you still need the answer, but I figured this out a bit ago and thought I'd give this question an answer since I came across it in trying to figure out what was going on. (Thanks for helping me confirm the issue, by the way.)
You can make use of Python's round function. Pretty much, just throw what you want into that function, and it'll spit out a properly rounded number.
The first way I got it working was like this:
x = box['rect'].x
if leftDown:
x -= 300 * deltaTime
if rightDown:
x += 300 * deltaTime
box['rect'].x = round(x)
(Where my deltaTime is a float, being a fraction of a second.)
As long as you're putting the float value you get through the round function before applying it, that should do the trick. It doesn't have to use separate variables or anything.
It may be worth noting that you cannot draw in fractions of a pixel. Ever. If you're familiar with a Lite-Brite, pixels work in that way, being a single lit up light. That's why the number you use in the end has to be an integer.

Python 2.7 - Pygame - move_ip() too granular

I'm practicing making an android app in pygame, and decided to do your classic bubble shooter. I have run into a problem though where the projectile launched by the player isn't accurate enough.
def move (self, time_passed):
x = (math.sin(self.angle) * self.speed) * time_passed
y = (math.cos(self.angle) * self.speed) * time_passed
c = self.rect.center
self.rect.center = (c[0]+x, c[1]+y)
def update(self, screen, time_passed):
if self.launched:
if not self.mpos:
self.mpos = pygame.mouse.get_pos()
diffx, diffy = (self.mpos[0]-self.rect.center[0],
self.mpos[1]-self.rect.center[1])
self.angle = math.atan2(diffx, diffy)
self.move(time_passed)
The screen and time_passed arguments are passed from the main loop and are the display and returned value of the Clock class's tick(60)/1000.0, for the sake of clarity.
If I print the values of x and y from move() it's very accurate: x: 1.0017224084 y: -21.9771825359, or something similar depending on where the mouse is. However, it seems pygame or move_ip only work with integers. I can click between what would be 1.00000001 and 1.9999999 and the ball will shoot in the exact spot, being 1 (in reference to the x coordinate). This is bad for my game. Is there a solution to this so I can get my objects to move very precisely?
EDIT: I realized I pasted in the wrong code. self.rect.center = (c[0]+x, c[1]+y) is where self.rect.move_ip(x, y) should be. Both methods yield the same result, however.
Keep track of your own positions using precise float values, and then instead of incrementally moving your Rects from frame to frame, just place them at their proper (integer-ized) positions each frame. That way you don't suffer from the sum of each frame's rounding error, but instead only have a single rounding involved at any given time.

Categories

Resources