PyGame: Nothing Happens - python

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)

Related

player.update wont take key input and make character move pygame

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()

I'm very new to python and one of my images will not draw onto the screen

I was trying to draw an image onto the screen but I keep getting errors. The error keeps saying "video system not initialized". I am new to python, can anyone help?
import pygame
import os
#game window
WIN = pygame.display.set_mode((1000, 800))
NAME = pygame.display.set_caption("Space War!")
#FPS limit
FPS = (60)
#image i am trying to draw onto screen
SPACE_BACKGROUND = pygame.image.load(os.path.join('space_background.png'))
pygame.init()
#allows pygame to quit
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#updates images
pygame.display.update()
#calling def main(): function
if __name__ == "__main__":
main()
do:
def main():
clock = pygame.time.Clock()
run = True
FPS = 60
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#updates images
WIN.blit(SPACE_BACKGROUND, (0, 0)) #you FORGOT this part
pygame.display.update()
BTW the main function cannot access the global 'FPS' variable so declare that within the 'main' function(make it local).

Obstacle keeps disappearing after each event tick. I need it to stay on the screen

I'm creating a small game in pygame with obstacles that fall from the top of the screen to the bottom. At each event tick, an obstacle is created. However, at each new tick (1500milliseconds) the current obstacle is removed before it can reach the bottom and a new one is created. I need the obstacles to stay on the screen while new ones are generated.
I'm trying to get this done with classes and functions only.
So I want to create an obstacle_movement() function within the obstacle class.
Can you help please?
My code is below.
import pygame
import sys
from random import randint
from pygame import surface
import time
import os
class obstacle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
Obstacle_directory = r'C:\\Users\\ctcar\\Documents\\CompSci\\GameDev\\selfgame\\Graphics\\Obstacles'
obstacle_lst = []
self.obstacle_frames = []
for filename in sorted(os.listdir(Obstacle_directory), key = len):
if filename.endswith('.png'):
obstacle_lst.append('Graphics/Obstacles/' + filename)
for sprite in obstacle_lst:
alpha_sprite = pygame.image.load(sprite).convert_alpha()
self.obstacle_frames.append(alpha_sprite)
y_pos = -20
self.obstacle_idx = 0
self.frames = self.obstacle_frames
self.image = self.frames[self.obstacle_idx]
self.rect = self.image.get_rect(midbottom = (randint(50, 750), y_pos))
def obstacle_animation(self):
self.obstacle_idx += 0.1
if self.obstacle_idx >= len(self.frames):
self.obstacle_idx = 0
self.image = self.frames[int(self.obstacle_idx)]
def update(self):
self.obstacle_animation()
self.rect.y += 4
obstacle_group = pygame.sprite.GroupSingle()
obstacle_timer = pygame.USEREVENT + 1
pygame.time.set_timer(obstacle_timer, randint(1000, 1100))
game_active = True
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if game_active:
screen.blit(sky_surface,(0,0))
screen.blit(ground_surface,(100,710))
if event.type == obstacle_timer:
obstacle_group.add(obstacle())
obstacle_group.draw(screen)
obstacle_group.update()
pygame.display.update()
clock.tick(60)
You need to use a pygame.sprite.Group insterad of a pygame.sprite.GroupSingle:
obstacle_group = pygame.sprite.GroupSingle()
obstacle_group = pygame.sprite.Group()
See obstacle_group = pygame.sprite.GroupSingle():
The GroupSingle container only holds a single Sprite. When a new Sprite is added, the old one is removed.
Furthermore, the events must be handled in the event loop:
game_active = True
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if game_active:
if event.type == obstacle_timer:
obstacle_group.add(obstacle())
if game_active:
screen.blit(sky_surface,(0,0))
screen.blit(ground_surface,(100,710))
obstacle_group.draw(screen)
obstacle_group.update()
pygame.display.update()
clock.tick(60)
pygame.quit()
sys.exit()

Im trying to solve this un-smooth and choppy animations and movements on pygame, i've been trying everything but nothing works

heres the video of the animation https://www.youtube.com/watch?v=uhPdN3v8vg0
other pygame codes dont act like this, only this specific one, so i'm pretty sure its not hardware problem
import sys
import time
import pygame
import os
from pygame import mixer
pygame.init()
pygame.mixer.init()
width,height=(900,500)
border= pygame.Rect(0,0,6,height)
WIN=pygame.display.set_mode((width,height))
bg= pygame.image.load(os.path.join('','pixel_bg.jpg'))
bg=pygame.transform.scale(bg,(width,height))
person1=pygame.image.load(os.path.join('','mario.png'))
p1_width, p1_height = (50,60)
person1=pygame.transform.scale(person1,(p1_width,p1_height))
black=(0,0,0)
p1_rect = pygame.Rect(50,340,p1_width,p1_height)
pygame.display.set_caption("rpg game")
Velocity= 4
jump_height = 50
FPS = 60
mixer.music.load("adventurebeat.mp3")
mixer.music.play(-1)
def draw():
WIN.blit(bg, (0, 0))
WIN.blit(person1, (p1_rect.x,p1_rect.y))
pygame.display.update()
def p1_movement(keys_pressed, p1_rect):
if keys_pressed[pygame.K_a] and p1_rect.x - Velocity > border.x + border.width: # left
p1_rect.x -= Velocity
if keys_pressed[pygame.K_d] and p1_rect.x + Velocity + p1_rect.width < width: # right
p1_rect.x += Velocity
if keys_pressed[pygame.K_w] and p1_rect.y - Velocity > 0: # up
p1_rect.y -= Velocity
if keys_pressed[pygame.K_SPACE] and p1_rect.y - Velocity > 0: # up
p1_rect.y -= jump_height
if keys_pressed[pygame.K_s] and p1_rect.y + Velocity + p1_rect.height < height: # down
p1_rect.y += Velocity
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick_busy_loop(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
draw()
keys_pressed = pygame.key.get_pressed()
p1_movement(keys_pressed,p1_rect)
main()
I've tried changing the clock.tick_busy_loop() to clock.tick() but it still doesnt work :/
You need to draw the object in the application loop instead of the event loop:
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick_busy_loop(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
# draw() <--- DELETE
keys_pressed = pygame.key.get_pressed()
p1_movement(keys_pressed,p1_rect)
draw() # <--- INSERT
The application loop is executed in every frame, but the event loop only is executed when an event occurs.

Windows/Python pygame.error: video system not initialized after adding pygame.init() [duplicate]

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.

Categories