首页 > 代码库 > Interactive Programming in Python Week7 Code style

Interactive Programming in Python Week7 Code style

 1 def draw(c): 2     global paddle1_pos, paddle2_pos 3      4     paddle_width = 80 5  6     if paddle_width/2 <= paddle1_pos + paddle1_vel <= width - paddle_width/2: 7         paddle1_pos += paddle1_vel 8     if paddle_width/2 <= paddle2_pos + paddle2_vel <= width - paddle_width/2: 9         paddle2_pos += paddle2_vel10         11     c.draw_line([width/2, 0],[width/2, height], 1, "White")12     13     c.draw_line([4, paddle1_pos-paddle_width/2], [4, paddle1_pos+paddle_width/2], 4, "White")14     c.draw_line([width-4, paddle2_pos-paddle_width/2], [width-4, paddle2_pos+paddle_width/2], 4, "White")

week 4 项目pong中绘制滑板以及模拟其移动的语句,注意if语句(控制滑板不移动出画布范围)里的变量是pos+vel,即要保持更新后的状态在画布内。

现在通过引入paddle class 来使代码风格更为简练。

 1 class Paddle: 2     def __init__(self, loc, pos, vel): 3         self.loc = loc 4         self.pos = pos 5         self.vel = vel 6         self.width = 80 7      8     def move(self): 9         if self.width/2 <= self.pos + self.vel <= width - self.width/2:10             self.pos += self.vel11             12     def draw(c, self):13         c.draw_line([self.loc, self.pos-self.width / 2], PADDLE_THICKNESS, "White")14 15 def draw(c):16     paddle1.move()17     paddle2.move()18         19     c.draw_line([width / 2, 0],[width / 2, height], 1, "White")20     21     paddle1.draw(c)22     paddle2.draw(c)

对于原来的key handler(响应键盘的function),原来的code

 1 def keydown(key): 2     global paddle1_vel, paddle2_vel 3     if key == simplegui.KEY_MAP["up"]: 4         paddle2_vel -= 2 5     elif key == simplegui.KEY_MAP["down"]: 6         paddle2_vel += 2 7     elif key == simplegui.KEY_MAP["w"]: 8         paddle1_vel -= 2 9     elif key == simplegui.KEY_MAP["s"]:10         paddle1_vel += 2

引入Dictionary 和一个iteration,即

1 inputs = {"up": [1, -2],2           "down": [1, 2],3           "w": [0, -2],4           "s": [0, 2]}5 6 def keydown(key):7     for i in inputs:8         if key == simplegui.KEY_MAP[i]:9             paddle_vel[inputs[i][0]] += inputs[i][1]

初看起来有些复杂 ,但是若看清inputs[i]的含义就瞬间通畅,比如当i是up时,inputs[i]代表[1,-2],所以inputs[i][0]就是1,input[i][1]则是-2

所以最后一条语句 代表 paddle_vel[1] += -2 即paddle1的速度变成朝上的2.

 

最后一条 ,尽量用通过变量间的关系来简化代码,尽量不用magic costant(满篇都是用手算出来的数字)

Interactive Programming in Python Week7 Code style