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()
Related
I just start learning pygame, the problem is : the game character that I'm making is moving when mouse is moving in screen even though I don't need to use mouse and I need help with it.
I added some code for bullets this part is not important for me now because the space ship is not moving without moving mouse in screen .
import pygame
from pygame.locals import*
#define fps
clock = pygame.time.Clock()
fps=60
screen_width = 600
screen_height = 800
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption(' space invaders')
#colors
red=(255,0,0)
green=(0,255,0)
#load image
bg = pygame.image.load("img/bg.png")
def draw_bg():
screen.blit(bg,(0,0))
#create spaceship class
class Spaceship(pygame.sprite.Sprite):
def __init__(self,x,y,health):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("img/spaceship.png")
self.rect = self.image.get_rect()
self.rect.center = [x, y]
self.health_start = health
self.health_remaining = health
self.last_shot = pygame.time.get_ticks()
def update(self):
#set movement speed
speed=8
#get key press
key=pygame.key.get_pressed()
if key[pygame.K_LEFT] and self.rect.left>0:
self.rect.x-=speed
if key[pygame.K_RIGHT] and self.rect.right<screen_width:
self.rect.x+=speed
time_now=pygame.time.get_ticks()
#shoot
if key[pygame.K_SPACE]:
bullet = Bullet(self.rect.centerx,self.rect.top)
bullet_group.add(bullet)
pygame.mouse.get_pos()
#draw health bar
pygame.draw.rect(screen,red,(self.rect.x,(self.rect.bottom+10),self.rect.width,15))
if self.health_remaining>0:
pygame.draw.rect(screen,green,(self.rect.x,(self.rect.bottom+10),int(self.rect.width*(self.health_remaining / self.health_start)),15))
#create Bullets class
class Bullets(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load("img/bullet.png")
self.rect = self.image.get_rect()
self.rect.center=[x,y]
def update(self):
self.rect.y-=5
# sprite groups
spaceship_group = pygame.sprite.Group()
bullet_group=pygame.sprite.Group()
#create player
spaceship=Spaceship(int(screen_width / 2),screen_height-100 ,3)
spaceship_group.add(spaceship)
run = True
while run:
clock.tick(fps)
draw_bg()
#events
for event in pygame.event.get():
if event.type==pygame.QUIT:
run=False
#update spaceship
spaceship.update()
update bullets
bullet_group.update()
spaceship_group.draw(screen)
bullet_group.draw(screen)
pygame.display.update()
pygame.quit
Looks like an indentation problem.
When your code is indented inside the for event in pygame.event.get() loop, it only runs when pygame receives events. You notice this through MOUSEMOTION events.
run = True
while run:
clock.tick(fps)
draw_bg()
#events
for event in pygame.event.get():
if event.type==pygame.QUIT:
run=False
# <---- moved this one indentation level, out of the evnet loop
#update spaceship
spaceship.update()
#update bullets
bullet_group.update()
spaceship_group.draw(screen)
bullet_group.draw(screen)
pygame.display.update()
I've tried everything to fix this, my code runs and a screen is shown but the image is not on the screen.
so far I've tried:
putting an absolute path when entering the image in pygame.image.load
trying os.join.path method (file cannot be found error)
And loads of other things
-How after trying everything, and closely following the book, i cant get it to work?
my code from alien_invasion.py:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
def __init__(self):
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.bg_color = (255, 0, 0)
self.ship = Ship(self)
def run_game(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.screen.fill(self.settings.bg_color)
pygame.display.flip()
self.screen.fill(self.bg_color)
self.ship.blitme()
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
code from ship.py:
import pygame
class Ship:
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
self.image = pygame.image.load('C:/Users/Documents/Python Learning/python crash course lessons/Alien Invasion/ship1.bmp')
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
self.screen.blit(self.image, self.rect)
code from settings.py
class Settings:
"""A class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's settings."""
# Screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
I really want to find the solution to this otherwise I will remain stuck since none of the solutions to other people with the same problem has solved my problem...
the program works, there are no errors shown the image just doesn't load to the image to the screen.
thank you if you helped
The image is not shown, because the display is not updated after drawing the image. Update the display after drawing the ship:
class AlienInvasion:
# [...]
def run_game(self):
clock = pygame.time.Clock()
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
self.screen.fill(self.bg_color)
self.ship.blitme()
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
limit frames per second to limit CPU usage with pygame.time.Clock.tick
Okay, so basically what I'm trying to do is keep the main file a little cleaner and I'm starting with the "Zombie" enemy by making it's own file which will most likely contain all enemies, and importing it in.
So I'm confused on how I'd set-up the Class for a sprite, you don't have to tell me how to get it to move or anything like that I just want it to simply appear. The game doensn't break when I run it as is, I just wanted to ask this question before I goto sleep so I can hopefully get a lot done with the project done tomorrow (School related)
Code is unfinished like I said just wanted to ask while I get some actual sleep just a few google searches and attempts.
Eventually I'll take from the advice given here to make a "Hero" class as well, and as well as working with importing other factors if we have the time.
Zombie code:
import pygame
from pygame.locals import *
class ZombieEnemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('images/zombie.png')
# self.images.append(img)
# self.image = self.images[0]
self.rect = self.image.get_rect()
zombieX = 100
zombieY = 340
zombieX_change = 0
Main Code:
import pygame
from pygame.locals import *
import Zombie
# Intialize the pygame
pygame.init()
# Create the screen
screen = pygame.display.set_mode((900, 567))
#Title and Icon
pygame.display.set_caption("Fighting Game")
# Add's logo to the window
# icon = pygame.image.load('')
# pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('images/character.png')
playerX = 100
playerY = 340
playerX_change = 0
def player(x,y):
screen.blit(playerImg,(x,y))
Zombie.ZombieEnemy()
def zombie(x,y):
screen.blit()
# Background
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load('images/background.png')
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
BackGround = Background('background.png', [0,0])
# Game Loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If keystroke is pressed check right, left.
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
#playerX_change = -2.0
BackGround.rect.left = BackGround.rect.left + 2.5
if event.key == pygame.K_RIGHT:
#playerX_change = 2.0
BackGround.rect.left = BackGround.rect.left - 2.5
# if event.type == pygame.KEYUP:
# if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
# BackGround.rect.left = 0
screen.blit(BackGround.image, BackGround.rect)
playerX += playerX_change
player(playerX,playerY)
pygame.display.flip()
Your sprite code is basically mostly there already. But as you say, it needs an update() function to move the sprites somehow.
The idea with Sprites in PyGame is to add them to a SpriteGroup, then use the group functionality for handling the sprites together.
You might want to modify the Zombie class to take an initial co-ordinate location:
class ZombieEnemy(pygame.sprite.Sprite):
def __init__( self, x=0, y=0 ):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('images/zombie.png')
self.rect = self.image.get_rect()
self.rect.center = ( x, y ) # NOTE: centred on the co-ords
Which allows the game to create a Zombie at a particular starting point (perhaps even a random one).
So to have a sprite group, first you need to create the container:
all_zombies = pygame.sprite.Group()
Then when you create a new zombie, add it to the group. Say you wanted to start with 3 randomly-positioned zombies:
for i in range( 3 ):
new_x = random.randrange( 0, WINDOW_WIDTH ) # random x-position
new_y = random.randrange( 0, WINDOW_HEIGHT ) # random y-position
all_zombies.add( Zombie( new_x, new_y ) ) # create, and add to group
Then in the main loop, call .update() and .draw() on the sprite group. This will move and paint all sprites added to the group. In this way, you may have separate groups of enemies, bullets, background-items, etc. The sprite groups allow easy drawing and collision detection between other groups. Think of colliding a hundred bullets against a thousand enemies!
while running:
for event in pygame.event.get():
# ... handle events
# Move anything that needs to
all_zombies.update() # call the update() of all zombie sprites
playerX += playerX_change
# Draw everything
screen.blit(BackGround.image, BackGround.rect)
player(playerX,playerY)
all_zombies.draw( screen ) # paint every sprite in the group
pygame.display.flip()
EDIT: Added screen parameter to all_zombies.draw()
It's probably worthwhile defining your player as a sprite too, and having a single-entry group for it as well.
First you could keep position in Rect() in class. And you would add method which draws/blits it.
import pygame
class ZombieEnemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load('images/zombie.png')
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = 340
self.x_change = 0
def draw(self, screen):
screen.blit(self.image, self.rect)
Next you have to assign to variable when you create it
zombie = Zombie.ZombieEnemy()
And then you can use it to draw it
zombie.draw(screen)
in
screen.blit(BackGround.image, BackGround.rect)
player(playerX,playerY)
zombie.draw(screen)
pygame.display.flip()
The same way you can create class Player and add method draw() to class Background and then use .
background.draw(screen)
player.draw(screen)
zombie.draw(screen)
pygame.display.flip()
Later you can use pygame.sprite.Group() to keep all objects in one group and draw all of them using one command - group.draw()
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()
I am attempting to use pygame to draw a map to a screen, but cannot understand why it won't. I'm not getting a traceback. The screen is initializing, then the image is not being drawn. I've attempted with other .bmp images with the same result, so there must be something in my code that is not ordered/written correctly.
Here is the main module of the game:
import pygame
import sys
from board import Board
def run_game():
#Launch the screen.
screen_size = (1200, 700)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('Horde')
#Draw the board.
game_board = Board(screen)
game_board.blit_board()
#Body of the game.
flag = True
while flag == True:
game_board.update_board()
run_game()
Here is the board module that you see being used. Specifically, the blit_board() function, which is silently failing to draw the map.bmp file I ask it to (file is in the same directory).
import pygame
import sys
class Board():
def __init__(self, screen):
"""Initialize the board and set its starting position"""
self.screen = screen
#Load the board image and get its rect.
self.image = pygame.image.load('coll.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#Start the board image at the center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.centery = self.screen_rect.centery
def blit_board(self):
"""Draw the board on the screen."""
self.screen.blit(self.image, self.rect)
def update_board(self):
"""Updates the map, however and whenever needed."""
#Listens for the user to click the 'x' to exit.
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
#Re-draws the map.
self.blit_board()
All I get is a black screen. Why will the map.bmp image not draw?
As Dan MaĊĦek stated you need to tell PyGame to update the display after drawing the image.
To achieve this simply modify your 'board' loop to the following:
def update_board(self):
"""Updates the map, however and whenever needed."""
#Listens for the user to click the 'x' to exit.
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
#Re-draws the map.
self.blit_board()
pygame.display.update()