pygame.display.flip() seems to not be working? - python-3.x

I've been working on a project, and when I tested it this happened. After a little testing I soon realized it was something wrong in the pygame display flip part of the code. I really don't see what's wrong here, so I hope one of you do.
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
img = pygame.image.load("test.png")
while 1:
screen.fill((0, 0, 0))
screen.blit(img, (0, 0))
pygame.display.flip()
pygame.time.delay(10)
Now, the result is a blank white screen that's 200 by 200. I hope someone sees what's wrong here. Also, my png doesn't matter here because I get the same result with just the fill(black), so I hope someone knows.

Couple things here:
1) I would recommend using the pygame clock instead of time.delay. Using the clock sets the frames per second to run the code, where the time.delay just sits and waits for the delay.
2) Pygame is event driven, so you need to be checking for events, even if you don't have any yet. otherwise it is interpreted as an infinite loop and locks up. for a more detailed explanation: click here
3) I would offer a way out of the game loop with a flag that can be set to false, that way the program can naturally terminate
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
img = pygame.image.load("test.png")
clock = pygame.time.Clock()
game_running = True
while game_running:
# evaluate the pygame event
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False # or anything else to quit the main loop
screen.fill((0, 0, 0))
screen.blit(img, (0, 0))
pygame.display.flip()
clock.tick(60)

Related

Blit function not working for displaying an image

I've currently been following along with a video over pygame and creating a space invaders type of game that I will modify for my own implementation of the game. However I've gotten to the section where you have to use the blit function in order to display an image for the background of the game and it's not working for me. Once the program is executed, the window is launched but without the image displayed for the background. I believe that I have properly loaded the image and stepped into the function that will use the blit function for displaying the background image as well. Please let me know if I have overlooked anything, any help will be greatly appreciated.
import pygame
import os
import time
import random
#Setting window frame
WIDTH, HEIGHT = 1000, 600
WINDOW = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Space Battle")
#Image Loading
RED_SPACESHIP = pygame.image.load(os.path.join("assets", "pixel_ship_red_small.png"))
GREEN_SPACESHIP = pygame.image.load(os.path.join("assets", "pixel_ship_green_small.png"))
BLUE_SPACESHIP = pygame.image.load(os.path.join("assets", "pixel_ship_blue_small.png"))
#Ship for player
YELLOW_SPACESHIP = pygame.image.load(os.path.join("assets", "pixel_ship_yellow.png"))
#Laser loading
YELLOW_LASER = pygame.image.load(os.path.join("assets", "pixel_laser_yellow.png"))
RED_LASER = pygame.image.load(os.path.join("assets", "pixel_laser_red.png"))
GREEN_LASER = pygame.image.load(os.path.join("assets", "pixel_laser_green.png"))
BLUE_LASER = pygame.image.load(os.path.join("assets", "pixel_laser_blue.png"))
Here is the code for loading in the back ground image
#Loading Backgrnd Img
BG = pygame.image.load(os.path.abspath("assets/background-black.png"))
formatedBG = pygame.transform.scale(BG, (WIDTH,HEIGHT))
Here is the code for the main function and handling background display.
def window_Redraw():
WINDOW.blit(formatedBG, (0,0))
pygame.display.update()
def main():
run = True
FPS = 60
clock = pygame.time.Clock()
while run:
clock.tick(FPS)
window_Redraw()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
main()
Here is a screenshot of the window after execution:
enter image description here
Your example is much more complicated that it should be. RED_SPACESHIP, BLUE_SPACESHIP... etc are irrelevant in this case and you should remove them.
You are displaying only a black background - nothing else, so it should be displayed. In order to check if everything is working, start from this example:
import pygame
# initialize the pygame module
pygame.init()
WIDTH, HEIGHT = 1000, 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
formatedBG = pygame.Surface((WIDTH, HEIGHT))
formatedBG.fill(pygame.color.Color(255, 0, 0, 0))
# BG = pygame.image.load(os.path.abspath("assets/background-black.png"))
# formatedBG = pygame.transform.scale(BG, (WIDTH, HEIGHT))
run = True
while run:
WINDOW.blit(formatedBG, (0, 0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
And then uncomment the background to check whether the background changed to black color.
My previous version of pygame which was 1.9.4 was causing my initial issues with displaying the background image using blit and the problem with the window not being able to display any color with the fill function. I solved these issues by running the command 'pip install==2.0.0.dev4' to upgrade pygame. Everything seems to be working properly now.

Can't create and run class why? [duplicate]

I have a simple Pygame program:
#!/usr/bin/env python
import pygame
from pygame.locals import *
pygame.init()
win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
But every time I try to run it, I get this:
pygame 2.0.0 (SDL 2.0.12, python 3.8.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
And then nothing happens.
Why I can't run this program?
Your application works well. However, you haven't implemented an application loop:
import pygame
from pygame.locals import *
pygame.init()
win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()
run = True
while run:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# update game objects
# [...]
# clear display
win.fill((0, 0, 0))
# draw game objects
# [...]
# update display
pygame.display.flip()
# limit frames per second
clock.tick(60)
pygame.quit()
The typical PyGame application loop has to:
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()
limit frames per second to limit CPU usage with pygame.time.Clock.tick
repl.it/#Rabbid76/PyGame-MinimalApplicationLoop See also Event and application loop
This is interesting. Computer read your program line by line[python]. When all the line are interpreted, the program closed. To solve this problem you need to add a while loop to make sure the program will continue until you close the program.
import pygame,sys
from pygame.locals import *
pygame.init()
pygame.display.set_caption("My first game")
win = pygame.display.set_mode((400,400))
#game loop keeps the game running until you exit the game.
game_running=True
while game_running:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
win.fill((0, 250, 154)) #Fill the pygame window with specific color. You can use hex or rgb color
pygame.display.update() #Refresh the pygame window
You can check more pygame Examples.
https://github.com/01one/Pygame-Examples
I think this will be helpful.

Random Module help in python

So here I have my code to connect 3 game. In order for me to proceed to finish coding the rest of the game, I need your help fixing the loop that determines what player goes first. When the loop randomly selects the player, it blits it's token however it keeps bliting both of the players tokens which means that the random function keeps running. How do I fix it so it runs once. Thanks!
import pygame, sys, random
from pygame.locals import*
#FPS
FPS =7
fpsClock = pygame.time.Clock()
#Display
DISPLAYSURF=pygame.display.set_mode((850, 725), 0, 32)
pygame.display.set_caption('Connect 3~Emoji Edition')
#Colors
WHITE=(255, 255, 255)
#Players
Player1='P1'
Player2='P2'
#Images
#Keyboard
Board=pygame.image.load('Keyboard.png')
Boardx=45
Boardy=200
#Token1
Token1=pygame.image.load('PoopEMJ.png')
Token1=pygame.transform.scale(Token1, (90, 90))
Token1x=375
Token1y=215
#Token2
Token2=pygame.image.load('LaughingEMJ.png')
Token2=pygame.transform.scale(Token2, (90, 90))
Token2x=375
Token2y=215
while True:
DISPLAYSURF.fill(WHITE)
DISPLAYSURF.blit(Board,(Boardx, Boardy))
#Randomly selects players *HELP*
Turn='Player'
if random.randint(0, 1) == 0:
Turn = Player1
DISPLAYSURF.blit(Token1,(Token1x, Token1y))
else:
Turn = Player2
DISPLAYSURF.blit(Token2,(Token2x, Token2y))
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
You have put the code to randomly select the player, in the While True loop.
This means that it will constantly select a new random player and blit it to the screen. you must only select a new random player when the last player has finished their turn, or it is the beginning of the game.

Pygame screen flickering

I am quite new to Python and currently trying to make my first game with Pygame. I just started and got a problem. My screen is flickering white (fill colour) to black. I tried to lower the tick (even to 1), but it didn't help (actually, it was flickering less, but still visible a lot). I tried to find any help online, but everywhere "display.update / flip used more than once per cycle" was suggested as a problem and it didn't fix mine.
I am currently running a Fedora 20 box, with Nvidia graphic card (and nouveau drivers), if the issue is connected with this.
My code:
import pygame
from pygame.locals import *
class visualisation(object):
def __init__(self):
pygame.init()
pygame.time.Clock().tick()
self.window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 0)
pygame.mouse.set_visible(False)
pygame.display.set_caption('MY GAME')
self.background = pygame.Surface(self.window.get_size())
self.background = self.background.convert()
self.background.fill((250, 250, 250))
self.window.blit(self.background, (0, 0))
pygame.display.update()
if __name__ == '__main__':
running = True
while(running):
arcade = visualisation()
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
pygame.quit()
Thanks a lot in advance :)
You are calling the following functions in a loop:
pygame.init()
pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 0)
If I am not mistaken this creates a new screen variable which is very bad.
You probably wanted to create a new arcade at the start of the game, instead of on each frame.
Try moving it before the loop:
running = True
arcade = visualisation()
while(running):
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False

Pygame Collision Explained

I am brand new to Python/Pygame. I have been able to piece together a few things in small test programs but trying to get a grasp of collision is just not happening. I've tried working through multiple tutorials but I feel like I need it completely broken down before I get a good sense of it.
Can someone explain how something like colliderect(Rect) works?
Do I need a class for the collide functions or can I just take two rectangles and get a result?
The code I am trying to work with is below. I was able to make two images, each surrounded by a rect, I am assuming the collision only works with sprites and not images? I can control one of the images with my mouse, and the would like to trigger a collision detection when I mouse over and click on the static image.
Any help would be greatly appreciated.
Thx
~T
pygame.init()
clock = pygame.time.Clock()
size=width, height= 600,400
screen = pygame.display.set_mode(size)
rageface = pygame.image.load("rageface.jpg")
rageface = pygame.transform.scale(rageface,(100,100))
rageface2 = pygame.transform.scale(rageface,(100,100))
black = (100,0,0)
green = (0,150,150)
r=0
x=50
y=50
mx,my = pygame.mouse.get_pos()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
mx,my = pygame.mouse.get_pos()
#colliderect(Rect) ????????????????????
screen.fill((r,0,0))
pygame.draw.rect(screen, black, [50, 50, 250, 100], 0)
pygame.draw.rect(screen, green, [mx-50, my-50, 250, 100], 0)
screen.blit(rageface2,(mx-50,my-50))
screen.blit(rageface,(x,y))
clock.tick(60)
pygame.display.flip()
colliderect works like this:
rect1.colliderect(rect2)
This will return True if the two rects are colliding, False otherwise.
here is the documentation
colliderect is a method of the pygame Rect class, sprites also have collision methods
In pygame an image that is loaded is a surface just like the pygame screen/display, to get a rect from a surface you use:
Surface.get_rect()
So to get one for say rageface just do rage_rect = rageface.get_rect() and now you can use rage_rect like a rect
Tell me if this is clear or if you need more help!

Resources