I am trying to display a game in pygame. But it won't work for some reason, any ideas? Here is my code:
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("My Game")
p = 1
green = (0,255,0)
pacman ="imgres.jpeg"
pacman_x = 0
pacman_y = 0
while True:
pacman_obj=pygame.image.load(pacman).convert()
screen.blit(pacman_obj, (pacman_x,pacman_y))
blue = (0,0,255)
screen.fill(blue)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
p=0
pygame.display.update()
Just a guess, as I haven't actually ran this:
Is the screen just showing up blue and you're missing the pacman image? What might be happening is that you are blitting pacman onto the screen, and then doing a screen.fill(blue), which is essentially overwriting your pacman image with blue. Try reversing these steps in your code (that is, filling the screen blue, then blitting pacman after).
if the screen shows up blue, it is because you need to "blit" the image after you do screen.fill
also, blue has to be defined at the top, and it should be in a different loop. here is how i would do it:
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("My Game")
p = 1
green = (0,255,0)
blue = (0,0,255)
pacman ="imgres.jpeg"
pacman_x = 0
pacman_y = 0
pacman_obj=pygame.image.load(pacman).convert()
done = False
clock=pygame.time.Clock()
while done==False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type==KEYDOWN:
if event.key==K_LEFT:
p=0
screen.fill(blue)
screen.blit(pacman_obj, (pacman_x,pacman_y))
pygame.display.flip()
clock.tick(100)
pygame.quit()
Note:
You are creating a new image every frame. This is slow.
Coordinates for blit can be Rect()s
Here's updated code.
WINDOW_TITLE = "hi world - draw image "
import pygame
from pygame.locals import *
from pygame.sprite import Sprite
import random
import os
class Pacman(Sprite):
"""basic pacman, deriving pygame.sprite.Sprite"""
def __init__(self, file=None):
"""create surface"""
Sprite.__init__(self)
# get main screen, save for later
self.screen = pygame.display.get_surface()
if file is None: file = os.path.join('data','pacman.jpg')
self.load(file)
def draw(self):
"""draw to screen"""
self.screen.blit(self.image, self.rect)
def load(self, filename):
"""load file"""
self.image = pygame.image.load(filename).convert_alpha()
self.rect = self.image.get_rect()
class Game(object):
"""game Main entry point. handles intialization of game and graphics, as well as game loop"""
done = False
color_bg = Color('seagreen') # or also: Color(50,50,50) , or: Color('#fefefe')
def __init__(self, width=800, height=600):
"""Initialize PyGame window.
variables:
width, height = screen width, height
screen = main video surface, to draw on
fps_max = framerate limit to the max fps
limit_fps = boolean toggles capping FPS, to share cpu, or let it run free.
color_bg = backround color, accepts many formats. see: pygame.Color() for details
"""
pygame.init()
# save w, h, and screen
self.width, self.height = width, height
self.screen = pygame.display.set_mode(( self.width, self.height ))
pygame.display.set_caption( WINDOW_TITLE )
# fps clock, limits max fps
self.clock = pygame.time.Clock()
self.limit_fps = True
self.fps_max = 40
self.pacman = Pacman()
def main_loop(self):
"""Game() main loop.
Normally goes like this:
1. player input
2. move stuff
3. draw stuff
"""
while not self.done:
# get input
self.handle_events()
# move stuff
self.update()
# draw stuff
self.draw()
# cap FPS if: limit_fps == True
if self.limit_fps: self.clock.tick( self.fps_max )
else: self.clock.tick()
def draw(self):
"""draw screen"""
# clear screen."
self.screen.fill( self.color_bg )
# draw code
self.pacman.draw()
# update / flip screen.
pygame.display.flip()
def update(self):
"""move guys."""
self.pacman.rect.left += 10
def handle_events(self):
"""handle events: keyboard, mouse, etc."""
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: self.done = True
# event: keydown
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
if __name__ == "__main__":
game = Game()
game.main_loop()
First you blit the image and then fill it with BLUE ,so it might show only blue screen ,
Solution: First fill screen blue and then blit it.
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("My Game")
p = 1
green = (0,255,0)
pacman ="imgres.jpeg"
pacman_x = 0
pacman_y = 0
while True:
pacman_obj=pygame.image.load(pacman).convert()
blue = (0,0,255)
screen.fill(blue) # first fill screen with blue
screen.blit(pacman_obj, (pacman_x,pacman_y)) # Blit the iamge
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
p=0
pygame.display.update()
Related
I want to remove the sprite and not display it on screen after click. The screenshot show that the sprite is successfully removed from the group, but it is still drawn on the screen. I would be happy to get help on this matter.
import pygame as pg
class Figure1(pg.sprite.Sprite):
def __init__(self, width: int, height: int):
super().__init__()
self.image = pg.Surface((width, height))
self.image.fill((0,0,0))
self.rect = self.image.get_rect()
class Game:
def __init__(self, main_surface: pg.Surface):
self.main_surface = main_surface
self.group = pg.sprite.Group()
self.main_sprite = Figure1(40,40)
self.group.add(self.main_sprite)
self.group.draw(self.main_surface)
self.selected = None
def btn_down(self, pos, btn):
if btn == 1:
if self.main_sprite.rect.collidepoint(pos):
print(self.group.sprites())
print(self.main_sprite.alive())
self.main_sprite.kill()
print(self.group.sprites())
print(self.main_sprite.alive())
self.group.draw(self.main_surface)
pg.init()
clock = pg.time.Clock()
screen = pg.display.set_mode((200,200))
screen.fill((100,100,100))
pg.display.update()
g = Game(screen)
run = True
while run:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
run = False
if event.type == pg.MOUSEBUTTONDOWN:
g.btn_down(event.pos, event.button)
clock.tick(60)
pg.display.update()
The sprite doesn't disappear just because you stop drawing it. Of course, you need to clear the screen. You have to clear the screen in every frame. The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling 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 calling either pygame.display.update() or pygame.display.flip()
import pygame as pg
class Figure1(pg.sprite.Sprite):
def __init__(self, width: int, height: int):
super().__init__()
self.image = pg.Surface((width, height))
self.image.fill((0,0,0))
self.rect = self.image.get_rect()
class Game:
def __init__(self, main_surface: pg.Surface):
self.main_surface = main_surface
self.group = pg.sprite.Group()
self.main_sprite = Figure1(40,40)
self.group.add(self.main_sprite)
self.selected = None
def btn_down(self, pos, btn):
if btn == 1:
if self.main_sprite.rect.collidepoint(pos):
self.main_sprite.kill()
def draw(self):
self.group.draw(self.main_surface)
pg.init()
clock = pg.time.Clock()
screen = pg.display.set_mode((200,200))
g = Game(screen)
run = True
while run:
# limit the frames per second
clock.tick(60)
# handle the events and update objects
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
if event.type == pg.MOUSEBUTTONDOWN:
g.btn_down(event.pos, event.button)
# clear the screen
screen.fill((100,100,100))
# draw the objects
g.draw()
# update the display
pg.display.update()
pg.quit()
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)
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'm trying to make a Space Invaders game using Pygame. However, I'm having trouble figuring out how to make the spaceship continuously shoot multiple bullets and have the bullets move along with it. The only way I have actually made the program shoot multiple bullets is through a for loop, although the bullets stop shooting once the for loop hits its end. Should I create a list to store all the bullets? Any help is appreciated :D.
Below is my Python code so far (It only has the spaceship that fires one bullet).
from __future__ import print_function
import pygame
import os, sys
from pygame.locals import *
x_location = 357
y_location = 520
bullet_location_x = x_location + 35
bullet_location_y = y_location - 5
def load_image(path, colorkey): # loads an image given the file path
try:
image = pygame.image.load(path)
except pygame.error, message:
print("Cannot load image: {0}".format(path)) # print out error message
image = image.convert() # convert image so that it can be displayed properly
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect() # Return the image and the image's rectangular area
def main():
global x_location, y_location, bullet_location_x, bullet_location_y
pygame.init()
background_color = (0, 0, 0) # green background
width, height = (800, 600) # width and height of screen
screen = pygame.display.set_mode((width, height)) # set width and height
pygame.display.set_caption('space invaders') # set title of game
clock = pygame.time.Clock() # create the clock
spaceship_img, spaceship_rect = load_image("spaceship.png", (0, 0, 0))
bullet_img, bullet_rect = load_image("bullet.png", (0, 0, 0))
while True:
screen.fill(background_color) # make the background green
##############################################################
# DISPLAY BULLET #
##############################################################
screen.blit(bullet_img, (bullet_location_x, bullet_location_y))
# Render the images
screen.blit(spaceship_img, (x_location, y_location))
keys = pygame.key.get_pressed() # get the keysnpressed
for event in pygame.event.get(): # check the events
if event.type == pygame.QUIT: # if the user presses quit
pygame.quit() # quit pygame
sys.exit() # terminate the process
if event.type == KEYDOWN:
if event.key == K_LEFT:
screen.fill(background_color)
x_location -= 5
screen.blit(spaceship_img, (x_location, y_location))
if event.key == K_RIGHT:
screen.fill(background_color)
x_location += 5
screen.blit(spaceship_img, (x_location, y_location))
if event.key == K_UP:
screen.blit(bullet_img, (bullet_location_x, bullet_location_y))
display_bullets = True
pygame.display.flip() # refresh the pygame window
clock.tick(60) # Makes the game run at around 60 FPS
bullet_location_y -= 5
pass
if __name__ == '__main__':
main()
You should separate your game into a loop that contains 3 different functions:
LOOP
UPDATE_LOGIC
INPUT_HANDLING
DRAW_ELEMENTS
END-LOOP
In the input_handling, put a bullet into a list of bullets if the player is not in cool-down.
In the update_logic, iterate of the bullet list calculating the positions through time, and cool-down time of the player.
In the draw_elements, simply draw every thing on your scene. (iterate over the bullet list)
and you can use different timers for the draw and update_logic. That way will help you to add new elements to your game easily
I've just downloaded python 3.3.2 and pygame-1.9.2a0.win32-py3.3.msi.
I have decided to try a few tutorials on youtube and see if they work.
I have tried thenewboston's 'Game Development Tutorial - 2 - Basic Pygame Program' to see if it works. It is supposed to produce a black background and a ball that is the mouse (or so i think). It comes up with a syntax error when i try to run it, if i delete it it just produces a black pygame window. Here is the code:
bgg="bg.jpg"
ball="ball.png"
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((540,341),0,32)
background=pygame.image.load(bgg).convert()
mouse_c=pygame.image.load(ball).convert_alpha()
while True:
for event in pygame.event.get():
if event.type ==QUIT:
pygame.quit()
sys.exit()
screen.blit(background), (0,0))
The screen.blit(bakcgorund, (0,0)) command is the problem, when it comes up with the syntax error it highlights the second bracket on the furthest right of the command. If I delete it it just shows a black pygame window. can anyone help me?
I updated your code:
import pygame
from pygame.locals import *
#about: pygame boilerplate
class GameMain():
# handles intialization of game and graphics, as well as game loop
done = False
def __init__(self, width=800, height=600):
"""Initialize PyGame window.
variables:
width, height = screen width, height
screen = main video surface, to draw on
fps_max = framerate limit to the max fps
limit_fps = boolean toggles capping FPS, to share cpu, or let it run free.
now = current time in Milliseconds. ( 1000ms = 1second)
"""
pygame.init()
# save w, h, and screen
self.width, self.height = width, height
self.screen = pygame.display.set_mode(( self.width, self.height ))
pygame.display.set_caption( "pygame tutorial code" )
self.sprite_bg = pygame.image.load("bg.jpg").convert()
self.sprite_ball = pygame.image.load("ball.png").convert_alpha()
def main_loop(self):
"""Game() main loop."""
while not self.done:
self.handle_events()
self.update()
self.draw()
def draw(self):
"""draw screen"""
self.screen.fill(Color('darkgrey'))
# draw your stuff here. sprites, gui, etc....
self.screen.blit(self.sprite_bg, (0,0))
self.screen.blit(self.sprite_ball, (100,100))
pygame.display.flip()
def update(self):
"""physics/move guys."""
pass
def handle_events(self):
"""handle events: keyboard, mouse, etc."""
events = pygame.event.get()
kmods = pygame.key.get_mods()
for event in events:
if event.type == pygame.QUIT:
self.done = True
# event: keydown
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
if __name__ == "__main__":
game = GameMain()
game.main_loop()
Your parenthesis are unbalanced; there are 2 opening parenthesis, and 3 closing parenthesis; that is one closing parenthesis too many:
screen.blit(background), (0,0))
# -----^ ------^ ---^
You probably want to remove the closing parenthesis after background:
screen.blit(background, (0,0))