16 步:让我们使用事件处理程序将新功能链接到按键,以使用箭头键控制播放器。

  • 在图形中,转到.将Sprite Key Event Handler拖到 main 函数的底部。
  • 在该行的开头,将sprite更改为player
  • 第一个参数是键盘上按键的代码。将左箭头键的"right"替换为"left"
  • 第二个参数是按键被按下时调用的函数。将right_key替换为move_left

To navigate the page using the TAB key, first press ESC to exit the code editor.

def set_stage(): """ Sets up the stage for the game """ stage.set_background("soccerfield") stage.disable_floor() def add_player(): """ Adds a player to the stage for the user to control """ player = codesters.Sprite("player1") player.go_to(0, -180) player.set_size(0.75) return player def add_ball(): """ Adds a ball to the stage and sets its attributes """ ball = codesters.Sprite("soccerball") ball.set_y_speed(-8) def head_ball(sprite, hit_sprite): """ Detects collisions between the player and ball """ my_var = hit_sprite.get_y_speed() hit_sprite.set_y_speed(-my_var + 1) my_var = hit_sprite.get_x_speed() hit_sprite.set_x_speed(my_var + 1) def move_left(sprite): """ Moves the player left """ sprite.move_left(50) def main(): """ Sets up the program and calls other functions """ set_stage() player = add_player() add_ball() player.event_collision(head_ball) main()
  • Run Code
  • 提交作品
  • 下个活动
  • Show Console
  • Reset Code Editor
  • Codesters How To (opens in a new tab)