Use Python with Sprites

By using Python with Sprites, you may:

  • Learn Python with your previous Scratch knowledge
  • Write big progarms (like algorithms) easily
  • Use complex data structures like dictionaries to do things that are not easy in Scratch.

In mBlock 5, Python can almost do whatever Scratch can do.
You can control the movement and appearence of your sprite. You may also draw pictures.
Using broadcasting and Sprite Variables, Python code can interact with the Python or Block code in other sprites.

Start Using Python

Start using Python by switching the programming mode from "Blocks" to "Python" (Insert Pics)

Note: please make sure that a sprite, not a hardware device, is currently selected. (Insert Pics)

This is an example of the Python code used in a Sprite.

from mblock import *

sprite.pencolor('red')
sprite.pendown()

for i in range(5):
    sprite.forward(200)
    sprite.right(144)

When the code is complete, click "Run" to run your Python code. (Insert Pic)

Convert Blocks to Python

(Insert Pic)

Moving a Sprite

forward(distance)

Tell the Sprite to move forward for a certain distance towards
the current facing direction.

sprite.forward(50)

backward(distance)

Tell the Sprite to move backward for a certain distance from the current facing direction.

sprite.backward(50)

right(degrees)

Tell the sprite to turn right for certain degrees.

sprite.right(90)

left(degrees)

Tell the Sprite to turn left for certain degrees.

sprite.left(90)

direction

Use the "direction" attribute to get the current facing direction of the Sprite

sprite.direction = 90 # set the facing direction to 90 degrees
sprite.direction = sprite.direction + 10 # tell the sprite to rotate clockwise for 10 degrees
print(sprite.direction) # now the facing direction will be 100

towards(sprite_name)

Tell the Sprite to face another sprite (the sprite_name is a string)

sprite.towards("Panda")
sprite.towards('mouse') # 朝向鼠标指针

bounce()

Tell the Sprite to bounce when it touches the edge of the stage.

while True:
    sprite.forward(50)
    sprite.bounce()

rotation_mode(mode)

Set the rotation mode of the Sprite.
"mode" is a boolean value, could be one of these:

  • 'left-right': the image of the Sprite only turns left or right
  • 'all-around' or True: the Sprite image could face any direction
  • 'none' or False: the Sprite image will not rotate.
sprite.rotation_mode('all-around')

Position and Coordinates

goto(x, y) | goto(place)

Tell the sprite to move to a certain (x, y) coordinate.
x, y is numbers. You may use the following special string value:

  • "random": move to a random location on the stage.
  • "mouse": move to the location of the mouse.
sprite.goto(30,60)
sprite.x # =30
sprite.setpos(0,0)
sprite.y # =0
sprite.goto("random") # move to a random location
sprite.goto("mouse") # move to the mouse pointer

glide(x, y, duration=5) | glide(location, duration=5)

Tell the Sprite to slide to a specific location in a certain duration.
You may also use the following string to denote the special location:

  • "random": a random location on the stage
  • "mouse": the location of the mouse pointer
sprite.glide(30, 60, 5) # Tell the sprite to move to (30, 60) in 5 seconds
sprite.glide("random", 2) # move to a random location in 2 seconds
sprite.glide("mouse", 2) # move to the pointer in 2 seconds

coordinate of the sprite: x, y

Get the coordinate of the Sprite, or set the (x, y) coordinate of the Sprite on the stage

sprite.x # get the x location of the Sprite
sprite.y # get the y location of the Sprite
sprite.x = 50 # set the x location of the Sprite to 50
sprite.y = 60 # set the y location to 60
sprite.y = sprite.y + 10 # increase the y coordinate by 10, that means move the Sprite up for 10
print(sprite.x) # print the x location of the sprite (50 in this case)
print(sprite.y) # print the y location of the sprite (70 in this case)

Appearances

say(text, duration=0)

Tell the Sprite to "say" some text.
If the duration is not specified, the text box will not disappear;
otherwise, it will disappear after a certain duration.

sprite.say("nice to meet you", 5)
sprite.say("hello world")

think(text, duration=0)

Tell the Sprite to "think" for a certain text.
If the duration is not specified, the text box will not disappear;
otherwise, it will disappear after a certain duration.

sprite.think("nice to meet you", 5)
sprite.think("hello world")

hide()

Hide the sprite

sprite.hide()

show()

Show the sprite

sprite.show()

set_costume(costume_name)

Change the costume of the sprite. The costome_name must exist in the Sprite, otherwise nothing will happen.

sprite.set_costume("Panda1")

next_costume()

Switch the costume of the sprite to the next costume.

sprite.next_costume()

set_backdrop(background_name)

Switch the backdrop of the Stage. the background_name must exist in the projects, otherwise nothing will happen.

sprite.set_backdrop("Party")

next_backdrop()

Switch the backdrop to the next backdrop

sprite.next_costume()

set_effect(effect, value)

Set the effect strength to a certain value. The effect could be one of these:

  • color
  • fisheye
  • whirl
  • pixelate
  • mosaic
  • brightness
  • ghost
sprite.set_effect("color", 10) # Set the color value to 10

change_effect_by(effect, value)

Increase the effect strength by a certain value. The effect could be one of these:

  • color
  • fisheye
  • whirl
  • pixelate
  • mosaic
  • brightness
  • ghost
sprite.change_effect_by("color", 10) # Increase the "color" effect by 10

clear_effect()

Clear all the Sprite Effects.

sprite.clear_effect()

size

Set or get the size proportion of the Sprite
100 is the original size (100%) of the Sprite.

sprite.size = 200 # enlarge the sprite to its 200%
sprite.size = sprite.size + - 50 # shrink the sprite by 50%
print(sprite.size) # print the proportional size of the sprite, 150 in this case

Play Sound

play(sound_effect_name)

Play a sound effect. The sound effect name must exist in the project,
otherwise nothing will happen

sprite.play("meow") # play the "meow" sound

play_until_done(sound_effect_name)

Play a sound effect, and run next statement when it is done.
The sound effect name must exist in the project, otherwise nothing will happen

sprite.play_until_done("meow") # play the "meow" sound

stop_sound()

Stop playing all the sound

sprite.stop_sound()

play_drum(instrument_number, beats)

Play a drum beat. Instrument number ranges from 1 to 18.
The "beats" refers to the duration of the drum beat.

sprite.play_drum(1, 0.25)

rest(beats)

Stop playing sound for a certain beat.

sprite.rest(0.5)

play_note(note_number, beats=0.25)

Play a musical note. The note_number is a integer (MIDI number)
The higher the number, the higher the pitch.
"beats" is the duration of the sound.

sprite.play_note(60, 0.25) # play a "C" note in the third level

set_inst(instrument_number)

Set the current instrument. The instrument number ranges from 1 to 21. TODO: Table of instruments

sprite.set_inst(1) # set the musical instrument to piano

set_sfx(sound_effect_name, value)

Set the value of the sound effect.

sprite.set_sfx('PITCH', 10) # set the value of the sound effect as 10

change_sfx_by(sound_effect_name, value)

Change the value of the sound effect.

sprite.change_sfx_by('PITCH', 10) # increase the value of the sound effect by 10

clear_sfx()

Clear all sound effects.

sprite.clear_sfx() # clear all sound effects

volume

Use volume to get or change the sound volume.
The volume value is a number ranged from 1 to 100.

sprite.volume = 50 # set the volume to 50
sprite.volume = sprite.volume + 10 # change the volume by 10%
print(sprite.volume) # 60

set_tempo(beats_per_minute) | change_tempo_by(beats_per_minute)

Use the tempo to set beat-per-minute(bpm) of music notes and sound effects.

sprite.set_tempo(60)
sprite.change_tempo_by(20)

Turtle Graphics

pendown()

Put down the pen. A trail will be drawn by the sprite when the pen is down.

sprite.pendown()

penup()

Lift up the pen. No trail will left behind when the Sprite moves then.

sprite.penup()

stamp()

Leave an image of the sprite at the current position, like using a stamp.

sprite.stamp()

pencolor(color) | pencolor(red, green, blue)

Change the color of the pen. The color could be:

  1. One of the follow strings: "red", "orange", "yellow", "green", "cyan", "blue", "purple", "black", "white", "grey"
  2. Hex code start with "#", like "#FF0000"
  3. A tuple of RGB value
  4. RGB values as parameters
sprite.pencolor("red")
sprite.pencolor("#FF0000")
sprite.pencolor(255, 0, 0) # 效果是相同的

pencolor_effect(effect_name, value)

set the pen effect (0-100)
the effect_name could be a string of:

  • "hue"
  • "saturation"
  • "brightness"
  • "transparency"
sprite.pencolor_effect("hue", 60)

change_pencolor_effect_by(effect_name, value)

Change the pen effect (0-100)
the effect_name could be a string of:

  • "color"
  • "saturation"
  • "brightness"
  • "transparency"
sprite.change_pencolor_effect_by("hue", 10)

change_pencolor_shade_by(value)

change the shade value of the pen color.

sprite.change_pencolor_shade_by(10)

clear()

Clear everything in the canvas drawn by the sprite.

sprite.clear()

pensize(pen_size)

Set the size of the pen.

sprite.pensize(1)

change_pensize_by(value)

Change the pen size by a certain value.

sprite.change_pensize_by(1) # increase the pen size by 1

Use Events

You can use events in Python to interact with the keyboard or the mouse
by adding a mark("decorator") before the function:

from mblock import *

@event.greenflag # the following function will run when the green flag is clicked
def on_green_flag(): # you may choose your own function name
    print("绿旗被按下了") # here put the code that will run after the green flag is clicked.

@greenflag

when the green flag is clicked/tapped

@event.greenflag
def on_green_flag():
    print("green flag is clicked!")

@keypressed(key_name)

When a certain key on the keyboard is pressed, fire the event. The key_name could be:
"a", "A", "1", "enter", "space", "backspace".

@event.keypressed("space")
def on_space_key():
    print("the space key is pressed")

@clicked

Trigger the event when the Sprite is clicked.
mousedown and mouseup might be added in the future.

@event.clicked
def on_clicked():
    print("the sprite is clicked")

@backdrop_enter(backdrop_name)

When the backdrop is set to the certain backdrop, trigger this event.

@event.backdrop_enter("Party")
def on_backdrop_enter():
    print("the backdrop is switched to Party")

@when_greater_than(parameter_name, value)

when a parameter with the certain name is greater than a value, trigger this event.
the parameter name could be:

  • "TIMER": the internal timer of Scratch
  • "VOLUME"(not implemented yet): the microphone volume.
@event.when_greater_than("timer", 10)
def on_backdrop_enter():
    print("10 seconds has been passed")

broadcast(event_name)

broadcast an event to the mBlock system.

sprite.broadcast("game_start")

@received(event_name)

when an event with a certain event_name is received, trigger the event.

@event.received("game_start")
def when_game_start():
    print("the game has been started")

Global Variables

You can use global variables to communicate with other spirtes' code
(whether it is in blocks or Python)
You can even use Python codes to communicate with robots or other devices.

set_variable(variable_name, value)

Set the value of a Scratch block variable.
The varible must exist in the block editor;
otherwise nothing will happen (other than producing a warning in the console).

sprite.set_variable("score", 50)

get_variable(variable_name)

Get the value of the varible.
If the variable name does not exist, return None.

print(sprite.get_variable("score"))

Clone Sprites and Flow Control

clone(sprite_name=None)

Clone a sprite.
Returns the cloned sprite (Sprite Object)
(Not implemented yet) If a Sprite name is not provided, clone the sprite itself.

sprite.clone() # clone myself
sprite.clone("Panda") # clone a panda sprite

delete_clone()

If the sprite is a clone, delete myself.

sprite.delete_clone()

stop_all() / stop_this() / stop_other()

Stop all sprites/(not implemented yte)stop the scripts in this sprite/(not implemented yte)stop the scripts in other sprites

sprite.stop_all() # stop all sprites on the stage

Basic Inputs and Outputs

print(content)

Print some content to the console at the bottom of the Python editor. Used to debug.

print("hello world")

input(prompt)

Prompt the user to input text at the stage.

name = sprite.input("what's your name?")
sprite.say("your name is:" + name)

Sprite Properties

touching(sprite_name)

Tell if the Sprite is touching other Sprites, the mouse, or the edge of the stage.
The result is True of False

print(sprite.touching("Panda")) # True if the Sprite is touching the "Panda" sprite
print(sprite.touching_mouse()) # True if the Sprite is touching the mouse pointer
print(sprite.touching_edge()) # True if the Sprite is touching the edge of the stagew

touching_color(color) | touching_color(red, green, blue) | touching_color(sprite_color, screen_color)

Tell if the Sprite is touching another color. The color could be:

  1. Hex values start with "#", like "#FF0000"
  2. A Tuple of RGB values.
  3. RGB values in numbers

The result is True of False

print(sprite.touching_color("#ff0000")) # Tell if the sprite is touching the red color
print(sprite.touching_color(255, 0, 0)) # the same
color = (255, 0, 0)
print(sprite.touching_color(color)) # the same
print(sprite.touching_color("#ff0000", "#00ff00")) # Tell if the red part of the sprite is touching the green part of the stage.

distance_to(sprite_name)

Get the distance from the Sprite to the another Sprite or the mouse

sprite.distance_to('_mouse_') # get the distance from the Sprite to the mouse
sprite.distance_to('Accordion3')

is_keypressed(key_name)

Tell if a certain key is pressed(returns True or False) Examples of key names: "a", "A", "1", "enter", "space", "backspace"

print(sprite.is_keypressed("space")) # When the space key is pressed, return True.

is_mousedown

Tell whether the mouse is down. Return True or False.

print(sprite.is_mousedown()) # 若执行当时鼠标被按下,返回True

Sprite Properties

A Sprite also has the following properties:

  • mousex: the mouse's x coordinate on the stage
  • mousey: the mouse's y coordinate on the stage
  • loudness: the loudness of the microphone
  • timer: the current value of the timer
  • current(unit): get the component of current time. "unit" could be: year | month | date | day_of_week | hour | minute | second: the current time
  • days_since_2000: days passed since 2000
print("%d, %d" % (sprite.mousex, sprite.mousey)) # output the mouse's coordinate
print(sprite.loudness) # output the current loudness
print(sprite.timer) # output the seconds from the timer
print("%d-%d-%d %d:%d:%d" % (sprite.current('year'), sprite.current('month'), sprite.current('date'), sprite.current('hour'), sprite.current('minute'), sprite.current('second')))
print("day of week: ", sprite.current('day_of_week')) # output the current day of the week
print("days since 2000", sprite.days_since_2000)

reset_timer()

reset the timer

sprite.reset_timer()
print(sprite.timer) # output zero, since the timer has been reset.

results matching ""

    No results matching ""