Can someone please help me debug my code because I don't get why I cannot make my character do a double jump with multiple spacebars. When I ran the script, I could move up,down,left,right but once I press spacebar one time, the object flies out of the window.
The problem comes with this if statement so I'm guessing that this if statement keeps running and incrementing my jumpCount, which I can't comprehend because after pressing space one time shouldn't the keys[pygame.K_SPACE] evaluate to true and then back to false again so this if statement shouldn't run unless I press another spacebar?
else:
if keys[pygame.K_SPACE]:
jumpCount += 5
number_to_compensate += 1
Here is my script:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 5 #To calculate the height I have to rise by
number_to_compensate = 0 #So the more times I press space(higher I jump) the more I have to fall by
run = True
while run:
pygame.time.delay(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - vel - width:
x += vel
if not (isJump):
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
if keys[pygame.K_SPACE]:
isJump = True
number_to_compensate += 1
else:
if keys[pygame.K_SPACE]:
jumpCount += 5
number_to_compensate += 1
if jumpCount >= -5 *number_to_compensate:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 5
isJump = False
number_to_compensate = 0
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
To what you want you need to change some the jump algorithm. Calculate the jump based on an acceleration and a velocity.
Define constants for the gravity and jump acceleration:
PLAYER_ACC = 15
PLAYER_GRAV = 1
Use the keyboard events for the jump, instead of pygame.key.get_pressed(). The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action.
Set the jump acceleration when the space is pressed:
acc_y = PLAYER_GRAV
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
acc_y = -PLAYER_ACC
vel_y = 0
Change the velocity depending on the acceleration and the y coordinate depending on the velocity in every frame:
vel_y += acc_y
y += vel_y
Limit the y-coordinate by the ground:
if y + height > ground_y:
y = ground_y - height
vel_y = 0
acc_y = 0
Minimal example:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
clock = pygame.time.Clock()
ground_y = 400
x, y = 200, ground_y
width, height = 40, 60
vel_x, vel_y = 5, 0
acc_y = 0
PLAYER_ACC = 15
PLAYER_GRAV = 1
run = True
while run:
acc_y = PLAYER_GRAV
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
acc_y = -PLAYER_ACC
vel_y = 0
keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel_x
x = max(0, min(500 - width, x))
vel_y += acc_y
y += vel_y
if y + height > ground_y:
y = ground_y - height
vel_y = 0
acc_y = 0
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
clock.tick(60)
pygame.quit()
Related
I want to make my character jump. In my current attempt, the player moves up as long as I hold down SPACEv and falls down when I release SPACE.
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if keys[pygame.K_SPACE]:
rect.y -= 1
elif rect.y < 220:
rect.y += 1
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
However, I want the character to jump if I hit the SPACE once. I want a smooth jump animation to start when SPACE is pressed once.
How would I go about this step by step?
To make a character jump you have to use the KEYDOWN event, but not pygame.key.get_pressed(). pygame.key.get_pressed () is for continuous movement when a key is held down. The keyboard events are used to trigger a single action or to start an animation such as a jump. See alos How to get keyboard input in pygame?
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
jump = True
Use pygame.time.Clock ("This method should be called once per frame.") you control the frames per second and thus the game speed and the duration of the jump.
clock = pygame.time.Clock()
while True:
clock.tick(100)
The jumping should be independent of the player's movement or the general flow of control of the game. Therefore, the jump animation in the application loop must be executed in parallel to the running game.
When you throw a ball or something jumps, the object makes a parabolic curve. The object gains height quickly at the beginning, but this slows down until the object begins to fall faster and faster again. The change in height of a jumping object can be described with the following sequence:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
Such a series can be generated with the following algorithm (y is the y coordinate of the object):
jumpMax = 10
if jump:
y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
A more sophisticated approach is to define constants for the gravity and player's acceleration as the player jumps:
acceleration = 10
gravity = 0.5
The acceleration exerted on the player in each frame is the gravity constant, if the player jumps then the acceleration changes to the "jump" acceleration for a single frame:
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
In each frame the vertical velocity is changed depending on the acceleration and the y-coordinate is changed depending on the velocity. When the player touches the ground, the vertical movement will stop:
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
See also Jump
Example 1: replit.com/#Rabbid76/PyGame-Jump
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
jump = False
jumpCount = 0
jumpMax = 15
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if jump:
rect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
Example 2: replit.com/#Rabbid76/PyGame-JumpAcceleration
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
player = pygame.sprite.Sprite()
player.image = pygame.Surface((30, 30), pygame.SRCALPHA)
pygame.draw.circle(player.image, (255, 0, 0), (15, 15), 15)
player.rect = player.image.get_rect(center = (150, 235))
all_sprites = pygame.sprite.Group([player])
y, vel_y = player.rect.bottom, 0
vel = 5
ground_y = 250
acceleration = 10
gravity = 0.5
run = True
while run:
clock.tick(100)
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
keys = pygame.key.get_pressed()
player.rect.centerx = (player.rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
player.rect.bottom = round(y)
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
all_sprites.draw(window)
pygame.display.flip()
pygame.quit()
exit()
I've tried many ideas like importing pynput but it kept on crashing and making my computer messed up. I've tried putting it in a loop but that didn't work as well and kept crashing
import sys
import pygame
import random
import os
import time
pygame.init()
#assigns thingys to window adjustments
size = width, height = 750, 750
white = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Snake Game")
#The coordinates and size of the snake square thingy
x = 350
y = 350
w = 25
h = 25
ax = range(30,700)
ay = range(40,700)
aw = 15
ah = 15
vel = 10
vertical1 = 9000
vertical2 = 0
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)
textx = 10
testy = 10
def show_score(x, y):
score = font.render("Score: "+ str(score_value), True, (255,0,0))
screen.blit(score, (x, y))
def divisible_random(a,b,n):
if b-a < n:
raise Exception('{} is too big'.format(n))
result = random.randint(a, b)
while result % n != 0:
result = random.randint(a, b)
return result
def apple(x,y):
pygame.draw.rect(screen, (255, 0, 0), (arx, ary, aw, ah))
arx = divisible_random(30,700,10)
ary = divisible_random(40,700,10)
while 1:
#Delays the movement so you can see snake thingy fps
pygame.time.delay(25)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
#gets the presses to move the snake
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
while True:
x= x - vel
if keys[pygame.K_RIGHT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
break
if keys[pygame.K_RIGHT]:
while True:
x= x + vel
if keys[pygame.K_LEFT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
break
if keys[pygame.K_DOWN]:
while True:
y = y + vel
if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_UP]:
break
if keys[pygame.K_UP]:
while True:
y = y - vel
if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_DOWN]:
break
screen.fill(white)
#The snake thingy and apple thingy
apple(arx, ary)
snake = pygame.draw.rect(screen, (0, 0, 0), (x, y, w, h))
diffrencex = abs(arx-x)
diffrencey = abs(ary-y)
if ((x == arx and y == ary) or ((diffrencex == 10 and x < arx) and (diffrencey == 10 and y < ary)) or ((diffrencex==10 and x< arx) and (y == ary)) or ((x == arx) and (diffrencey==10 and y< ary))):
score_value += 1
arx = divisible_random(30,700,10)
ary = divisible_random(40,700,10)
#Borders for the frame thingy
pygame.draw.line(screen, (0,0,0), (14, 10), (14, 800), 30)
pygame.draw.line(screen, (0,0,0), (734, 10), (734, 800), 30)
pygame.draw.line(screen, (0,0,0), (9000, 734), (0 , 734), 30)
pygame.draw.line(screen, (0,0,0), (9000, 24), (0 , 24), 30)
if x < 30:
x = 700
if x > 700:
x = 30
if y > 700:
y = 40
if y < 40:
y = 700
show_score(textx, testy)
print(arx,ary,x,y)
pygame.display.update()
pygame.quit
I know the code isn't neat not organized but I'm working on it as soon as I finish making the game
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
while True:
x= x - vel
if keys[pygame.K_RIGHT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
break
if keys[pygame.K_RIGHT]:
while True:
x= x + vel
if keys[pygame.K_LEFT] or keys[pygame.K_DOWN] or keys[pygame.K_UP]:
break
if keys[pygame.K_DOWN]:
while True:
y = y + vel
if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_UP]:
break
if keys[pygame.K_UP]:
while True:
y = y - vel
if keys[pygame.K_LEFT] or keys[pygame.K_RIGHT] or keys[pygame.K_DOWN]:
break
I encounter problems here to be exact
Use the keyboard events (KEYDOWN, KEYUP - see pygame.event) rather than pygame.key.get_pressed(). Add a variable direction and change the state tof the variable when LEFT, RIGHT, UP respectively DOWN is pressed. Change the player's position according to the direction:
direction = (0, 0)
while 1:
#Delays the movement so you can see snake thingy fps
pygame.time.delay(25)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
direction = (-1, 0)
elif event.key == pygame.K_RIGHT:
direction = (1, 0)
elif event.key == pygame.K_UP:
direction = (0, -1)
elif event.key == pygame.K_DOWN:
direction = (0, 1)
x += vel * direction[0]
y += vel * direction[1]
You want continuous movement, but you don't want to hold down the button. You want to move the snake even if no key is pressed. Therefore, you need to save the direction of movement in a variable and change the direction once when a key is pressed. The keyboard event occurs once when a key is pressed and is the right choice to change direction.
Use a variable to store the direction of movement. Have key presses affect that variable. Then, check that variable every loop iteration, and move the snake according to the direction.
What I am trying to do here is make my collision detect allow me to jump on a square but it doesn't seem to work. Its a the very bottom of the main loop.
# --- COLLISION is at the bottom of main loop
# ------
# this is a pygame module that I imported
import pygame
pygame.init()
# this is just my screen I created win defines it
win = pygame.display.set_mode((500,500))
# this is my caption for my game
pygame.display.set_caption("Just Tryna learn Something")
# these are my coordinates for my enemy where it will spawn
cordx = 300
cordy = 300
heights = 70
widths = 70
# my Player Coordinate and its speed and and its Jump
x = 200
y = 200
height = 40
width = 40
speed = 5
isJump = False
jumpCount = 10
# main loop
# main loop for my game
running = True
while running:
pygame.time.delay(100)
win.fill((0,0,0))
#-----------------------------------------------------------------------------------------
# this here draws my player in my window
Player = pygame.draw.rect(win, (140, 0,150), (x, y, height, width))
#-----------------------------------------------------------------------------------------
# this here draws my enemy
Enemy = pygame.draw.rect(win, (90,90,90), (cordx, cordy, heights, widths))
#=-------------------------------------------------------------------------------------
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#-------------------------------------------------------------------
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= speed
if keys[pygame.K_RIGHT]:
x += speed
# this here is my functions for movement and Jumping
if not(isJump):
if keys[pygame.K_UP]:
y -= speed
if keys[pygame.K_DOWN]:
y += speed
if keys[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -10:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 10
isJump = False
# COLLISION here is my collision detect and collision
its suppose to make me stand on the square with my little box when I jump on it
but it doesnt seem to work (Enemy) is the big box and (Player) is the little box
if Player.colliderect(Enemy):
pygame.draw.rect(win, (150,0,140), (50, 50, 20, 70))
if Player.top >= 375 and Player.top <= 370:
x = 375
# ---------------------------------------------------------
pygame.display.update()
pygame.quit()
Continuously let the player fall down. Add a variable fall = 0 and the variable to y and increment fall in every frame, if the player is not jumping. A jump ends, if the player reaches the maximum jump height (jumpCount == 0):
if not isJump:
y += fall
fall += 1
# [...]
else:
if jumpCount > 0:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 10
isJump = False
Limit the player to the bottom of the window (500), and the top of the block by setting the y coordinate of the player:
Player.topleft = (x, y)
collide = False
if Player.colliderect(Enemy):
y = Enemy.top - Player.height
collide = True
if Player.bottom >= 500:
y = 500 - Player.height
collide = True
It is only allowed to jump, if the player stands on the ground or on the block:
if collide:
if keys[pygame.K_SPACE]:
isJump = True
fall = 0
Furthermore use pygame.time.Clock() and tick(), instead of pygame.time.delay() for a smooth movement. Control the speed by the flops per second (FPS):
FPS = 60
clock = pygame.time.Clock()
running = True
while running:
clock.tick(FPS)
#pygame.time.delay(100)
See the example:
# --- COLLISION is at the bottom of main loop
# ------
# this is a pygame module that I imported
import pygame
pygame.init()
# this is just my screen I created win defines it
win = pygame.display.set_mode((500,500))
# this is my caption for my game
pygame.display.set_caption("Just Tryna learn Something")
# these are my coordinates for my enemy where it will spawn
cordx = 300
cordy = 350
heights = 70
widths = 70
# my Player Coordinate and its speed and and its Jump
x = 200
y = 200
height = 40
width = 40
speed = 5
isJump = False
jumpCount = 10
fall = 0
FPS = 60
clock = pygame.time.Clock()
# main loop
# main loop for my game
running = True
while running:
clock.tick(FPS)
#pygame.time.delay(100)
win.fill((0,0,0))
#-----------------------------------------------------------------------------------------
# this here draws my player in my window
Player = pygame.draw.rect(win, (140, 0,150), (x, y, height, width))
#-----------------------------------------------------------------------------------------
# this here draws my enemy
Enemy = pygame.draw.rect(win, (90,90,90), (cordx, cordy, heights, widths))
#=-------------------------------------------------------------------------------------
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#-------------------------------------------------------------------
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= speed
if keys[pygame.K_RIGHT]:
x += speed
# this here is my functions for movement and Jumping
if not isJump:
y += fall
fall += 1
Player.topleft = (x, y)
collide = False
if Player.colliderect(Enemy):
collide = True
y = Enemy.top - Player.height
if Player.right > Enemy.left and Player.left < Enemy.left:
x = Enemy.left - Player.width
if Player.left < Enemy.right and Player.right > Enemy.right:
x = Enemy.right
if Player.bottom >= 500:
collide = True
y = 500 - Player.height
if collide:
if keys[pygame.K_SPACE]:
isJump = True
fall = 0
else:
if jumpCount > 0:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 10
isJump = False
pygame.display.update()
pygame.quit()
I was trying to create something along the lines of mario, this is far from perfect I know. Anyways, while trying to make the "jumping" method I ran into an issue - The jumping doesn't work the way I intended it to work. Whenether I click the space bar my red square moves up and down randomly, I have to press the spacebar and hold it to complete a jump and even then its not perfect. Sometimes when I hold the space bar for too long the red square will continue to jump again. Is there any way to solve this issue? I'd be very thankful for any help, thanks.
import pygame, time, math, random, sys
from pygame.locals import *
background = pygame.image.load("assets/MarioBackground.png")
def events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
W, H = 640, 400
HW, HH = W / 2, H / 2
AREA = W * H
FPS = 60
bg_x = 0
isJump = False
jumpCount = 10
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((W,H))
pygame.display.set_caption("Mario")
class Mario():
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
pygame.draw.rect(screen, (255,0,0), (self.x, self.y, 40, 40))
def move(self):
global bg_x
if pressed_keys[K_RIGHT] and bg_x > -920:
if self.x > 490:
bg_x -= 5
else:
self.x += 5
if pressed_keys[K_LEFT] and self.x > 5:
self.x -= 5
def jump(self):
global jumpCount, isJump
if pressed_keys[K_SPACE]:
if jumpCount >= -10:
isJump = True
print(jumpCount)
neg = 1
if jumpCount < 0:
neg = -1
self.y -= (jumpCount ** 2) * 0.1 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 10
mario = Mario(50, 270)
while True:
clock.tick(FPS)
events()
pressed_keys = pygame.key.get_pressed()
screen.blit(background, (bg_x,0))
mario.move()
mario.draw()
mario.jump()
pygame.display.update()
Just check if isJump is true and then execute the jumping code in the jump method. I also recommend adding the isJump and jumpCount as attributes to Mario, so that you don't have to modify global variables.
To prevent the continuous jumping while Space is pressed, you have to handle the key press in the event queue. Then the jump action is triggered only once per key press not while the key is being held down.
import pygame, time, math, random, sys
from pygame.locals import *
background = pygame.Surface((640, 400))
background.fill((30, 90, 120))
W, H = 640, 400
HW, HH = W / 2, H / 2
AREA = W * H
FPS = 60
bg_x = 0
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((W,H))
class Mario():
def __init__(self, x, y):
self.x = x
self.y = y
# isJump and jumpCount should be attributes of Mario.
self.isJump = False
self.jumpCount = 10
def draw(self):
pygame.draw.rect(screen, (255,0,0), (self.x, self.y, 40, 40))
def move(self):
global bg_x
if pressed_keys[K_RIGHT] and bg_x > -920:
if self.x > 490:
bg_x -= 5
else:
self.x += 5
if pressed_keys[K_LEFT] and self.x > 5:
self.x -= 5
def jump(self):
# Check if mario is jumping and then execute the
# jumping code.
if self.isJump:
if self.jumpCount >= -10:
neg = 1
if self.jumpCount < 0:
neg = -1
self.y -= self.jumpCount**2 * 0.1 * neg
self.jumpCount -= 1
else:
self.isJump = False
self.jumpCount = 10
mario = Mario(50, 270)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
# Start to jump by setting isJump to True.
mario.isJump = True
clock.tick(FPS)
pressed_keys = pygame.key.get_pressed()
screen.blit(background, (bg_x,0))
mario.move()
mario.draw()
mario.jump()
pygame.display.update()
You can fix it by implementing the following rules:
you can only begin a jump when you touch the floor
you start a jump by pressing the space bar (set a variable) and stop it, when you touch the floor
you start a jump on keydown (pygame.KEYDOWN) not if pressed.
Some code snippets:
Begin jump
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and self.y == 0:
isJump = True
End jump
if self.y == 0:
isJump = False
With this rules you can only jump, when you're on the floor. You don't need to hold the space bar and you won't jump a second time if you hold the space bar to long
Thank you in advance for your time.
If I fire a bullet with space key, a stream of bullets are created. If I would set a delay with time.sleep() inside 'if keys[pygame.K_SPACE]:' it would also freeze the loop for the set amount of seconds. How could I make it so only 1 bullet fires at a time? This is the copy of my game loop, please tell me if more of the code is needed:
def game_loop():
global pause
x = (display_width * 0.2)
y = (display_height * 0.2)
x_change = 0
y_change = 0
blob_speed = 3
velocity = [2, 2]
pos_x = display_width/1.2
pos_y = display_height/1.2
gameExit = False
while not gameExit:
for event in pygame.event.get():#monitors hardware movement/ clicks
if event.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
if pos_x + blob_width > display_width or pos_x < 601:
velocity[0] = -velocity[0]
if pos_y + blob_height > display_height or pos_y < 0:
velocity[1] = -velocity[1]
# Checks to see if any keys are held down and remembers them with the variable keys.
keys = pygame.key.get_pressed()
for b in range(len(bullets)):
bullets[b][0] += 6
for bullet in bullets:
if bullet[0] > 1005:
bullets.remove(bullet)
if keys[pygame.K_SPACE]:
bullets.append([x+25, y+24])
# If the player is holding down one key or the other the blob moves in that direction
if x < 0:
x = 0
if keys[pygame.K_a]:
x_change = -blob_speed
if x > 401 - blob_width:
x = 401 - blob_width
if keys[pygame.K_d]:
x_change = blob_speed
if keys[pygame.K_p]:
pause = True
paused()
# If the player is holding down both or neither of the keys the blob stops
if keys[pygame.K_a] and keys[pygame.K_d]:
x_change = 0
if not keys[pygame.K_a] and not keys[pygame.K_d]:
x_change = 0
if y < 0:
y = 0
if keys[pygame.K_w]:
y_change = -blob_speed
if y > display_height - blob_height:
y = display_height - blob_height
if keys[pygame.K_s]:
y_change = blob_speed
if keys[pygame.K_w] and keys[pygame.K_s]:
y_change = 0
if not keys[pygame.K_w] and not keys[pygame.K_s]:
y_change = 0
#print(event)
# Reset x and y to new position
x += x_change
y += y_change
gameDisplay.fill(blue) #changes background surface
pygame.draw.line(gameDisplay, black, (601, display_height), (601, 0), 3)
pygame.draw.line(gameDisplay, black, (401, display_height), (401, 0), 3)
blob(pos_x, pos_y)
blob(x, y)
for bullet in bullets:
gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
pygame.display.update() #update screen
clock.tick(120)#moves frame on (fps in parameters)
Here's an answer without classes. You just have to store the previous time when a bullet was fired, subtract it from the current time and check if it's above some time limit (500 ms in this example) to see if we're ready to fire.
import pygame
def game_loop():
pygame.init()
gameDisplay = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
bulletpicture = pygame.Surface((10, 5))
bulletpicture.fill(pygame.Color('sienna1'))
bullets = []
x = 50
y = 240
previous_time = pygame.time.get_ticks()
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
current_time = pygame.time.get_ticks()
# We're ready to fire when 500 ms have passed.
if current_time - previous_time > 500:
previous_time = current_time
bullets.append([x+25, y+24])
remaining_bullets = []
for bullet in bullets:
bullet[0] += 6 # Move the bullet.
if bullet[0] < 500: # Filter out the bullets.
remaining_bullets.append(bullet)
bullets = remaining_bullets
gameDisplay.fill((30, 30, 30))
for bullet in bullets:
gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
pygame.display.update()
clock.tick(120)
game_loop()
pygame.quit()