the player is shaking when walking [duplicate] - python

So I run the code and it just starts glitching out. I am new to pygame.
Here is the code:
import pygame
pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((1000, 1000))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480
def player(x, y):
# Blit means Draw
screen.blit(playerimg, (x, y))
# Game loop (Put all code for pygame in this loop)
while running:
screen.fill((225, 0, 0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether is right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("Left arrow is pressed")
if event.key == pygame.K_RIGHT:
print("Right key has been pressed")
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
print("kEYSTROKE RELEASED")
# RGB (screen.fill) = red green blue
player(playerX, playerY)
pygame.display.update()
The image is not the glitching one as I was not able to post a video but it is what my code does

The problem is caused by multiple calls to pygame.display.update(). An update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.
Remove all calls to pygame.display.update() from your code, but call it once at the end of the application loop:
while running:
screen.fill((225, 0, 0))
# pygame.display.update() <---- DELETE
# [...]
player(playerX, playerY)
pygame.display.update()
If you update the display after screen.fill(), the display will be shown filled with the background color for a short moment. Then the player is drawn (blit) and the display is shown with the player on top of the background.

Related

player img wont load onto the window in pygame. Theres no error whatsoever though I just cant see the img on screen [duplicate]

This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
I was wondering why my playerIMG wont load in pygame
(2 answers)
How can I make a sprite move when key is held down
(6 answers)
Closed 7 months ago.
Here is my code below this is my first pygame project any help will be appreciated! I think its something to do with the
def player(playerX,playerY):
pygame.display.update()
block of code. Though when I play around with it sometimes it won't even display my background object and only displays the screen filler black.
#initializing the game
pygame.init()
FPS = 60
black = (0,0,0)
white = (255,255,255)
#creating the screen and setting the size
gameDisplay = pygame.display.set_mode((800,600))
#setting the title of the window
pygame.display.set_caption('Space Crashers')
#going into our files and loading the image for the background
background = pygame.image.load(r'C:\\Users\\ahmad\\Downloads\\pygame projects\\Assets\\newBackground.jpg')
#player image and model
playerImg = pygame.image.load(r'C:\\Users\\ahmad\\Downloads\\pygame projects\\Assets\\blueShip.png')
#these cords are for the player ship to be in the middle of the screen
playerX = 370
playerY = 480
#creating player function
def player(x,y):
gameDisplay.blit(playerImg, (x,y))
# window creation
clock = pygame.time.Clock()
running = True
while running:
#setting the background to black
gameDisplay.fill(black)
#then changing the background to the image we loaded
gameDisplay.blit(background,(0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
# if the keystroke is pressed, the player will move
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX -= .01
if event.key == pygame.K_RIGHT:
playerX += .01
if event.key == pygame.K_UP:
playerY -= .01
if event.key == pygame.K_DOWN:
playerY += .01
def player(playerX,playerY):
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
In your game loop you should normally
fill your screen black
draw and blit everything to the screen
update the screen
catch the events
let the clock tick
You didn't call the player() function in your loop to draw the player image neither the clock.tick() function. You don't need to overwrite the player function. Also if ran without any arguments, you should only have one event loop, otherwise some events could be ignored.
pygame.init()
FPS = 60
black = (0, 0, 0)
white = (255, 255, 255)
# window
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Space Crashers')
# background image
background = pygame.image.load(r'C:\\Users\\ahmad\\Downloads\\pygame projects\\Assets\\newBackground.jpg')
# player image
playerImg = pygame.image.load(r'C:\\Users\\ahmad\\Downloads\\pygame projects\\Assets\\blueShip.png')
# these coords are for the player ship to be in the middle of the screen
playerX = 370
playerY = 480
# draw player
def player(x, y):
gameDisplay.blit(playerImg, (x, y))
# window creation
clock = pygame.time.Clock()
running = True
while running:
# reset display
gameDisplay.fill(black)
# blit background
gameDisplay.blit(background, (0, 0))
### blit the player ###
player(playerX, playerY)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# move player
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX -= .01
if event.key == pygame.K_RIGHT:
playerX += .01
if event.key == pygame.K_UP:
playerY -= .01
if event.key == pygame.K_DOWN:
playerY += .01
pygame.display.update()
clock.tick(FPS)
pygame.quit()

Confused with movement in pygame

I am trying to make a small game in pygame. The player is the left hand red rectangle (if you run it) and I am just trying to make the rocket variable move to the left quickly. Whenever I run the program if I press any key or move my mouse it moves the rocket.
Here is the code:
import pygame,sys,random
pygame.init()
pygame.key.set_repeat(1, 100)
size=width,height=1280,830
screen = pygame.display.set_mode(size)
black = [0, 0, 0]
white = [255, 255, 255]
sky_blue = ((0,255,255))
red = ((255,0,0))
font = pygame.font.SysFont("Arial",14)
rocket=pygame.Rect(1200,350,150,50)
player= pygame.Rect(250,350,250,50)
hull=100
player_speed=100
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type==pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player_speed=player_speed+100
if event.key == pygame.K_LEFT:
player_speed=player_speed-100
if event.key == pygame.K_UP:
player.top=player.top-50
if event.key == pygame.K_DOWN:
player.top=player.top+50
if player_speed>1000:
player_speed=1000
if player_speed<100:
player_speed=100
if player.top<0:
player.top=0
elif player.bottom>height:
player.bottom=height
#rocket code
if player.colliderect(rocket):
hull=hull-100
if player_speed>99:
rocket.right=rocket.right-5
screen.fill(sky_blue)
pygame.draw.rect(screen,red,player)
pygame.draw.rect(screen,red,rocket)
renderedText = font.render("Speed: "+str(player_speed),1,black)
screen.blit(renderedText, (width/2+50,10))
if hull<1:
renderedText = font.render("GAME OVER",1,black)
screen.blit(renderedText, (width/2+500,500))
pygame.display.flip()
pygame.time.wait(10)
You indentation is incorrect which is causing a logic error.
if player_speed>1000:
...
rocket.right=rocket.right-5
The code between these lines need to be one indent lower. Else this code will only be run when there is a event. Since the for loop will skip execution of any code within if there is no events.

Screen only updating when moving my mouse over it, is there something wrong with my code?

Here's the code:
# Initialize the pygame
pygame.init()
# Create the screen
screen = pygame.display.set_mode((800, 600))
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load("player.png")
playerX = 370
playerY = 480
def player(x, y):
screen.blit(playerImg, (x, y))
# Run game until x is pressed
running = True
while running:
for event in pygame.event.get():
screen.fill((0, 0, 0))
playerX += 0.1
print(playerX)
if event.type == pygame.QUIT:
running = False
pygame.display.quit()
sys.exit()
player(playerX, playerY)
pygame.display.update()
For some reason the screen only updates when i move my mouse over it or when i spam a button on my keyboard. I don't have any more details to add so i have to type this otherwise i can't post my question.
Fix your indents. You only need to check event type in the event loop. The draw code is under the while loop.
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.quit()
sys.exit()
screen.fill((0, 0, 0))
playerX += 0.1
print(playerX)
player(playerX, playerY)
pygame.display.update()
It's a matter of Indentation. You have to update the screen application loop rather than the event loop:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#<--| INDENTATION
screen.fill((0, 0, 0))
playerX += 0.1
print(playerX)
player(playerX, playerY)
pygame.dispaly.flip()

Continuous movement of a box in pygame

I have written the following code that creates a simple game where when you click an arrow on the keyboard a box moves a unit over in the game.
I am trying to make it so that if i push any of the arrow buttons the box will continue to move in that direction until another arrow is pushed. So if i push the right arrow once instead of scooting +50 pixels it will move continuously across the screen untill a different arrow is clicked and then it will go that way
import pygame #importing the pygame library
# some initializations
pygame.init() # this line initializes pygame
window = pygame.display.set_mode( (800,600) ) # Create a window with width=800 and height=600
pygame.display.set_caption( 'Rectangle move' ) # Change the window's name we create to "Rectangle move"
clock = pygame.time.Clock() # Clocks are used to track and control the frame-rate of a game (how fast and how slow the pace of the game)
# This line creates and initializes a clock.
# color definitions, using RBG color model.
black = (0,0,0)
white = (255,255,255)
# initial center position for the square (bob)
x,y = 0,0
lastKey=0
game_loop=True
while game_loop:
for event in pygame.event.get(): # loop through all events
if event.type == pygame.QUIT:
game_loop = False # change the game_loop boolean to False to quit.
if event.type == pygame.KEYDOWN:
lastKey = event.key
#check last entered key
#lastKey equals "LEFT", "RIGHT", "UP", "DOWN" --> do the required stuff!
#set x coordinate minus 50 if left was pressed
if lastKey == pygame.K_LEFT:
x -= 50
if lastKey == pygame.K_RIGHT:
x += 50
if lastKey == pygame.K_UP:
y += 50
if lastKey == pygame.K_DOWN:
y -= 50
if event.key == pygame.K_LEFT:
x -= 50
if event.key == pygame.K_RIGHT:
x += 50
if event.key == pygame.K_UP:
y += 50
if event.key == pygame.K_DOWN:
y -= 50
# draw and update screen
window.fill( black ) # fill the screen with black overwriting even bob.
pygame.draw.rect( window, white, (x, y, 50, 50) ) # draw bob on the screen with new coordinates after its movement.
# the parameters are as follows: window: is the window object you want to draw on. white: the object color used to fill the rectangle
# (x,y,50,50) x is the x position of the left side of the rectangle. y is the y position of the upper side of the rectangle.
# In other words (x,y) is the coordinate of the top left point of the rectangle.
# 50 is the width, and 50 is the height
pygame.display.update() #updates the screen with the new drawing of the rectangle.
#fps stuff:
clock.tick(10) # this controls the speed of the game. low values makes the game slower, and large values makes the game faster.
pygame.quit()
any help would be much appreciated.
Try to save the entered key into a variable and check it after your Event-Loop.
Like this:
#...
lastKey = None
while game_loop:
for event in pygame.event.get(): # loop through all events
if event.type == pygame.QUIT:
game_loop = False # change the game_loop boolean to False to quit.
if event.type == pygame.KEYDOWN:
lastKey = event.key
#check last entered key
#lastKey equals "LEFT", "RIGHT", "UP", "DOWN" --> do the required stuff!
#set x coordinate minus 50 if left was pressed
if lastKey == pygame.K_LEFT
x -= 50
#<add the other statements here>
#(...)
I would recommend to not use that many if-statements. It could get a bit confusing after some time.
Check the following question out to keep your code brief:
Replacements for switch statement in Python?
You want to change the state of your application when you press a key. So you need a variable to keep track of that state (the state is: What direction should the box move?).
Here's a complete, minimal example that does what you're looking for. Note the comments.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
screen_r = screen.get_rect()
clock = pygame.time.Clock()
rect = pygame.rect.Rect(0, 0, 50, 50)
# let's start at the center of the screen
rect.center = screen_r.center
# a dict to map keys to a direction
movement = {pygame.K_UP: ( 0, -1),
pygame.K_DOWN: ( 0, 1),
pygame.K_LEFT: (-1, 0),
pygame.K_RIGHT: ( 1, 0)}
move = (0, 0)
# a simple helper function to apply some "speed" to your movement
def mul10(x):
return x * 10
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
sys.exit()
# try getting a direction from our dict
# if the key is not found, we don't change 'move'
if e.type == pygame.KEYDOWN:
move = movement.get(e.key, move)
# move the rect by using the 'move_ip' function
# but first, we multiply each value in 'move' with 10
rect.move_ip(map(mul10, move))
# ensure that 'rect' is always inside the screen
rect.clamp_ip(screen_r)
screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('White'), rect)
pygame.display.update()
clock.tick(60)
I use a Rect instead of keeping track of two coordinates x and y, since that allows to make use of the move_ip and clamp_ip functions to easily move the rect inside the screen.
Here are two versions, the first demonstrates how to utilize an event loop to get continuous movement (similar to Sloth's solution, but a bit simpler for beginners who don't know dictionaries yet), the second one shows how to achieve this with pygame.key.get_pressed().
Solution 1: Check which key was pressed in the event loop and change the x and y velocities to the desired values. Then add the velocities to the rect.x and rect.y positions in the while loop.
I'd actually recommend using vectors instead of the velocity_x and velocity_y variables and another one for the actual position of your sprite. pygame.Rects can't have floats as their coordinates and so a vector or separate variables for the position would be more accurate.
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(100, 200, 40, 60)
velocity_x = 0
velocity_y = 0
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_d:
velocity_x = 4
elif event.key == pg.K_a:
velocity_x = -4
elif event.type == pg.KEYUP:
if event.key == pg.K_d and velocity_x > 0:
velocity_x = 0
elif event.key == pg.K_a and velocity_x < 0:
velocity_x = 0
rect.x += velocity_x
rect.y += velocity_y
screen.fill((40, 40, 40))
pg.draw.rect(screen, (150, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
Solution 2: Call pygame.key.get_pressed to check which key is currently being held down. Check if the left, right, up or down keys are held and then adjust the position of the sprite each frame.
pygame.key.get_pressed has the disadvantage that you can't know the order of the key presses, but the code looks a bit simpler.
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(100, 200, 40, 60)
velocity = (0, 0)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
keys = pg.key.get_pressed()
if keys[pg.K_d]:
rect.x += 4
if keys[pg.K_a]:
rect.x -= 4
screen.fill((40, 40, 40))
pg.draw.rect(screen, (150, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()

Pygame how to "place" an image when you press a key

import pygame, random, time
class Game(object):
def main(self, screen):
bg = pygame.image.load('data/bg.png')
select = pygame.image.load('data/select.png')
block1 = pygame.image.load('data/enemy1.png')
clock = pygame.time.Clock()
while 1:
clock.tick(30)
spriteList = []
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
spriteList.append(block1, (0, 0))
mouse = pygame.mouse.get_pos()
print(mouse)
screen.fill((200, 200, 200))
screen.blit(bg, (0, 0))
screen.blit(select, (mouse))
for sprite in spriteList:
screen.blit(sprite[0], sprite[1])
pygame.display.flip()
if __name__ == '__main__':
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
pygame.init()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Sandbox')
Game().main(screen)
I'm trying to make it so where you move the mouse a box follows it. Then when you click the space key, "place" an image where you pressed space and then leave it there and be able to place another image somewhere else without effecting the first one. I tried using spriteList but I am kind of confused on where to go from here.
And when I run it I get an error saying: .append() takes one argument (2 given)
Add a tuple to your list. Also, store the mouse position, not (0, 0). Change
spriteList.append(block1, (0, 0))
to
spriteList.append((block1, mouse))
Also, you could rewrite
for sprite in spriteList:
screen.blit(sprite[0], sprite[1])
to
for (img, pos) in spriteList:
screen.blit(img, pos)

Categories