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()
Related
I wrote a python game using pygame and pymunk, but the playground() section doesnt work. It supposed to show a static object, but it doesnt. I asked and it was supposed to interact with balls being dropped.
heres the code:
import pygame, sys
import pymunk
import pymunk.pygame_util
from pymunk.vec2d import Vec2d
size = (800, 600)
FPS = 120
space = pymunk.Space()
space.gravity = (0,250)
pygame.init()
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
class Ball:
global space
def __init__(self, pos):
self.body = pymunk.Body(1,1, body_type = pymunk.Body.DYNAMIC)
self.body.position = pos
self.radius = 60
self.shape = pymunk.Circle(self.body, self.radius)
space.add(self.body, self.shape)
# INDENTATION
#<--|
def draw(self):
x = int(self.body.position.x)
y = int(self.body.position.y)
pygame.draw.circle(screen, (255,0,0), (x,y), self.radius)
def playground():
body = pymunk.Body(1,1, body_type = pymunk.Body.STATIC)
balls = []
balls.append(Ball((400,0)))
balls.append(Ball((100,0)))
balls.append(Ball((600,100)))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
balls.append(Ball(event.pos))
# INDENTATION
#<------|
screen.fill((217,217,217))
for ball in balls:
ball.draw()
playground()
space.step(1/50)
pygame.display.update()
clock.tick(FPS)
Any solution?
Its for a school project so any help will greated.
Thanks.
You forgot to add the body into the space, that's why the balls kept on falling.
You also need to define the shape of the body which is a required argument in adding to space. Lastly, you need to draw into pygame screen the shape as previously defined.
def playground():
body = pymunk.Body(1,1, body_type = pymunk.Body.STATIC)
polygon_points = [(0,580),(800,580),(800,600),(0,600)]
shape = pymunk.Poly(space.static_body, polygon_points)
space.add(body, shape)
pygame.draw.polygon(screen, (0, 0, 0), polygon_points)
I have been trying to make a little game using Pygame. This is my first time using Pygame and I have looked at many tutorials, but my sprite still won't appear. It only shows a black line. How can I fix it?
Xcord = 0
grey = (192,192,192)
import pygame, random, time
pygame.init()
import time
Color_line=(0,0,0)
screen = pygame.display.set_mode([1000, 500])
all_sprites_list = pygame.sprite.Group()
import pygame
grey = (192,192,192)
playerWidth = 50
playerHeight = 50
all_sprites_list = pygame.sprite.Group()
class Player(pygame.sprite.Sprite):
def __init__(self, grey, playerWidth, playerHeight):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([50, 50])
self.image.fill(grey)
self.image.set_colorkey(grey)
pygame.draw.rect(self.image, grey, [0, 0, playerWidth, playerHeight])
self.rect = self.image.get_rect()
player = Player(grey, 50, 50)
player.rect.x = Xcord
player.rect.y = 400
def update(Player):
pygame.sprite.Sprite.update(Player)
player.rect.x = Xcord
player.rect.y = 400
all_sprites_list.add(player)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255))
all_sprites_list.update()
pygame.draw.line(screen,Color_line,(0,500),(1000,500), 75)
all_sprites_list.draw(screen)
pygame.display.flip()
Xcord =+ 50
if Xcord == 400:
Xcord == 0
pygame.quit()
I am kind of trying to make something similar to Google Chrome's no Wi-Fi dinosaur game.
You have a few mistakes.
First: you fill sprite with GRAY and you use set_key on GRAY, so the sprite is transparent and simply you can't see the sprite.
Second: the code runs very fast and the sprite leaves the window and you can't see the sprite.
Third: in the code if Xcord == 400: Xcord == 0, you need = 0 instead of == 0 - and this is why the sprite leaves the window and never go back to position (0, 400)
Another problem is the big mess in the code - you even run some code two times.
My version with many changes.
# PEP8: all imports at start.
# PEP8: every module on a separate line
import pygame
import random
import time
# --- constants --- # PEP8: `UPPER_CAS_NAMES`
GRAY = (192, 192, 192)
RED = (255, 0, 0)
# --- classes --- # PEP8: `CamelCaseName`
class Player(pygame.sprite.Sprite):
def __init__(self, color, x, y, width, weight): # you don't need prefix `player` in variables in class `Player`
super().__init__() # Python 3 method for running a function from the original class
self.color = color
self.image = pygame.Surface([width, weight])
self.image.fill(color)
#self.image.set_colorkey(color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
self.rect.x += 5
if self.rect.x >= 400:
self.rect.x = 0
# --- main ---
color_line = (0,0,0) # PEP8: spaces around `=`, space after `,`
pygame.init()
screen = pygame.display.set_mode([1000, 500])
all_sprites_list = pygame.sprite.Group()
player_width = 50
player_weight = 50
player = Player(RED, 50, 400, 50, 50) # color, x, y, width, height
all_sprites_list.add(player)
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# - only updates -
all_sprites_list.update()
# - only draws -
screen.fill((255, 255, 255))
pygame.draw.line(screen, color_line, (0, 500), (1000, 500), 75)
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(30) # Slow down to 30 FPS (frames per seconds)
pygame.quit()
PEP 8 -- Style Guide for Python Code
So there you go, I wanted to experiment a little pygame but I find myself stuck.
Context
I created a small sprite (with Piskelapp) that represents the player and looks like:
player.png
then add my background in jpg format. However when launching the game, my sprite is cut by the background as follows:
The ship is not placed in front of the background and more I go up it, more it disappears behind the background...
Here is my code:
import pygame
pygame.init()
# class user
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.pv = 100
self.__max_health = 100
self.attack = 2
self.velocity = 5
self.image = pygame.image.load('assets/player.png')
self.rect = self.image.get_rect()
self.rect.x = 400
self.rect.y = 500
# open game window
pygame.display.set_caption("Rocket 'n' Rock")
screen = pygame.display.set_mode((1080, 720))
# background import
bg = pygame.image.load('assets/bg.jpg')
# load player
player = Player()
running = True
# game mainloop
while running:
# bg apply
screen.blit(bg, (0,-400))
# screen update
pygame.display.flip()
# player image apply
screen.blit(player.image, player.rect)
# if player close the window
for event in pygame.event.get():
# *close event
if event.type == pygame.QUIT:
running = False
pygame.quit()
print("close game")
anyone have a tip? I'm wondering if it's not a file format problem?
thank you for your time
In you game mainloop, you should put:
screen.blit(player.image, player.rect)
before:
pygame.display.flip()
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 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()