I am new to pygame. I've coded on Python before but never in pygame.
I've made a code which plays a sound when certain keys are clicked and now I tried to make in image moving every time that the user click with his mouse.
import pygame, os, sys
pygame.init()
screen = pygame.display.set_mode((1300,1300))
screen.fill((250,250,250))
img = pygame.image.load(os.path.join(sys.path[0],"fonddecran.v1.jpg"))
screen.blit(img, (0, 0))
pygame.display.flip()
barrel=pygame.image.load(os.path.join(sys.path[0],"barrel-man.jpg"))
pygame.display.flip()
pygame.mixer.init()
it = true
while it:
for event in pygame.event.get():
if event.type == pygame.QUIT:
it=False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 3:
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
elif event.button == 1:
screen.blit(barrel,event.pos)
pygame.display.flip()
elif event.type == pygame.KEYUP:
if event.key == ord('b'):
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
pygame.quit()
Unfortunately, the image just appears one more time every time. How can I delete it so it looks like it has moved?
To be able to "move" the image, you have to redraw the scene in each frame. Add a variable that stores the position of the image. Change the variable to the mouse position when you click the mouse:
import pygame, os, sys
pygame.init()
screen = pygame.display.set_mode((1300,1300))
img = pygame.image.load(os.path.join(sys.path[0],"fonddecran.v1.jpg"))
barrel=pygame.image.load(os.path.join(sys.path[0],"barrel-man.jpg"))
pygame.mixer.init()
barrel_pos = None
it = True
while it:
for event in pygame.event.get():
if event.type == pygame.QUIT:
it=False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 3:
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
elif event.button == 1:
barrel_pos = event.pos
elif event.type == pygame.KEYUP:
if event.key == ord('b'):
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
screen.fill((250,250,250))
screen.blit(img, (0, 0))
if barrel_pos:
screen.blit(barrel, barrel_pos)
pygame.display.flip()
pygame.quit()
Related
I want the screen to change to all black after the enter button is pressed.
I was trying to have the screen clear here, when the enter key gets pressed:
def newScreen(self):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
pygame.win.fill(self,(0,0,0))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
win.fill((0,0,0))
Even this will not work if you have a bigger code that is blitting something else on the screen like a background in the while loop as it will again blit the background and black screen would be visible for a micro second thus you will need to define a variable(black_fill is my name) and set its value as False and if not black_fill: than only blit the other images and else: win.fill((0,0,0)).Also when enter is pressed( the way you tracked its clicking by events) just make black_fill as True.
win = pygame.display.set_mode((1000, 500))
black_fill = False
bg = pygame.image.load('any_bg_file')
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
black_fill = True
if not black_fill:
win.blit(bg, (0, 0))
else:
win.fill((0, 0, 0))
pygame.display.flip()
I want to create a really simple application that starts a song while you press the SPACE bar, but when I start the application and press the space bar, I just hear a "pop" sound, and nothing starts. No music.
Here is the code:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.pre_init(42000,-16,1,2048)
pygame.mixer.init()
musik = pygame.mixer.Sound(b'musik.wav')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
musik.play()
Ok, thank you so much guys ! It works perfectly now.
Here is the final code if someone has the same problem as me:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
pygame.event.clear()
while True:
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
elif event.type == KEYUP and event.key == K_SPACE:
pygame.mixer.music.stop()
I don't know why the code doesn't work, but I know it does work if you use a mp3 file. try this:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
If you want to use your .wav file you can find .wav to .mp3 online
I think that you misunderstood the use for pygame.event. You should try with pygame.event.wait() :
pygame.event.clear()
while True:
# wait until new event happens - blocking instruction
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key = K_SPACE:
musik.play()
I'm a beginner in python and I am trying to learn the features of pygame in order to make a simple game. I want to move an image using the wasd keys, but it's not working. Please help.
I'm using python (3.7.0) on windows 10.
The following is the code:
import pygame
from pygame.locals import *
pygame.init()
pygame.display.init()
keys = [False, False, False, False]
screen=pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
background=pygame.Surface(screen.get_size())
background.fill((255,255,255))
playerpos=[100,100]
player=pygame.image.load("Copper.png")
while 1:
pygame.display.init()
screen.fill(0)
screen.blit(background,(0,0))
screen.blit(player,playerpos)
for event in pygame.event.get():
pygame.display.init()
pygame.display.flip()
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_RETURN:
pygame.display.quit()
pygame.display.flip()
# 8 - loop through events
for event in pygame.event.get():
# 9 - check if event is X button
if event.type==pygame.QUIT:
# 10 - quit the game
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
# 9 - Move player
if keys[0]:
playerpos[1]-=500
elif keys[2]:
playerpos[1]+=500
if keys[1]:
playerpos[0]-=500
elif keys[3]:
playerpos[0]+=500
I expect the image "Copper.png" to move when I press w,a,s,d but the image does not move. The image does refresh everytime I press w,a,s,d but does not move.
Get rid of the multiple even handling loops. Use a single loop to handle all the events.
Further it is sufficient to init the display once (pygame.display.init())
Create a variable speed, which defines the number of pixels, the position of the image changes by each step
First evaluate the pygame.QUIT event and stop running the main loop when the event happens:
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
Then handle the other events like the pygame.KEYDOWN and pygame.KEYUP.
For a continuously movement, the manipulation of the player position has to be done outside the event loop. If it would be don in the loop, the the position of the player would only change if en event occurs. Note use a small "speed" (speed = 1), else the player would rapidly moved out of the window.
for event in pygame.event.get():
# event handling
if keys[0]:
playerpos[1]-=speed
elif keys[2]:
playerpos[1]+=speed
if keys[1]:
playerpos[0]-=speed
elif keys[3]:
playerpos[0]+=speed
Do the drawing of the scene at the end of main loop:
speed = 1
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key==pygame.K_RETURN:
done = True
for i in range(4):
if event.key == (K_w, K_a, K_s, K_d)[i]:
keys[i]=True
elif event.type == pygame.KEYUP:
for i in range(4):
if event.key == (K_w, K_a, K_s, K_d)[i]:
keys[i]=False
if keys[0]:
playerpos[1]-=speed
elif keys[2]:
playerpos[1]+=speed
if keys[1]:
playerpos[0]-=speed
elif keys[3]:
playerpos[0]+=speed
screen.fill(0)
screen.blit(background,(0,0))
screen.blit(player,playerpos)
pygame.display.flip()
Note, alternatively you can use pygame.key.get_pressed() to get all states of of all keyboard buttons at once. So you don't need to evaluate the key events separately:
speed = 1
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
done = True
allKeys = pygame.key.get_pressed()
playerpos[0] += -speed if allKeys[K_a] else speed if allKeys[K_d] else 0
playerpos[1] += -speed if allKeys[K_w] else speed if allKeys[K_s] else 0
screen.fill(0)
screen.blit(background,(0,0))
screen.blit(player,playerpos)
pygame.display.flip()
I'm trying to pause my game by pressing the 'p' key, but after it pauses it does not unpause when p is pressed again. Here are the relevant segments of my code, I'd like to know how to fix this and/or if there are better alternative methods of implementing a game pause.
pause = False
while True:
if not pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#game code
keys = pygame.key.get_pressed()
#if key up
elif keys[pygame.K_p]:
pause = True #appears to work correctly, screen freezes and
#prints "PAUSED" every tick.
#more game code
pygame.display.update()
fpsClock.tick(FPS)
else:
print("PAUSED")
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.type == pygame.K_p:
pause = False
pygame.display.update()
fpsClock.tick(FPS)
The code below does the trick.
I have added in if not pause: ... else: section also a handler for a keypress because without it there will be no chance to come out of the pause (the part if not pause won't never ever be run without this keypress check if once paused).
import pygame
pygame.init() # start PyGame (necessary because 'import pygame' doesn't start PyGame)
colorWhite = (255, 255, 255) # RGB color for later use in PyGame commands (valueRed=255, valueGreen=255, valueBlue=255)
colorWhite = (255, 255, 255) # RGB color for later use in PyGame commands (valueRed=255, valueGreen=255, valueBlue=255)
winDisplay = pygame.display.set_mode((1024, 768)) # set PyGame window size to 1024x768 pixel
pygame.display.set_caption("Minimal PyGame Test Script")
winDisplay.fill(colorWhite)
fpsClock = pygame.time.Clock()
FPS = 15
pause = False
pauseCounter = 0
while True:
if not pause:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
pause = not pause
#game code
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#more game code
pygame.display.update()
fpsClock.tick(FPS)
else:
pauseCounter += 1
print(pauseCounter, "PAUSED")
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
pause = not pause
#more game code
pygame.display.update()
fpsClock.tick(FPS)
I'm working on a small script in Python 2.7.9 and Pygame that would be a small display for our IT department. The idea is that there are several toggle switches that indicate our current status (in, out, etc) , some information about our program at the school, and play a short video that repeats with images of the IT staff etc. I have an older version of Pygame compiled that still allows for pygame.movie to function.
All of the parts of the script work, but when it gets to the end of the .mpg, the movie will not replay until there is an EVENT, like switching our status or moving the mouse. I have tried to define a variable with movie.get_time and call to rewind at a certain time, but the movie will not rewind (currently commented out) . Is there a way to play the movie on repeat without requiring an event, or maybe I could spoof an event after a certain length of time (note that the documentation for pygame.movie is outdated, the loops function does not work) ?
Thank you for the help!
import pygame, sys, os, time, random
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("DA IT Welcome Sign")
pygame.font.get_default_font()
bg = pygame.image.load('da.jpg')
in_img = pygame.image.load('in.png')
out_img = pygame.image.load('out.png')
etc_img = pygame.image.load('etc.png')
present = in_img
done = False
img = 1
clock = pygame.time.Clock()
movie = pygame.movie.Movie('wallace.mpg')
movie_screen = pygame.Surface(movie.get_size()).convert()
playing = movie.get_busy()
movie.set_display(movie_screen)
length = movie.get_length()
currenttime = movie.get_time()
movie.play()
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == pygame.QUIT:
movie.stop()
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
img = 1
if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
img = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
img = 3
if event.type == pygame.KEYDOWN and event.key == K_w:
pygame.display.set_mode((800, 600))
if event.type == pygame.KEYDOWN and event.key == K_f:
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
if img == 1:
present = in_img
if img == 2:
present = out_img
if img == 3:
present = etc_img
if not(movie.get_busy()):
movie.rewind()
movie.play()
#movie.get_time()
#if currenttime == 25.0:
# movie.stop()
# movie.rewind()
# movie.play()
windowSurface.blit(bg, (0, 0))
windowSurface.blit(movie_screen,(550,175))
windowSurface.blit(present, (0,0))
pygame.display.flip()
You need to take the code for replaying the movie out of the for loop that gets current events. Do this for that code and any other code you want to happen continuously without waiting for an event by moving the code 4 spaces to the left.
Like so:
while not done:
for event in pygame.event.get(): #gets most recent event, only executes code below when there is an event
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == pygame.QUIT:
movie.stop()
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
img = 1
if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
img = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
img = 3
if event.type == pygame.KEYDOWN and event.key == K_w:
pygame.display.set_mode((800, 600))
if event.type == pygame.KEYDOWN and event.key == K_f:
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
#code below is out of the event for loop and thus executes whenever the while loop runs through
if img == 1:
present = in_img
if img == 2:
present = out_img
if img == 3:
present = etc_img
if not(movie.get_busy()):
movie.rewind()
movie.play()
#movie.get_time()
#if currenttime == 25.0:
# movie.stop()
# movie.rewind()
# movie.play()
windowSurface.blit(bg, (0, 0))
windowSurface.blit(movie_screen,(550,175))
windowSurface.blit(present, (0,0))
pygame.display.flip()
I have run into this problem too while trying to do things with pygame, it seems to be a common error.