Pygame "Asteroids" Style Screen - python

I'm trying to design a game with screen transfer mechanics similar to Asteroids. I want it so that if you move to the edge of the screen, you appear on the other end. Here is a test code so far. The idea is to move too far right and reappear on the left. I do appear on the left, but only after I lift up on the right key.
if position_x >= 1200:
position_x = 0

You definitely should post some of your code so we know how you set position_x and how you use it, but what I can say that might help is to use modulo instead of direct resetting. So for example, when you're updating position_x - position_x = (position_x + speed) % 1200

Related

Using recursion in pygame

I'm new to python and programming in general and am working on a final project for a python centric class. One of the requirements that I cant seem to figure out how to make work is to integrate recursion into our code in order to show a working knowledge. I've worked up a simple "bullet hell" style game using pygame.
My goal is that when contact is made between a bullet and an enemy, that a series of bullet sets will be launched from the player position as a sort of short-term modifier.
This code runs in the main loop whenever a bullet hits an enemy:
for i in reversed(range(len(bullets))):
for j in reversed(range(len(enemies))):
if bullets[i].collided(enemies[j].rect):
del enemies[j]
del bullets[I]
s.global_score += 100
more_bullets(10)
#print("Hit!")
#print(s.global_score)
break
The "more_bullets" function is the focus of my recursion, and calls this:
def more_bullets(n):
if(n > 0):
spawnx = sq.rect.x+10 + sq.rect.width/2 - 10
b = Square(s.red, spawnx,sq.rect.y, 10,30)
b.direction = 'N'
b.player_speed = 10
bullets.append(b)
spawnx = sq.rect.x-10 + sq.rect.width/2 - 10
b = Square(s.red, spawnx,sq.rect.y, 10,30)
b.direction = 'N'
b.player_speed = 10
bullets.append(b)
pygame.display.update()
more_bullets(n-1)
print(f"Fired x {n}")
The outcome currently is that my debug does print 10 times making me think that the recursion is functioning correctly, however only one set of bullets is firing when the collision occurs. I'm thinking that all 10 bullets are firing faster than I can register it and just stacking on the screen.
Is there an easy-to-use function that might slow down the firing of the bullets? or have messed up something more fundamentally here?
I'm thinking that all 10 bullets are firing faster than I can register it and just stacking on the screen.
You're correct.
I don't believe there's an "easy way" to do what you're asking the way you think. The recursion is immediate, meaning that the function runs 10 times right away when it's called. For it to send out a burst of staggered bullets, you'd need some kind of timer or queue or something along those lines that runs alongside your main loop, and recursion isn't really a natural fit for that. The same will go for any kind of game logic function that plays out over a period of time.
This isn't what's being asked, but here's an idea of what you could do, even though it's kind of a redundant use of recursion: add a parameter to that function that dictates the angle the bullet is being shot. Then, add a little bit to that parameter on every recursive call. That way an arc of bullets will be shot at the same time.

Is there a way to keep an object in bounds in pygame, and make it move when you hold the directional keys down?

I am using pygame 1.9.6 and python 3.7.7. I am looking for a way to have something drawn by pygame(or maybe even an image) that stays inside the window border(and stops when I release the key. I started with the “if keys[]:” method:
if keys[pygame.K_LEFT] and x>0:
x-=speed
that made it stay in bounds, but it only moved a few pixels and then did not repeat.
Next I tried the “event.key” method:
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
xchange=-speed
ychange=-0
but that just makes the object move forever. I tried putting “and x>0” on the same line right after the direction, an “if x>0:” before, an “if x<0:” after, but the event never updates to see that the coordinates are past the edge, even with update commands. It just keeps going and going. I also don’t know how to make the object stop moving when I release the key, since event.key’s have the event always on.
Thank you for all the help you can offer.
In order for something to stay within a frame, you must check if it's coordinates are not past the border before moving it.
keys = pygame.key.get_pressed()
if(keys[K_LEFT]):
if(square.left > 0):
square.left -= 10
if(keys[K_RIGHT]):
if(square.right < 600):
square.left += 10
if(keys[K_UP]):
if(square.top > 0):
square.top -= 10
if(keys[K_DOWN]):
if(square.bottom < 600):
square.bottom += 10
This is an example of how you would do this with a Rect object, it checks for border and then moves the object if its within those border and the appropriate key is being pressed. I can't apply this to your code as I cannot see enough of it but you just have to replace the coordinates. For example, you might have thing.x instead of square.left

name 'delta_scroll' is not defined even though I defined it?

so I am trying to make my enemy not scroll with my camera when it moves left and right
I someone helped me make a function to stop my enemy from scrolling all it suppose to do is not make my enemy scroll example vid
def onscroll(enemying, delta_scroll):
for enemys in enemying:
enemys.position = (enemys.position[0] - delta_scroll, enemys.position[1])
then on my main loop I called that function so my enemy doesnt scroll with my screen
# camera left and right movement
if playerman.y < 250:
playerman.y += 1
for enemys in enemying:
enemys.y += delta_scroll
but for some reason I keep getting the same error
name 'delta_scroll' is not defined
Enemy Class
my full code
Quick tip- there are a TON of pg.image.load("myImg.png") commands. here is a better way of doing it:
standingright = []
for i in range(1, 16):
imgPath = "d"+str(i)+".png"
img = pg.image.load(imgPath)
standingright.append(img)
This is a much more concise way of loading the images. It will result in the exact same list of images in the exact same order, but I thought I would mention it to you because it will make your code much neater.
About the issue at hand: I searched your code for mentions of delta_scroll, and found it being used, but never defined. Also I saw you defined the function "onscroll", but never used it. Are you getting these two mixed up perhaps?

Python Inputs module - detect axis of gamepad joystick with lenience?

To simplify this problem, let's say I simply want to be able to detect whether my gamepad's right thumbstick is being pushed up (but not horizontally, within some lenience), pushed to the right (but not up, within some lenience) or being pushed to the left (but not up, within some lenience).
Unfortunately, the lenience is required, but I haven't found a way to do it yet. Thusfar I have been using the inputs library:
https://pypi.org/project/inputs/
But it's not super well documented and as far as I can tell it doesn't let you compare an exact angle of the thumbstick at any one time.
Using their own example code, I have this snippet of a function:
def get_true_game_input():
inputArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0]
# All the different buttons that are important to be detected, including whether the thumbstick has been moved left, right, or up
events = get_gamepad()
for event in events:
if event.code == "ABS_RY":
if event.state >= 8000:
print("top Guard!")
inputArray[5] = 1
elif event.code == "ABS_RX":
if event.state >= 8000:
inputArray[6] = 1
print("right guard!")
elif event.state <= -8000:
inputArray[4] = 1
print("left guard!")
Which works up until one moves the stick, for example, upwards, then ever so slightly to the left or right, whereupon it will detect that instead.
The problem is that, with the way Inputs seems to work, events is always either empty, or of size 1. So it will either detect a horizontal movement or a vertical movement, and one will overwrite the other.
Is there some way to solve this? I am also open to rebuilding this using a different library, but cannot find any other. I am using a dualshock 4 controller using the DS4 Tool.
Any help or advice would be greatly appreciated. Thank you.

My Character Sprite Doesn't Move Off Screen

I have been going over Paul Craven's Python and Pygame tutorial and lately I am trying to understand everything in Sprites. So, being inspired by Craven's multiple levels code, I've written my own code on it and it worked fine.
The logic is, if player sprite is off screen(for example screen width is equal to 640 and player's x value is greater than 640, than you are in the next level). Than, I decided to add menu to my game(?) and menu works fine as well.
The problem is, now my character can't get to second level. It seems it's x value is unable to pass 640, and I don't know why.
Since I am not able to use Stackoverflow editor good enough to share Python code(you know, intended), I will be using Pastebin to share my code.
http://pastebin.ubuntu.com/10392389/
Stackoverflow doesn't let me post the image files I've used, but they are classic pictures I got from the internet.
Any help is appreciated, thanks.
if current_level_num == 1 and player.rect.x > SCREEN_WIDTH:
current_level_num = 2
current_level = levels[current_level_num]
player.rect.x = 0
if current_level_num == 2 and player.rect.x < 1:
current_level_num = 1
current_level = levels[current_level_num]
player.rect.x = SCREEN_WIDTH
The character moves to the 2nd level, then immediately moves back to the 1st. The player should be moved farther to the right than the level 2 boundary.

Categories

Resources