import pygame as pg
import time
import random
import pyglet
from pygame import mixer
pg.init()
mixer.init()
sx=1920
sy=1080
x=100
y=100
xP=yP=3
score=scorem=0
size=(sx,sy)
screen=pg.display.set_mode(size)
pg.display.set_caption('CybeRun')
font=pg.font.SysFont('valorax',128)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
BLACK=(0,0,0)
WHITE=(255,255,255)
FPS=60
gg=pg.image.load('hz.png')
cyru=font.render("CyberRun",1,BLACK,WHITE)
tw,th=cyru.get_size()
zad=pg.image.load('zad.jpg')
zadOK=pg.transform.scale(zad, (1920,1080))
width=1920
i=0
f=1
mixer.music.load('FON.wav')
UPm=pyglet.media.load("UP.mp3")
DOWNm=pyglet.media.load("DOWN.mp3")
mixer.music.play(-1)
while True:
for ev in pg.event.get():
if ev.type==pg.QUIT:
exit()
screen.fill(BLACK)
screen.blit(zadOK,(i,0))
screen.blit(zadOK,(width+i,0))
if i==-width:
screen.blit(zadOK,(width+i,0))
i=0
i-=1
screen.blit(cyru,(((sx-tw)//2),0))
screen.blit(gg,(x,y))
key=pg.key.get_pressed()
if key[pg.K_UP]:
y-=yP
UPm.play()
if key[pg.K_DOWN]:
y+=yP
DOWNm.play()
pg.display.update()
I was trying to write my first game. As planned, at the very bottom of the code, I want the desired sound to be made whenever the up or down key is pressed. But the trouble is that when you click the sound (sounds) overlap each other. I've tried everything I can, but nothing helps. I'm a beginner and I don't understand much yet(
You have to use the KEYDOW
and KEYUP
events for your task.
a Player
object and queue
the sound.
play()
the sound on KEYDOWN
and delete()
the sound on KEYUP
.
Also delete
the sound currently playing when a key is pressed.
upPlayer = pyglet.Player()
upPlayer.queue(UPm)
downPlayer = pyglet.Player()
downPlayer.queue(DOWNm)
while True:
for ev in pg.event.get():
if ev.type == pg.QUIT:
exit()
if ev.type == pg.KEYDOWN:
if ev.key == pg.K_UP:
downPlayer.delete()
upPlayer.play()
if ev.key == pg.K_DOWN:
upPlayer.delete()
downPlayer.play()
if ev.type == pg.KEYUP:
if ev.key == pg.K_UP:
upPlayer.delete()
if ev.key == pg.K_DOWN:
downPlayer.delete()
# [...]
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN
event occurs once every time a key is pressed. KEYUP
occurs once every time a key is released. Use the keyboard events for a single action such as starting sound playback.
pygame.key.get_pressed()
returns a sequence with the state of each key. If a key is held down, the state for the key is 1
, otherwise 0
. It is a snapshot of the keys at that very moment The new state of the keys must be retrieved continuously in each frame. Use pygame.key.get_pressed()
to evaluate the current state of a button and get continuous movement.