I am not getting any frames even though I have set my clock tick to 60 and it is in the right space. I also know its not my computer because I have run larger games with better frames. Also it cant be the indentation because I have it intended correctly.
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
gameclock = pygame.time.Clock()
fps = str(int(gameclock.get_fps()))
playerX = 250
playerY = 250
playerSpeed = 3
playerFrontImg = pygame.image.load("Images/PlayerImages/playerFront.png")
playerRightImg = pygame.image.load("Images/PlayerImages/playerRight.png")
playerBackImg = pygame.image.load("Images/PlayerImages/playerBack.png")
playerLeftImg = pygame.transform.flip(playerRightImg, True, False)
playercurrentImg = playerFrontImg
running = True
while running:
gameclock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
playerY -= playerSpeed
playercurrentImg = playerBackImg
if event.key == pygame.K_DOWN:
playerY += playerSpeed
playercurrentImg = playerFrontImg
if event.key == pygame.K_RIGHT:
playerX += playerSpeed
playercurrentImg = playerRightImg
if event.key == pygame.K_LEFT:
playerX -= playerSpeed
playercurrentImg = playerLeftImg
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
playerY += 0
if event.key == pygame.K_DOWN:
playerY += 0
if event.key == pygame.K_RIGHT:
playerX += 0
if event.key == pygame.K_LEFT:
playerX += 0
playerRect = playercurrentImg.get_rect(topleft = (playerX, playerY))
screen.fill((255, 255, 100))
print(fps)
screen.blit(playercurrentImg, (playerX, playerY))
pygame.display.update()
pygame.quit()
quit()
Any help would be greatly appreciated, I have been struggling with this issue for awhile now.
Is there any other tips on how I should organize my code.
You need to invoke get_fps() in the application loop:
Compute your game's framerate (in frames per second). It is computed by averaging the last ten calls to Clock.tick().
gameclock = pygame.time.Clock()
# [...]
running = True
while running:
gameclock.tick(60)
fps = str(int(gameclock.get_fps()))
# [...]
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 or a step-by-step movement.
pygame.key.get_pressed() returns a list 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:
running = True
while running:
gameclock.tick(60)
fps = str(int(gameclock.get_fps()))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
playerY -= playerSpeed
playercurrentImg = playerBackImg
if keys[pygame.K_DOWN]:
playerY += playerSpeed
playercurrentImg = playerFrontImg
if keys[pygame.K_RIGHT]:
playerX += playerSpeed
playercurrentImg = playerRightImg
if keys[pygame.K_LEFT]:
playerX -= playerSpeed
playercurrentImg = playerLeftImg
# [...]
Related
So I'm trying to do a game in python, I'm new to pygame, so I was following some tutorials, the player it's showing perfectly, but the enemy isn't showing. I've tried watching the tutorial multiple times, but I still have no clue of what it's happening.
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
#Titulo E Icono
pygame.display.set_caption("Invaders")
icon = pygame.image.load('logo.jpg')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('spaceship.png')
playerX = 370
playerY = 480
playerX_change = 0
enemyImage = pygame.image.load('enemy.png')
enemyX = 370
enemyY = 48
enemyX_change = 0
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y):
screen.blit(enemyImg, (x, y))
#Loop
running = True
while running:
screen.fill((59, 59, 59))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#Right Or Left Checker
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.5
if event.key == pygame.K_RIGHT:
playerX_change = 0.5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <=0:
playerX=0
elif playerX >=736:
playerX = 736
player(playerX, playerY)
pygame.display.update()
You missed to call the enemy function. In addition, the events must be handled in the event loop:
running = True
while running:
screen.fill((59, 59, 59))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# INDENTATION
#-->|
#Right Or Left Checker
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.5
if event.key == pygame.K_RIGHT:
playerX_change = 0.5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <=0:
playerX=0
elif playerX >=736:
playerX = 736
player(playerX, playerY)
enemy(enemyX, enemyY) # <--- this is missing
pygame.display.update()
I am writing my first pygame script, but the K_SPACE event does not work. When the script is run, nothing happens when the space bar is pressed. I have changed K_SPACE to K_LEFT and K_LSHIFT and they work absolutely fine, so I don't think the error is in the code itself?
The Input is mid-way through the code but I wanted to include it all to ensure there were no issues above which were causing it.
Any ideas?
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('spaceship.png')
pygame.display.set_icon(icon)
background = pygame.image.load('space.jpg')
playerImg = pygame.image.load('battleship.png')
playerX = 370
playerY = 480
playerX_change = 0
enemy1Img = pygame.image.load('alien.png')
enemy1X = random.randint(0,800)
enemy1Y = random.randint(50,150)
enemy1X_change = 0.1
enemy1Y_change = 40
laserImg = pygame.image.load('laser.png')
laserX = 0
laserY = 480
laserX_change = 0
laserY_change = 0.5
laser_state = "ready"
def player(x, y):
screen.blit(playerImg, (playerX,playerY))
def enemy1(x, y):
screen.blit(enemy1Img, (enemy1X, enemy1Y))
def fire_laser(x, y):
global laser_state
laser_state = "fire"
screen.blit(laserImg, (x+30, y+10))
running = True
while running:
screen.fill((0, 0, 0))
screen.blit(background, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
elif event.key == pygame.K_RIGHT:
playerX_change = 0.1
elif event.key == pygame.K_SPACE:
if laser_state == 'ready':
laserX = playerX
fire_laser(laserX, laserY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
enemy1X += enemy1X_change
if enemy1X <= 0:
enemy1X_change = 0.1
enemy1Y += enemy1Y_change
elif enemy1X >= 736:
enemy1X_change = -0.1
enemy1Y += enemy1Y_change
if laserY <= 0:
laserY = 480
laser_state = 'ready'
if laser_state == "fire":
fire_laser(laserX,laserY)
laserY -= laserY_change
player(playerX, playerY)
enemy1(enemy1X, enemy1Y)
pygame.display.update()
I can reproduce the issue with your orignal code.
It's a matter of Indentation. You have to handle the events in the event loop not after the event loop.
Move the event handling in the event loop:
running = True
while running:
screen.fill((0, 0, 0))
screen.blit(background, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# INDENTATION
#-->|
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
elif event.key == pygame.K_RIGHT:
playerX_change = 0.1
elif event.key == pygame.K_SPACE:
if laser_state == 'ready':
laserX = playerX
fire_laser(laserX, laserY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
i have tried making bullet in pygame using this tutorial https://youtu.be/8wEYDLVrAB8 but i have failed to do so here is commented code ,
. if problem arise please leave a comment on it . thank you for helping .i have already asked it once in this website but it didnt work [![ this is current state when firing bullet][1]][1] . i am running it in pycharm
import pygame
import random
#module importing
pygame.init()
pygame.display.init()
#screen creation
screen = pygame.display.set_mode((800, 600))
bacground = pygame.image.load("background.png")
#player information
playerimg = pygame.image.load("spaceship.png")
playerX_change = 0
playerX = 360
playerY = 480
#enemy information
enemyimg = pygame.image.load("enemy.png")
enemyX = random.randint(0,736)
enemyY = random.randint(50,150)
enemyX_change = 4
enemyY_change = 40
#bullet information
bulletimg = pygame.image.load("enemy.png")
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 40
bullet_state = "ready"
#all three functions
def player(x, y):
screen.blit(playerimg, (x, y))
#enemy draw function
def enemy(x, y):
screen.blit(enemyimg, (x, y))
#bullet fire function
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletimg, (x + 16, y+10))
# drawing player on screen
# game loop
running = True
while running == True:
#stuff happening in game loop
screen.fill((200, 200, 0))
screen.blit(bacground,(0,0))
player(playerX, playerY)
enemy(enemyX, enemyY)
if bullet_state == "fire":
fire_bullet(playerX, bulletY)
bulletY -= bulletY_change
#detection of the keys pressed and consequences
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
player(playerX, playerY)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
fire_bullet(bulletX,bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
#player and enemy movement system
playerX += playerX_change
enemyX += enemyX_change
#enemy and player collision detection
if enemyX <= 0:
enemyX_change = 4
enemyY += enemyY_change
if enemyX>= 736:
enemyX_change = -4
enemyY += enemyY_change
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
#display update
pygame.display.update()
It is a matter of Indentation. You have to handle the events in the event loop instead of the application loop:
while running == True:
#stuff happening in game loop
screen.fill((200, 200, 0))
screen.blit(bacground,(0,0))
player(playerX, playerY)
enemy(enemyX, enemyY)
if bullet_state == "fire":
fire_bullet(playerX, bulletY)
bulletY -= bulletY_change
#detection of the keys pressed and consequences
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# INDENTATAION
#-->|
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
fire_bullet(bulletX,bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
import pygame, sys
pygame.init()
pygame.display.set_caption("test 1")
#main Variables
clock = pygame.time.Clock()
window_size = (700, 700)
screen = pygame.display.set_mode(window_size, 0, 32)
#player variables
playerx = 150
playery = -250
player_location = [playerx, playery]
player_image = pygame.image.load("player/player.png").convert_alpha()
player_rect = player_image.get_rect(center = (80,50))
#button variables
move_right = False
move_left = False
move_up = False
move_down = False
while True:
screen.fill((4, 124, 32))
screen.blit(player_image, player_location, player_rect)
if move_right == True:
playerx += 4
if move_left == True:
playerx -= 4
if move_up == True:
playery -= 4
if move_down == True:
playery += 4
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
move_right = True
if event.key == pygame.K_a:
move_left = True
if event.key == pygame.K_w:
move_up = True
if event.key == pygame.K_s:
move_down = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_d:
move_right = False
if event.key == pygame.K_a:
move_left = False
if event.key == pygame.K_w:
move_up = False
if event.key == pygame.K_s:
move_down = False
pygame.display.update()
clock.tick(120)
I cant get it to work. I pressed the button but it wont go up or down. It worked well when i used no rectangle for the player. I wanter so i can move the character up and down in the y axis also. I just started to learn how to use PyGame so please help me thanks.
As you move the player, you change the playerx and playery variables. However, the player id drawn to the position that is stored in player_location. You must update player_location before drawing the player:
while True:
screen.fill((4, 124, 32))
player_location = [playerx, playery]
screen.blit(player_image, player_location, player_rect)
# [...]
Note that you don't need player_location at all. Draw the player at [playerx, playery]:
while True:
screen.fill((4, 124, 32))
screen.blit(player_image, [playerx, playery], player_rect)
Okay so I started a project today where I created Space Invaders. The only I'm personally having issues with is the pause and unpause button. I'm using Python 3.7.4 and Pygame 1.9.6.
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bullet_Sound = mixer.Sound('laser.wav')
bullet_Sound.play()
# Get the current x coordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
So I don't know if I should have the pause button first or not.
I've tried:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
while running:
'''The rest of the code'''
Where the # Pausing is:
I've tried:
if event.key == pygame.K_p:
paused = not paused # for pause and unpausing
No 'u' key.
So I'm just lost on where I should put it at. So it would be nice with the help. I looked at question: pausing/ Unpausing in Pygame for help. So anything else let me know.
Here's a minimal, complete example of a ball moving. You can pause and unpause its movement by pressing P. You can change its speed using ←↑→↓. Pressing Spacebar will reset the speed.
import pygame
WIDTH = 640
HEIGHT = 480
FPS = 30
class Ball(pygame.sprite.Sprite):
"""Moving ball sprite"""
def __init__(self, color="white", size=20, speedx=-5, speedy=-5):
pygame.sprite.Sprite.__init__(self)
self.color = pygame.color.Color(color)
# instead of loading an image from file, draw a circle.
self.image = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, self.color, (size, size), size)
self.rect = self.image.get_rect()
# start ball in the middle of the screen
self.rect.x = WIDTH / 2 - self.rect.width / 2
self.rect.y = HEIGHT / 2 - self.rect.height / 2
self.speedx = speedx
self.speedy = speedy
self.size = size
def update(self):
# reverse direction if out of bounds
if not (0 < self.rect.x < WIDTH - self.size*2):
self.speedx *= -1
if not (0 < self.rect.y < HEIGHT - self.size*2):
self.speedy *= -1
# update position
self.rect.x += self.speedx
self.rect.y += self.speedy
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
ball = Ball()
balls = pygame.sprite.Group()
balls.add(ball)
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_p:
paused = not paused
elif event.key == pygame.K_UP:
ball.speedy += 5
elif event.key == pygame.K_DOWN:
ball.speedy -= 5
if event.key == pygame.K_RIGHT:
ball.speedx += 5
elif event.key == pygame.K_LEFT:
ball.speedx -= 5
elif event.key == pygame.K_SPACE:
# reset speed
ball.speedx = 2
ball.speedy = 0
# update game elements
if not paused:
pygame.display.set_caption('Running')
ball.update()
else:
pygame.display.set_caption('Paused')
# draw surface - fill background
window.fill(pygame.color.Color("grey"))
## draw sprites
balls.draw(window)
# show surface
pygame.display.update()
# limit frames
clock.tick(FPS)
pygame.quit()
Note that whilst paused, events are still being handled, so you can still adjust the speed. To change this behaviour, you'd need to discard specific events when paused is True.