1 defDraw (c):2 GlobalPaddle1_pos, Paddle2_pos3 4Paddle_width = 805 6 ifPADDLE_WIDTH/2 <= Paddle1_pos + paddle1_vel <= WIDTH-PADDLE_WIDTH/2:7Paddle1_pos + =Paddle1_vel8 ifPADDLE_WIDTH/2 <= Paddle2_pos + paddle2_vel <= WIDTH-PADDLE_WIDTH/2:9Paddle2_pos + =Paddle2_velTen OneC.draw_line ([Width/2, 0],[WIDTH/2, height], 1," White") A -C.draw_line ([4, PADDLE1_POS-PADDLE_WIDTH/2], [4, PADDLE1_POS+PADDLE_WIDTH/2], 4," White") -C.draw_line ([Width-4, PADDLE2_POS-PADDLE_WIDTH/2], [Width-4, PADDLE2_POS+PADDLE_WIDTH/2], 4," White")
Week 4 Project Pong to draw a skateboard and simulate its movement statements, note that the IF statement (Control skateboard does not move out of the canvas range) variables are pos+vel, that is, to keep the updated state within the canvas.
The code style is now more concise by introducing paddle class.
1 classPaddle:2 def __init__(Self, loc, POS, vel):3Self.loc =Loc4Self.pos =POS5Self.vel =vel6Self.width = 807 8 defMove (self):9 ifSELF.WIDTH/2 <= Self.pos + self.vel <= WIDTH-SELF.WIDTH/2:TenSelf.pos + =Self.vel One A defDraw (C, self): -C.draw_line ([Self.loc, SELF.POS-SELF.WIDTH/2], paddle_thickness," White") - the defDraw (c): - Paddle1.move () - Paddle2.move () - +C.draw_line ([Width/2, 0],[WIDTH/2, height], 1," White") - + Paddle1.draw (c) APaddle2.draw (c)
For the original key handler (response keyboard function), the original code
1 defKeyDown (key):2 GlobalPaddle1_vel, Paddle2_vel3 ifKey = = Simplegui. key_map[" up"]:4Paddle2_vel-= 25 elifKey = = Simplegui. key_map[" Down"]:6Paddle2_vel + = 27 elifKey = = Simplegui. key_map["W"]:8Paddle1_vel-= 29 elifKey = = Simplegui. key_map["s"]:TenPaddle1_vel + = 2
Introduce dictionary and a iteration, i.e.
1Inputs = {" up": [1,-2],2 " Down": [1, 2],3 "W": [0,-2],4 "s": [0, 2]}5 6 defKeyDown (key):7 forIinchInputs:8 ifKey = =Simplegui. Key_map[i]:9Paddle_vel[inputs[i][0]] + = inputs[i][1]
It may seem complicated at first, but if you see the meaning of inputs[i] instantaneously, such as when I is up, inputs[i] stands for [1,-2], so inputs[i][0] is 1,input[i][1] 2
So the last statement represents paddle_vel[1] + =-2 that is, paddle1 speed becomes 2 upwards.
The last one, try to use the relationship between the variables to simplify the code, as far as possible without magic costant (full text is calculated by hand numbers)
Interactive Programming in Python Week7 Code style