I am new to pygame and this code I created by following a tutorial is not working. The white box i made on the screen should be moving with my arrow keys but its not. Does anyone know why? Also can someone explain what self means in the class and defs?
import pygame
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,
)
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
#Define a player object by extending pygame.sprite.Sprite
# The surface drawn on the screen is now an attribute of Player
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()
def update(self, pressed_keys):
if pressed_keys[K_UP]:
self.rect.move_ip(0,-5)
if pressed_keys[K_DOWN]:
self.rect.move_ip(0,5)
if pressed_keys[K_LEFT]:
self.rect.move_ip(-5,0)
if pressed_keys[K_RIGHT]:
self.rect.move_ip(5,0)
#Instantiate player
pygame.init()
player = Player()
#keeps main loop running
running = True
#main loop
while running:
for event in pygame.event.get():
#Did user hit a key?
if event.type == KEYDOWN:
# Was it the escape key? if so, exit loop
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.fill((0,0,0))
screen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
pygame.display.flip()
I tried to make the block move by clicking the arrow keys.
You always draw the player in the center of the screen:
screen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
You have to draw the player at player.rect:
screen.blit(player.surf, player.rect)
However, since you use pygame.sprite.Sprite you should also use pygame.sprite.Group and you should limit the frames per second with pygame.time.Clock.tick:
clock = pygame.time.Clock()
player = Player()
spriteGroup = pygame.sprite.Group()
spriteGroup.add(player)
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.fill((0,0,0))
spriteGroup.draw(screen)
pygame.display.flip()
Related
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.
New to Python and have left myself stumped for a few hours. I am trying to follow the examples in the book Python Crash Course. Im at the last part of trying to make bullets shoot across the screen but i come with the AttributeError when trying to define the limits of the game screen the bullet can travel before being deleted, in the '_update_bullets' method. I have tried using self.screen_rect but that also brings up an AttributeError.
import sys
import pygame
from gun import Gun
from bullets import Bullet
class SidewaysShooter:
#Game board
def __init__(self):
#Initializes game and resources.
pygame.init()
self.screen = pygame.display.set_mode((1200, 500))
pygame.display.set_caption("Sideways Shooter")
self.gun = Gun(self)
self.bullets = pygame.sprite.Group()
#set background color
self.bg_color = (153, 72, 141)
def run_game(self):
#Start the main loop for the game
while True:
self._check_events()
self.gun.update ()
self._update_bullets()
self._update_screen()
def _check_events(self):
#Watch for keyboard and mounse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_keydown_events(self, event):
if event.key == pygame.K_UP:
self.gun.moving_up = True
elif event.key == pygame.K_DOWN:
self.gun.moving_down = True
elif event.key == pygame.K_SPACE:
self._fire_bullet()
elif event.key == pygame.K_q:
pygame.quit()
sys.exit()
def _check_keyup_events(self, event):
if event.key == pygame.K_UP:
self.gun.moving_up = False
if event.key == pygame.K_DOWN:
self.gun.moving_down = False
def _fire_bullet(self):
"""Create a new bullet and add it to the bullets group."""
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_bullets(self):
"""Update the position of the bullets and get rid of old bullets."""
#Update bullets position
self.bullets.update()
#Get rid of bullets that have disappeared.
for bullet in self.bullets.copy():
if bullet.rect.left >= self.screen_right:
self.bullets.remove(bullet)
def _update_screen(self):
#Update images on a screen and flip to a new screen
self.screen.fill(self.bg_color)
self.gun.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
pygame.display.flip()
if __name__== '__main__':
#MAke a game instance, and run the game.
ai = SidewaysShooter()
ai.run_game()
'''
You get the attribute error because there is no "screen_right"-Attribute defined (in your example).
You need to inizialize it as a Int, to have access to it in all of the objects functions it needs to be in your "__init__(self)" function.
Example:
def __init__(self):
#Initializes game and resources.
pygame.init()
self.display_width = 1200 # The size of the screen should be defined
self.display_height = 500 # Now you can use it when you create the screen.
self.screen = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption("Sideways Shooter")
self.gun = Gun(self)
self.bullets = pygame.sprite.Group()
#set background color
self.bg_color = (153, 72, 141)
self.screen_right = self.display_width # This is the position of the right side of the screen, 0 would be the left side
This question already has answers here:
Windows/Python pygame.error: video system not initialized after adding Mp3 file
(2 answers)
Closed 5 years ago.
I added some music to my pygame game and pygame.init() to the script to initialize the video system before it is called, but I think the code is so messy that nothing is in the right place even after moving everything to where it needs to be. As a result of this addition, I'm now getting this error still after adding pygame.init():
Traceback (most recent call last):
File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\My First game ERROR.py", line 31,
in for event in pygame.event.get():
pygame.error: video system not initialized
Here is the code that I have written:
# This just imports all the Pygame modules
import pygame
pygame.init()
class Game(object):
def main(self, screen):
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('St.Patrick game')
Game().main(screen)
clock = pygame.time.Clock()
while 1:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.quit():
pygame.quit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
pygame.quit()
pygame.mixer.init(44100, -16,2,2048)
import time
pygame.mixer.music.load('The Tonight Show Star Wars The Bee Gees Stayin Alive Shortened.mp3')
pygame.mixer.music.play(-1, 0.0)
#class Player(pygame.sprite.Sprite):
# def __init__(self, *groups):
# super(Player, self.__init__(*groups)
#self.image = pygame.image.load('Sprite-01.png')
# self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
#def update(self):
# key = pygame
image = pygame.image.load('Sprite-01.png')
# initialize variables
image_x = 0
image_y = 0
image_x += 0
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
image_x -= 10
if key[pygame.K_RIGHT]:
image_x += 10
if key[pygame.K_UP]:
image_y -= 10
if key[pygame.K_DOWN]:
image_y += 10
screen.fill((200, 200, 200))
screen.blit(image, (image_x, image_y))
pygame.display.flip()
pygame.mixer.music.stop(52)
Your problem can be pygame.quit() inside while loop.
pygame.quit() uninitializes modules initialized with pygame.init() - but it doesn't exit while loop so while-loop tries to use event.get() in next loop. And then you get problem because you uninitialized modules.
Besides, it makes no sense
if event.type == pygame.quit():
it has to be
if event.type == pygame.QUIT:
pygame.quit() is function which ends what pygame.init() started.
pygame.QUIT is constant value - try print(pygame.QUIT) - which you can compare with event.type.
We use UPPER_CASE_NAMES for constant values. Read: PEP 8 -- Style Guide for Python Code
Finally, you need rather
running = True
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
So it exits loop but it doesn't uninitialize modules which you will need in rest of code.
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)
I am making a game in pygame and when I go to run the game nothing is happening. A black box appears but does nothing at all there is no display etc. Also what bugs me is the fact the Python Shell is not displaying any errors at all. Here is the code for the main file:
import pygame
import sys
import random
import pygame.mixer
import math
from constants import *
from player import *
class Game():
def __init__(self):
#States (Not country states)
self.game_state = STATE_INGAME
#State variables
#self.stateMenu =
#Screen
size = SCREEN_WIDTH, SCREEN_HEIGHT
self.screen = pygame.display.set_mode(size)
pygame.display.set_caption('WIP')
self.screen_rect = self.screen.get_rect()
# Player
self.player = Player(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
def run(self):
clock = pygame.time.Clock()
if self.game_state == STATE_INGAME:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.player_move()
self.player.update()
self.player.render(self.screen)
clock.tick(100)
def player_move(self):
# move player and check for collision at the same time
self.player.rect.x += self.player.velX
self.player.rect.y += self.player.velY
Game().run()
I have checked the player file many times and there are NO errors in there at all. Well not from what I can see. Thanks for the help!
You need a while-loop:
def run(self):
clock = pygame.time.Clock()
while True:
if self.game_state == STATE_INGAME:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.player_move()
self.player.update()
self.player.render(self.screen)
clock.tick(100)