I have written simple code to get a green block which is my sprite to scroll across the screen. When the game starts the sprite is meant to appear in the centre of the screen, however when I run my code the screen is just black and the green block does not appear unless I click on the x cross on the window to exit the screen, then it appears for a second when the window is closing. Any ideas how I can resolve this.
import pygame, random
WIDTH = 800 #Size of window
HEIGHT = 600 #size of window
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
class Player(pygame.sprite.Sprite):
#sprite for the player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH/2, HEIGHT/2)
def update(self):
self.rect.x += 5
#initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
#Game loop
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
#check for closing window
if event.type == pygame.QUIT:
running = False
#update
all_sprites.update()
#Render/Draw
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
All your code to updat the sprites, fill the screens and draw the sprites is outside your main loop (while running)
You must have in mind that identation Python's syntax: your commands are just outside your mainloop.
Moreover, I'd strongly advise to put that mainloop inside a proper function, instead of just leaving it on the module root.
...
#Game loop
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
#check for closing window
if event.type == pygame.QUIT:
running = False
#update
all_sprites.update()
#Render/Draw
screen.fill(BLACK)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
Related
import pygame as pygame , sys,time
pygame.init()
size = (700,500)
window_game = pygame.display.set_mode(size)
_run_ = True
white = (255,255,255)
mouse_pos = pygame.mouse.get_pos()
class mySprite(pygame.sprite.Sprite):
def __init__ (self,cord_x,cord_y,picture,colorkey):
super().__init__()
self.image = pygame.Surface([0,0])
self.image = pygame.image.load(picture)
self.image.set_colorkey(colorkey)
self.rect = self.image.get_rect()
self.rect.center = [cord_x,cord_y]
self.kill()
placeSP_group = pygame.sprite.Group()
Clock = pygame.time.Clock()
FPS = 500
while _run_:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.QUIT
sys.exit()
mouse_pos = pygame.mouse.get_pos()
placeSP = [mySprite(mouse_pos[0],mouse_pos[1],'sp_1.png',white)]
pygame.display.flip()
placeSP_group.draw(window_game)
placeSP_group.add(placeSP[:])
Clock.tick(FPS)
now i want that my sprite get's killed and get the new mouse position
and window_game.fill('black')
dosen't work is there any thing you can do to fix it pls tell me...
what i wan't is every time my mouse moves i wan't kill the last sprite and create the other one with the current sprite pos.
You use kill() in wrong moment.
kill() works when Sprite is inside Group but you first create Sprite which try to use kill() and later you add this sprite to Group.
You should first create Sprite, next add to Group and later run kill() for first Sprite in Group
placeSP_group.sprites()[0].kill()
but normal Group doesn't have to keep sprites in order and better use
placeSP_group = pygame.sprite.OrderedUpdates()
Full working code. It display 5 sprites which follow mouse.
import pygame
import sys
# --- constants --- # PEP8: `UPPER_CASE_NAMES` for constants
WHITE = (255, 255, 255) # PE8: space after `,`
SIZE = (700, 500)
FPS = 50 # there is no need to use `500` because Python can't run so fast,
# and monitors runs with 60Hz (eventually 120Hz) which can display 60 FPS (120 FPS)
# --- classes --- # PEP8: `CamelCaseNames` for classes
class MySprite(pygame.sprite.Sprite):
def __init__(self, x, y, picture, colorkey):
super().__init__()
# you need one of them
# load image
#self.image = pygame.image.load(picture)
# OR
# create surface
self.image = pygame.Surface((10, 10))
self.image.fill((255, 0, 0))
# ----
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.image.set_colorkey(colorkey)
# --- main ---
pygame.init()
window_game = pygame.display.set_mode(SIZE)
#placeSP_group = pygame.sprite.Group()
placeSP_group = pygame.sprite.OrderedUpdates() # Group which keep order
sprite1 = MySprite(0, 0, 'sp_1.png', WHITE)
sprite2 = MySprite(0, 0, 'sp_1.png', WHITE)
sprite3 = MySprite(0, 0, 'sp_1.png', WHITE)
sprite4 = MySprite(0, 0, 'sp_1.png', WHITE)
sprite5 = MySprite(0, 0, 'sp_1.png', WHITE)
placeSP_group.add([sprite1, sprite2, sprite3, sprite4, sprite5])
clock = pygame.time.Clock() # PEP8: `lower_case_names` for variables
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
#running = False
pygame.quit()
exit()
# create new Sprite
x, y = pygame.mouse.get_pos()
new_sprite = MySprite(x, y, 'sp_1.png', WHITE)
# add new Sprite at the end of OrderedUpdates()
placeSP_group.add([new_sprite])
# remove Sprite at the beginning of OrderedUpdates()
placeSP_group.sprites()[0].kill()
# ---
pygame.display.flip()
window_game.fill('black')
placeSP_group.draw(window_game)
clock.tick(FPS)
I'm working on this pygame game and i'm just getting started but got a bit confused because i want the image to move in the x-axis along with the mouse but when i run the program i want the image to show up at the center or the 'floor' but appears at the left side instead. This is my code and a screenshot of what's happening.
import pygame
import sys
pygame.init()
pygame.mixer.init()
WIDTH, HEIGHT = 400, 500
FPS = 60
TITLE = 'FOOD DROP'
SIZE = 190
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE_SKY = (152, 166, 255)
# Display
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
# Surfaces
floor_surface = pygame.Surface((WIDTH, 100))
floor_surface.fill(BLUE_SKY)
floor_rect = floor_surface.get_rect(midbottom=(200, 500))
# Images
LOAD_DITTO = pygame.image.load('Graphics/ditto.png')
DITTO = pygame.transform.scale(LOAD_DITTO, (SIZE, SIZE))
# Time
CLOCK = pygame.time.Clock()
class Figure:
def draw_figure(self, mouse_x):
SCREEN.blit(DITTO, (mouse_x - 90, 330))
# Game loop
SCREEN_UPDATE = pygame.USEREVENT
# main_game = Main()
figure = Figure()
running = True
while running:
CLOCK.tick(FPS)
mx, my = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
SCREEN.fill(WHITE)
SCREEN.blit(floor_surface, floor_rect)
figure.draw_figure(mx)
pygame.display.update()
When i run the program, this happens:
And i want the image to appear right at the center or the x-axis, not the border, i don't know why is this happening. Just to state, that screenshot was taken when the mouse hadn't been placed over the display.
If the mouse pointer is not in the window (out of focus), the initial position of the mouse pointer is (0, 0). Therefore pygame.mouse.get_pos returns (0, 0). It is also not possible to set the mouse position with pygame.mouse.set_pos if it is not in the window.
Initialize the variables mx and mx with the center of the window. Change the mouse position only when the mouse pointer is in the window (in focus). pygame.mouse.get_focused can be used to test whether the mouse is in the window.
mx, my = SCREEN.get_rect().center
running = True
while running:
CLOCK.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if pygame.mouse.get_focused():
mx, my = pygame.mouse.get_pos()
SCREEN.fill(WHITE)
SCREEN.blit(floor_surface, floor_rect)
figure.draw_figure(mx)
pygame.display.update()
pygame.quit()
sys.exit()
I've got an issue where pygame is only rendering ablack screen with a strange glitchy green line on it.
I'm following a tutorial on RealPython.com and everything went smoothly with the first attempt. Once I did the second attempt this is what renders, which is clearly wrong.
#sidescrolling air-shooter
import pygame
#import pygame locals
from pygame.locals import(
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,
)
#constants for screen width/height
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player, self).__init__()
self.surf = pygame.Surface((75,25))
self.surf.fill((255, 255,255))
self.rect = self.surf.get_rect()
pygame.init()
#create screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Instantiate player
player = Player()
#keep the game running!
running = True
#loop time!
while running:
#look at all the events
for event in pygame.event.get():
#did the user hit a key?
if event.type == KEYDOWN:
#Was it escape? uh oh we gotta stop
if event.key == K_ESCAPE:
running = False
elif event.type ==QUIT:
running = False
#fill screen with white
screen.fill((255, 255, 255))
# Create a surface and pass in a tuple containing legth and width
surf = pygame.Surface((50, 50))
# Give the surface a color to separate it from the Background
surf.fill((0, 0, 0))
rect = surf.get_rect()
#This line says "Draw surf onto the screen at the center"
screen.blit(surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
#Draw the player on the screen
screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
pygame.display.flip()
pygame.quit()
I've even checked the source code for their project and it seems to match up.
It is a matter of Indentation. You need to draw the scene and update the display in the application loop instead of after the application loop:
#loop time!
while running:
#look at all the events
for event in pygame.event.get():
#did the user hit a key?
if event.type == KEYDOWN:
#Was it escape? uh oh we gotta stop
if event.key == K_ESCAPE:
running = False
elif event.type ==QUIT:
running = False
#-->| INDENTATION
#fill screen with white
screen.fill((255, 255, 255))
# Create a surface and pass in a tuple containing legth and width
surf = pygame.Surface((50, 50))
# Give the surface a color to separate it from the Background
surf.fill((0, 0, 0))
rect = surf.get_rect()
#This line says "Draw surf onto the screen at the center"
screen.blit(surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
#Draw the player on the screen
screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
pygame.display.flip()
pygame.quit()
I am learning pygame by making a simple game.
Here is the code:
Main script:
import pygame
from gracz2 import SpriteGenerator
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
pygame.init()
pygame.display.set_caption("Super Gra!")
screen_height = 720
screen_width = 1280
screen = pygame.display.set_mode((screen_width, screen_height))
all_sprites_list = pygame.sprite.Group()
playerSprite = SpriteGenerator(1,150,150)
playerSprite.rect.x = (screen_width/2 - 75)
playerSprite.rect.y = 550
all_sprites_list.add(playerSprite)
clock = pygame.time.Clock()
mainloop = True
playtime = 0
while mainloop:
for event in pygame.event.get():
# User presses QUIT-button.
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
# User presses ESCAPE-Key
if event.key == pygame.K_ESCAPE:
mainloop = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
playerSprite.moveLeft(8)
if keys[pygame.K_RIGHT]:
playerSprite.moveRight(8)
milliseconds = clock.tick(60)
playtime += milliseconds / 1000.0
all_sprites_list.update()
pygame.display.set_caption("Czas gry: " + str(round(playtime,1)) + " sekund")
# Refresh the screen
screen.fill(BLACK)
all_sprites_list.draw(screen)
screen.blit(playerSprite.image, (playerSprite.rect.x,playerSprite.rect.y))
pygame.display.flip()
print(all_sprites_list.sprites())
print(all_sprites_list)
print(playerSprite.rect.x)
print(playerSprite.rect.y)
pygame.quit()
and another file called "gracz2.py":
import pygame
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
class SpriteGenerator(pygame.sprite.Sprite):
#This class represents a player. It derives from the "Sprite" class in Pygame.
def __init__(self, type, width, height):
# Call the parent class (Sprite) constructor
super().__init__()
# Pass in the color of the player, and its x and y position, width and height.
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
if type == 1:
self.image = pygame.image.load("sprite-ufo.gif").convert_alpha()
elif type == 2:
self.image = pygame.image.load("sprite-bomb.jpg").convert_alpha()
# Fetch the rectangle object that has the dimensions of the image.
self.rect = self.image.get_rect()
def moveRight(self, pixels):
self.rect.x += pixels
def moveLeft(self, pixels):
self.rect.x -= pixels
It could be done in one file but the code is more readable for me this way.
around line 50 i call all_sprites_list.draw(screen)
which to my understanding should blit all the sprites contained in all_sprites_list but it does nothing.
I have to use screen.blit(playerSprite.image, (playerSprite.rect.x,playerSprite.rect.y))
to manually blit the sprite.
As i am going to add generate lots of sprites later i can't blit them all manually.
Why doesn't all_sprites_list.draw(screen) work as intended?
It's probably a stupid mistake in the code but I am trying to find for over an hour now and I am unable to locate it.
Turns out that when i restart my PC the draw() function works fine.
I don't know what caused it first, sorry for asking without following the first rule of IT troubleshooting first (restart and try again)
PS: thank you furas for your answers
I'm not sure what I am doing wrong here. There are no errors appearing but when the game loads nothing appears, just the black background. This is the code that I am running for loading my sprite into the game.
import pygame
import sys
import os
pygame.init()
"""
Spawn Player
"""
class Player(pygame.sprite.Sprite):
pygame.display.set_mode()
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.images = []
img = pygame.image.load(os.path.join("images", "ninja.jpeg")).convert()
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
def Run(self):
pygame.sprite.Sprite.__init__(self)
self.images = []
for i in range(1,5):
run_img = pygame.image.load(os.path.join("run","ninja_run" + str(i) + ".jpeg")).convert()
self.images.append(run_img)
self.image = self.images[0]
self.rect = self.image.get_rect()
"""
Setup
"""
worldx = 900
worldy = 700
fps = 40
ani = 4
clock = pygame.time.Clock()
world = pygame.display.set_mode([worldx, worldy])
player = Player()
player.rect.x = 32
player.rect.y = 32
player_list = pygame.sprite.Group()
player_list.add(player)
BLUE = (25, 25, 200)
BLACK = (20, 20, 20)
WHITE = (255, 255, 255)
RED = (200, 25, 25)
"""
Main Loop
"""
main = True
while main:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
break
#world.blit(backdrop, backdrop_box)
player_list.draw(world)
world.fill(BLACK)
pygame.display.flip()
clock.tick(fps)
I had a friend look over the code and he said there is a problem with the init under the player class but aside from that I really do not understand where the problem within the code is.
The window is calling properly and I'm getting the background as black but the sprite simply will not load.
I'm working with this tutorial here to get the sprites to show up. I already have the movement among other parts setup the only thing that doesn't seem to be working is the code revolving around the sprites.
Any help here would be great.
You do world.fill(BLACK) immediately for pygame.display.flip().
world.fill(BLACK) fills the entire window surface in black and covers everything which was drawn before. pygame.display.flip() updates the window. This causes that the window is appears completely black.
Change the order of the instructions to solve the issue:
world.fill(BLACK)
player_list.draw(world)
# world.fill(BLACK) <---- delete
pygame.display.flip()