Can't create and run class why? [duplicate] - python-3.x

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.

Related

How to use pygame and vlc with supervisor? [duplicate]

I'm having a problem. I want to load and play a video in pygame but it doesn't start. The only thing that I am seeing is a black screen. Here is my code:
import pygame
from pygame import display,movie
pygame.init()
screen = pygame.display.set_mode((1024, 768))
background = pygame.Surface((1024, 768))
screen.blit(background, (0, 0))
pygame.display.update()
movie = pygame.movie.Movie('C:\Python27\1.mpg')
mrect = pygame.Rect(0,0,140,113)
movie.set_display(screen, mrect.move(65, 150))
movie.set_volume(0)
movie.play()
Can you help me??
The pygame.movie module is deprecated and not longer supported.
If you only want to show the video you can use MoviePy (see also How to be efficient with MoviePy):
import pygame
import moviepy.editor
pygame.init()
video = moviepy.editor.VideoFileClip("video.mp4")
video.preview()
pygame.quit()
An alternative solution is to use the OpenCV VideoCapture. Install OpenCV for Python (cv2) (see opencv-python). However, it should be mentioned that cv2.VideoCapture does not provide a way to read the audio from the video file.
This is only a solution to show the video but no audio is played.
Opens a camera for video capturing:
video = cv2.VideoCapture("video.mp4")
Get the frames per second form the VideoCapture object:
fps = video.get(cv2.CAP_PROP_FPS)
Create a pygame.time.Clock:
clock = pygame.time.Clock()
Grabs a video frame and limit the frames per second in the application loop:
clock.tick(fps)
success, video_image = video.read()
Convert the camera frame to a pygame.Surface object using pygame.image.frombuffer:
video_surf = pygame.image.frombuffer(video_image.tobytes(), video_image.shape[1::-1], "BGR")
See also Video:
Minimal example:
import pygame
import cv2
video = cv2.VideoCapture("video.mp4")
success, video_image = video.read()
fps = video.get(cv2.CAP_PROP_FPS)
window = pygame.display.set_mode(video_image.shape[1::-1])
clock = pygame.time.Clock()
run = success
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
success, video_image = video.read()
if success:
video_surf = pygame.image.frombuffer(
video_image.tobytes(), video_image.shape[1::-1], "BGR")
else:
run = False
window.blit(video_surf, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
You are not actually blitting it to a screen. You are also not utilizing a clock object so it will play as fast as possible. Try this:
# http://www.fileformat.info/format/mpeg/sample/index.dir
import pygame
FPS = 60
pygame.init()
clock = pygame.time.Clock()
movie = pygame.movie.Movie('MELT.MPG')
screen = pygame.display.set_mode(movie.get_size())
movie_screen = pygame.Surface(movie.get_size()).convert()
movie.set_display(movie_screen)
movie.play()
playing = True
while playing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
movie.stop()
playing = False
screen.blit(movie_screen,(0,0))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
I just got that MELT.MPG from the link provided in the comment. You should be able to simply switch out that string for your actual MPG you want to play and it will work... maybe.
As you probably know, the pygame.movie module is deprecated and no longer exists in the latest version of pygame.
An alternative would be to read in frames of the video one by one and blit them onto the pygame screen using the the cv2 module (OpenCV), that can be installed with the command prompt command:
pip install opencv-python
Then, you can run the code:
import cv2
import pygame
cap = cv2.VideoCapture('video.mp4')
success, img = cap.read()
shape = img.shape[1::-1]
wn = pygame.display.set_mode(shape)
clock = pygame.time.Clock()
while success:
clock.tick(60)
success, img = cap.read()
for event in pygame.event.get():
if event.type == pygame.QUIT:
success = False
wn.blit(pygame.image.frombuffer(img.tobytes(), shape, "BGR"), (0, 0))
pygame.display.update()
pygame.quit()

can i generate an image using python within jupyter

Is there a way to use python code to create an image (in memory ) and display it within a jupyter notebook?
I want to be able to display some grid of pixels so I need to be able to set its size and be able to select which of its pixels is lit and which is not.
eventually I would like to make it animate display a series of calculate pixel images.
I tried using :
import pygame as pg
pg.init()
screen= pg.display.set_mode([225,150])
r=pg.Color('red')
w=pg.Color('white')
data=[
[r,r,r,r,r,r,r,r,r],
[r,w,w,w,w,w,w,w,r],
[r,w,w,w,w,w,w,w,r],
[r,w,w,w,w,w,w,w,r],
[r,w,w,w,w,w,w,w,r],
[r,r,r,r,r,r,r,r,r]
]
for y,row in enumerate(data):
for x,colour in enumerate(row):
rect = pg.Rect(x*25,y*25,25,25)
screen.fill(colour,rect=rect)
pg.display.update()
while True:
for event in pg.event.get():
if event.type == QUIT:
pg.quit()
sys.exit()
CLOCK.tick(30)
Which I grabbed from https://www.youtube.com/watch?v=b84EywkQ3HI but it does not seem to do anything in jupyter.
The code snippet is incomplete. The complete and working example is as follows:
import pygame as pg
from pygame.locals import * # <---
pg.init()
screen= pg.display.set_mode([225,150])
r=pg.Color('red')
w=pg.Color('white')
data=[
[r,r,r,r,r,r,r,r,r],
[r,w,w,w,w,w,w,w,r],
[r,w,w,w,w,w,w,w,r],
[r,w,w,w,w,w,w,w,r],
[r,w,w,w,w,w,w,w,r],
[r,r,r,r,r,r,r,r,r]
]
for y,row in enumerate(data):
for x,colour in enumerate(row):
rect = pg.Rect(x*25,y*25,25,25)
screen.fill(colour,rect=rect)
CLOCK = pg.time.Clock() # <---
pg.display.update()
while True:
for event in pg.event.get():
if event.type == QUIT:
pg.quit()
sys.exit()
CLOCK.tick(30)
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()

pygame.display.flip() seems to not be working?

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)

Key Pressing System PyGame

I'm making a basic pong game and want to make a system where a button press makes the paddle goes up or down. I'm fairly new to PyGame and here's my code so far.
import pygame, sys
from pygame.locals import*
def Pong():
pygame.init()
DISPLAY=pygame.display.set_mode((600,400),0,32)
pygame.display.set_caption("Pong")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
DISPLAY.fill(BLACK)
while True:
def P(b):
pygame.draw.rect(DISPLAY,WHITE,(50,b,50,10))
xx=150
P(xx)
for event in pygame.event.get():
if event.type==KEYUP and event.key==K_W:
P(xx+10)
xx=xx+10
pygame.display.update()
elif event.type==QUIT:
pygame.quit()
sys.exit()
Please read some tutorials and/or docs. This is really basic and if you don't get this right it will bite you later.
Anyway, here's how it could look:
import pygame
pygame.init()
DISPLAY = pygame.display.set_mode((600,400))
paddle = pygame.Rect(0, 0, 10, 50)
paddle.midleft = DISPLAY.get_rect().midleft
speed = 10
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit(0)
keystate = pygame.key.get_pressed()
dy = keystate[pygame.K_s] - keystate[pygame.K_w]
paddle.move_ip(0, dy * speed)
DISPLAY.fill(pygame.Color("black"))
pygame.draw.rect(DISPLAY, pygame.Color("white"), paddle)
pygame.display.update()
clock.tick(30)
That is ok for Pong but I still wouldn't write my game like this. So read some tutorials and maybe try CodeReview if you really want to improve your code.

How to use keyboard in pygame?

I tried the simple script below, but I get no response. Maybe I don't understand what pygame is capable of doing. I simply want to assign a certain function to a certain key. Like if I press the letter 'h' I want "Bye" to print on the screen or if I press 'g' then play a certain song. And so on and so on...
import pygame
from pygame.locals import *
pygame.init()
print K_h #It prints 104
while True:
for event in pygame.event.get():
if event.type==KEYDOWN:
if event.key==K_h:
print "Bye" #Nothing is printed when I press h key
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,480))
clock = pygame.time.Clock()
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == KEYDOWN:
if event.key == K_h:
print "bye"
for what ever reason for me atleast it seems the event command wouldn't work with out the use of a screen even if it has no purpose this will get you the results you want.

Resources