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
KEYDOWandKEYUPevents for your task. aPlayerobject andqueuethe sound.play()the sound onKEYDOWNanddelete()the sound onKEYUP.Also
deletethe sound currently playing when a key is pressed.The keyboard events (see pygame.event module) occur only once when the state of a key changes. The
KEYDOWNevent occurs once every time a key is pressed.KEYUPoccurs 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 is1, otherwise0. It is a snapshot of the keys at that very moment The new state of the keys must be retrieved continuously in each frame. Usepygame.key.get_pressed()to evaluate the current state of a button and get continuous movement.