Mouse On The Track Drum Kit

Pygame Zero provides useful built-in objects to help you make games easily.

The metronome starts, I hit some drums with my mouse. Nothing upon playback. Doesn't show anything recorded. I was using the soft synths - opened up Studio Instruments and drum kit. I'm using the UA-1G. I don't have any other device. I can drag and drop in any of the samples that are in the drum kit. They show up in the track. Louisiana Baton Rouge Sound and drum kit ( self.TrillFastlife) submitted 2 years ago by TrillFastlife. Hi sorry for my question but i search long time for hits, stomps, sound kit, fall brass and all sound like louisiana style beats type boosie, mista cain, nba youngboy, old cash money and no limit pleace if you have same like this THANKS!

Screen¶

The screen object represents your game screen.

It is a thin wrapper around a Pygame surface that allows you to easilydraw images to the screen (“blit” them).

HIGH QUALITY SOUNDS. SOUNDFONTS, WAVE FILES, SXFS,CUSTOM SIGNITURE DRUMS. Mouse on the track and lil boosie kit. This Sound Kit Contains: Kicks Midi Files Percussion Snares Vox Download.

class Screen
surface

The raw Pygame surface that represents the screen buffer. You canuse this for advanced graphics operations.

clear()

Reset the screen to black.

fill((red, green, blue))

Fill the screen with a solid color.

blit(image, (left, top))

Draw the image to the screen at the given position.

blit() accepts either a Surface or a string as its imageparameter. If image is a str then the named image will beloaded from the images/ directory.

draw.line(start, end, (r, g, b))

Draw a line from start to end.

draw.circle(pos, radius, (r, g, b))

Draw the outline of a circle.

draw.filled_circle(pos, radius, (r, g, b))

Draw a filled circle.

draw.rect(rect, (r, g, b))

Draw the outline of a rectangle.

Takes a Rect.

draw.filled_rect(rect, (r, g, b))

Draw a filled rectangle.

draw.text(text, [pos, ]**kwargs)

Draw text.

There’s an extremely rich API for positioning and formatting text; seeText Formatting for full details.

Free
draw.textbox(text, rect, **kwargs)

Draw text, sized to fill the given Rect.

There’s an extremely rich API for formatting text; seeText Formatting for full details.

Rect¶

The Pygame Rect class is available as a built in. This can be used in avariety of ways, from detecting clicks within a region to drawing a box ontothe screen:

For example, you can draw a box with:

Resource Loading¶

The images and sounds objects can be used to load images and soundsfrom files stored in the images and sounds subdirectories respectively.Pygame Zero will handle loading of these resources on demand and will cachethem to avoid reloading them.

You generally need to ensure that your images are named with lowercase letters,numbers and underscores only. They also have to start with a letter.

File names like these will work well with the resource loader:

These will not work:

Images¶

Pygame Zero can load images in .png, .gif, and .jpg formats. PNG isrecommended: it will allow high quality images with transparency.

We need to ensure an images directory is set up. If your project contains thefollowing files:

Then space_game.py could draw the ‘alien’ sprite to the screen with thiscode:

The name passed to blit() is the name of the image file within the imagesdirectory, without the file extension.

Or using the Actors API,

There are some restrictions on the file names in both cases: they may onlycontain lowercase latin letters, numbers and underscores. This is to preventcompatibility problems when your game is played on a different operating systemthat has different case sensitivity.

Image Surfaces¶

You can also load images from the images directory using the imagesobject. This allows you to work with the image data itself, query itsdimensions and so on:

Each loaded image is a Pygame Surface. You will typically usescreen.blit(...) to draw this to the screen. It also provides handy methodsto query the size of the image in pixels:

class Surface
get_width()

Returns the width of the image in pixels.

get_height()

Returns the height of the image in pixels.

get_size()

Returns a tuple (width, height) indicating the size in pixels of thesurface.

get_rect()

Get a Rect that is pre-populated with the bounds of the imageif the image was located at the origin.

Effectively this is equivalent to:

Sounds¶

Pygame Zero can load sounds in .wav and .ogg formats. WAV is great forsmall sound effects, while OGG is a compressed format that is more suited tomusic. You can find free .ogg and .wav files online that can be used in yourgame.

We need to ensure a sounds directory is set up. If your project contains thefollowing files:

Then drum_kit.py could play the drum sound whenever the mouse is clickedwith this code:

Each loaded sound is a Pygame Sound, and has various methods to play andstop the sound as well as query its length in seconds:

class Sound
play()

Play the sound.

play(loops)

Play the sound, but loop it a number of times.

Parameters:loops – The number of times to loop. If you pass -1 as thenumber of times to loop, the sound will loop forever (oruntil you call Sound.stop()
stop()

Stop playing the sound.

get_length()

Get the duration of the sound in seconds.

You should avoid using the sounds object to play longer pieces of music.Because the sounds sytem will fully load the music into memory before playingit, this can use a lot of memory, as well as introducing a delay while themusic is loaded.

Music¶

Warning

The music API is experimental and may be subject to cross-platformportability issues.

In particular:

  • MP3 may not be available on some Linux distributions.
  • Some OGG Vorbis files seem to hang Pygame with 100% CPU.

In the case of the latter issue, the problem may be fixed by re-encoding(possibly with a different encoder).

A built-in object called music provides access to play music from withina music/ directory (alongside your images/ and sounds/ directories,if you have them). The music system will load the track a little bit at a timewhile the music plays, avoiding the problems with using sounds to playlonger tracks.

Another difference to the sounds system is that only one music track can beplaying at a time. If you play a different track, the previously playing trackwill be stopped.

music.play(name)

Play a music track from the given file. The track will loop indefinitely.

This replaces the currently playing track and cancels any tracks previouslyqueued with queue().

You do not need to include the extension in the track name; for example, toplay the file handel.mp3 on a loop:

music.play_once(name)

Similar to play(), but the music will stop after playing through once.

Mouse On The Track Trill Ent

music.queue(name)

Similar to play_once(), but instead of stopping the current music, thetrack will be queued to play after the current track finishes (or afterany other previously queued tracks).

music.stop()

Stop the music.

music.pause()

Pause the music temporarily. It can be resumed by callingunpause().

music.unpause()

Unpause the music.

music.is_playing()

Returns True if the music is playing (and is not paused), False otherwise.

music.fadeout(duration)

Fade out and eventually stop the current music playback.

Parameters:duration – The duration in seconds over which the sound will be fadedout. For example, to fade out over half a second, callmusic.fadeout(0.5).
music.set_volume(volume)

Set the volume of the music system.

This takes a number between 0 (meaning silent) and 1 (meaning full volume).

music.get_volume()

Get the current volume of the music system.

If you have started a music track playing using music.play_once(), youcan use the on_music_end()hook to do something when themusic ends - for example, to pick another track at random.

Clock¶

Often when writing a game, you will want to schedule some game event to occurat a later time. For example, we may want a big boss alien to appear after 60seconds. Or perhaps a power-up will appear every 20 seconds.

More subtle are the situations when you want to delay some action for a shorterperiod. For example you might have a laser weapon that takes 1 second to chargeup.

We can use the clock object to schedule a function to happen in thefuture.

Let’s start by defining a function fire_laser that we want to run in thefuture:

Then when the fire button is pressed, we will ask the clock to call it forus after exactly 1 second:

Note that fire_laser is the function itself; without parentheses, it isnot being called here! The clock will call it for us.

(It is a good habit to write out times in seconds with a decimal point, like1.0. This makes it more obvious when you are reading it back, that you arereferring to a time value and not a count of things.)

clock provides the following useful methods:

class Clock
schedule(callback, delay)

Schedule callback to be called after the given delay.

Repeated calls will schedule the callback repeatedly.

Parameters:
  • callback – A callable that takes no arguments.
  • delay – The delay, in seconds, before the function should becalled.
schedule_unique(callback, delay)

Schedule callback to be called once after the given delay.

If callback was already scheduled, cancel and reschedule it. Thisapplies also if it was scheduled multiple times: after callingschedule_unique, it will be scheduled exactly once.

Parameters:
  • callback – A callable that takes no arguments.
  • delay – The delay, in seconds, before the function should becalled.
schedule_interval(callback, interval)

Schedule callback to be called repeatedly.

Parameters:
  • callback – A callable that takes no arguments.
  • interval – The interval in seconds between calls to callback.
unschedule(callback)

Unschedule callback if it has been previously scheduled (either becauseit has been scheduled with schedule() and has not yet been called,or because it has been scheduled to repeat withschedule_interval().

Note that the Pygame Zero clock only holds weak references to each callbackyou give it. It will not fire scheduled events if the objects and methods arenot referenced elsewhere. This can help prevent the clock keeping objectsalive and continuing to fire unexpectedly after they are otherwise dead.

The downside to the weak references is that you won’t be able to schedulelambdas or any other object that has been created purely to be scheduled. Youwill have to keep a reference to the object.

Actors¶

Once you have many images moving around in a game it can be convenient to havesomething that holds in one place the image and where it is on screen. We’llcall each moving image on screen an Actor. You can create an actor by supplyingat least an image name (from the images folder above). To draw the alien talkedabout above:

You can move the actor around by setting its pos attribute in an update:

And you may change the image used to draw the actor by setting its imageattribute to some new image name:

Mouse On The Track Beats

Actors have all the same attributes and methods as Rect,including methods like .colliderect() which can be used to test whethertwo actors have collided.

Positioning Actors¶

If you assign a new value to one of the position attributes then the actor willbe moved. For example:

will position the alien so its right-hand side is set to WIDTH.

Similarly, you can also set the initial position of the actor in theconstructor, by passing one of these as a keyword argument: pos,topleft, topright, bottomleft, bottomright, midtop,midleft, midright, midbottom or center:

This can be done during creation or by assigning a pair of x, y co-ordinates.For example:

Changing center=(100,100) to midbottom=(100,200) gives you:

If you don’t specify an initial position, the actor will initially bepositioned in the top-left corner (equivalent to topleft=(0,0)).

Anchor point¶

Actors have an “anchor position”, which is a convenient way to position theactor in the scene. By default, the anchor position is the center, so the.pos attribute refers to the center of the actor (and so do the x andy coordinates). It’s common to want to set the anchor point to anotherpart of the sprite (perhaps the feet - so that you can easily set the Actor tobe “standing on” something):

anchor is specified as a tuple (xanchor,yanchor), where the values canbe floats or the strings left, center/middle, right, top orbottom as appropriate.

Rotation¶

The .angle attribute of an Actor controls the rotation of the sprite, indegrees, anticlockwise (counterclockwise).

The centre of rotation is the Actor’s anchor point.

Note that this will change the width and height of the Actor.

For example, to make an asteroid sprite spinning slowly anticlockwise inspace:

To have it spin clockwise, we’d change update() to:

As a different example, we could make an actor ship always face the mousepointer. Because angle_to() returns 0 for “right”, the sprite weuse for “ship” should face right:

Remember that angles loop round, so 0 degrees 360 degrees 720 degrees.Likewise -180 degrees 180 degrees.

Distance and angle to¶

Actors have convenient methods for calculating their distance or angle to otherActors or (x,y) coordinate pairs.

Actor.distance_to(target)

Return the distance from this actor’s position to target, in pixels.

Actor.angle_to(target)

Return the angle from this actor’s position to target, in degrees.

This will return a number between -180 and 180 degrees. Right is 0 degreesand the angles increase going anticlockwise.

Therefore:

  • Left is 180 degrees.
  • Up is 90 degrees.
  • Down is -90 degrees.

The Keyboard¶

You probably noticed that we used the keyboard in the above code.If you’d like to know what keys are pressed on the keyboard, you can query theattributes of the keyboard builtin. If, say, the left arrow is held down,then keyboard.left will be True, otherwise it will be False.

There are attributes for every key; some examples:

The full set of key constants is given in the Buttons and Keysdocumentation, but the attributes are lowercase, because these are variablesnot constants.

Deprecated since version 1.1: Uppercase and prefixed attribute names (eg. keyboard.LEFT orkeyboard.K_a) are now deprecated; use lowercase attribute namesinstead.

New in version 1.1: You can now also query the state of the keys using the keyboard constantsthemselves:

Animations¶

You can animate most things in pygame using the builtin animate(). Forexample, to move an Actor from its current position on thescreen to the position (100,100):

animate(object, tween='linear', duration=1, on_finished=None, **targets)

Animate the attributes on object from their current value to thatspecified in the targets keywords.

Parameters:
  • tween – The type of tweening to use.
  • duration – The duration of the animation, in seconds.
  • on_finished – Function called when the animation finishes.
  • targets – The target values for the attributes to animate.

The tween argument can be one of the following:

‘linear’Animate at a constant speed from start to finish
‘accelerate’Start slower and accelerate to finish
‘decelerate’Start fast and decelerate to finish
‘accel_decel’Accelerate to mid point and decelerate to finish
‘end_elastic’Give a little wobble at the end
‘start_elastic’Have a little wobble at the start
‘both_elastic’Have a wobble at both ends
‘bounce_end’Accelerate to the finish and bounce there
‘bounce_start’Bounce at the start
‘bounce_start_end’Bounce at both ends

The animate() function returns an Animation instance:

class Animation
stop(complete=False)

Stop the animation, optionally completing the transition to the finalproperty values.

Parameters:complete – Set the animated attribute to the target value.
running

This will be True if the animation is running. It will be Falsewhen the duration has run or the stop() method was called beforethen.

on_finished

Mouse On Tha Track Drum Kit

You may set this attribute to a function which will be calledwhen the animation duration runs out. The on_finished argumentto animate() also sets this attribute. It is not called whenstop() is called. This function takes no arguments.

Tone Generator¶

Pygame Zero can play tones using a built-in synthesizer.

tone.play(pitch, duration)

Play a note at the given pitch for the given duration.

Duration is in seconds.

The pitch can be specified as a number in which case it is the frequencyof the note in hertz.

Trill Ent Mouse On The Track Mixtape

Alternatively, the pitch can be specified as a string representing a notename and octave. For example:

  • 'E4' would be E in octave 4.
  • 'A#5' would be A-sharp in octave 5.
  • 'Bb3' would be B-flat in octave 3.

Creating notes, particularly long notes, takes time - up to severalmilliseconds. You can create your notes ahead of time so that this doesn’t slowyour game down while it is running:

tone.create(pitch, duration)

Create and return a Sound object.

The arguments are as for play(), above.

This could be used in a Pygame Zero program like this:

As a musician, I’ve long been a fan of Apple’s GarageBand software for its ease of use and powerful recording and editing tools. It’s often my go-to software for demoing songs with my band, due to how quickly you can set up a new project and start recording.

But one gripe I’ve had about GarageBand for years, throughout all of its iterations, is its lack of a volume control for the built-in metronome.

GarageBand’s metronome button is found at the top of the project window, and you can turn it on or off—that’s all. When on, you hear a short repeating click that matches the tempo of your project, and by playing along with that beat as you record, you’ll be able to stay in time with the other tracks in your project.

The problem is that this click sound becomes increasingly difficult to hear as you add more tracks, especially when recording loud instruments like guitars or drums. And, again, there’s no way to increase the volume level of the click.

So my solution has been to always first create my own click track in any new project I’m working on. Placing a click on its own track allows me to adjust its volume as needed.

But rather than creating a click track from scratch every time I start a new project, I instead have a version of the click I’ve saved as a loop in GarageBand, which allows me to drag the click into any project and automatically match the current tempo.

How to create a click loop

If you’d like to create your own click loop, start in an empty GarageBand project, and create a Software Instrument track. With that track selected, go to the Library pane on the right, choose Drum Kit and select one of the built-in drum kits. For this example, I used the Brooklyn kit.

Then, it’s a matter of finding a sound to use as the click. A short, percussive sound works best, like a rim shot or clap. You should avoid longer sounds or sounds that have their own tones or notes, so your click doesn’t clash with your song.

To find a sound, open the Musical Typing keyboard under the Window menu.

Set the Velocity to 127 to ensure that the sound will be recorded at its loudest possible setting. To use the rim shot sound for this example, set the Octave to C1. Pressing the W key on your keyboard should now give you a rim shot. Now you’re ready to record.

Your goal is to play quarter notes to the current tempo, basically matching the beat of GarageBand’s metronome. So make sure the metronome is active by clicking its button at the top of the window. You’ll probably want to leave the count-in option next to it on as well.

Make sure the playhead is at the beginning of the track. When you’re ready, click the Record button (or press R) to start recording, and play at least 8 beats (two measures) along with the beat. Press the Spacebar to stop recording.

Next, since you’ll be relying on the click track to have a perfect beat for all your future recordings, you’ll want to make sure its timing is perfect. Select the region you just recorded, and open the Editor by clicking its button at the top left of the window.

In the Editor pane, under the Region tab, set the Time Quantize menu to ¼ Note and make sure its Strength is set to 100, to ensure that your notes are perfectly in time.

At this point, you could simply place your cursor in the upper right-hand corner of the region and drag to the right to create a looping click track for this particular project, but since we want to make the click available for all projects, we’ll save it as a loop.

To do so, click the Loop Library button in the upper right-hand corner of the window. Then simply drag the region into the bottom section of the Loop Library pane. That opens a window where you can name and classify this loop.

I suggest using the name Click Track. Make sure the Type is set to Loop, in order to ensure that this loop will automatically conform to the tempo of any project you drag it into. You can ignore the rest of the options in this window, and click Create.

And that’s it! You can close the project without saving.

Test your click track by creating a new project. Perform a search in the Loop Library for “click track” to find your loop, and drag it into your project. Then place your cursor in the upper right-hand corner of the region and drag it out to the right to loop it continuously for the length of your song. If you don’t know how long the song is going to be, just drag the loop out to an estimated length—you can always increase or decrease its length as necessary.

And you now have a perfect metronome click track, whose volume you can control with the track fader, and which you’ll have a much easier time hearing than GarageBand’s built-in metronome.

*Image by Death to the Stock Photo

Want to become a master of GarageBand? Check out Chow’s course, GarageBand Essential Training.