IIPP Week 4 - Lists, keyboard input, the basics of modelling motion

Week 4a - Basics of Lists

List

Create

none, string, lists

Access

len
slice

Update

# List reference problem

###################################################
# Student should enter code below

a = [5, 3, 1, -1, -3, 5]
b = a
c = list(a)
c[1] = 0
b[0] = 0
print a
print b
print c


###################################################
# Explanation

# The assignment b = a created a second reference to a.
# Setting b[0] = 0 also mutated the list that both 
# a and b reference.  As a result, a[0] == 0.

# See the Programming Tips videos for a more detail 
# explanation and examples

Keyboard Input

# control the position of a ball using the arrow keys

import simplegui

# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20

ball_pos = [WIDTH / 2, HEIGHT / 2]

# define event handlers
def draw(canvas):
    canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")

def keydown(key):
    vel = 4
    if key == simplegui.KEY_MAP["left"]:
        ball_pos[0] -= vel
    elif key == simplegui.KEY_MAP["right"]:
        ball_pos[0] += vel
    elif key == simplegui.KEY_MAP["down"]:
        ball_pos[1] += vel
    elif key == simplegui.KEY_MAP["up"]:
        ball_pos[1] -= vel        

# create frame 
frame = simplegui.create_frame("Positional ball control", WIDTH, HEIGHT)

# register event handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)

# start frame
frame.start()

Tips

  • some key like shift in simplegui KEY_MAP will become a number
  • pressing a key for a long time will just call the keyboard handler once

Week 4b - Keyboard Control

Velocity Control

using draw handler to control the velocity can keep the ball moving

Global & Local for lists

a = [4, 5, 6]

def mutate_part(x):
    a[1] = x #Global, don't need to declare glabal

def assign_whole(x):
    a = x #local

def assign_whole_global(x):
    global a
    a = x #a become an int

mutate_part(100)

assign_whole(200)

assign_whole_global(300)

Tuple

  • cannot change element in it
  • string is a type of tuple
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值