Python交互小游戏(四):Memory——Mouse input,list methods,dictionaries

1 Mouse Input

例 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Examples of mouse input

import simplegui
import math

# intialize globals
WIDTH = 450
HEIGHT = 300
ball_pos = [WIDTH / 2, HEIGHT / 2]
BALL_RADIUS = 15
ball_color = "Red"

# helper function
def distance(p, q):
return math.sqrt( (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)

# define event handler for mouse click, draw
def click(pos):
global ball_pos, ball_color
if distance(pos, ball_pos) < BALL_RADIUS:
ball_color = "Green"
else:
ball_pos = list(pos) # pos是一个tuple,而tuple不能被修改
ball_color = "Red"

def draw(canvas):
canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "Black", ball_color)

# create frame
frame = simplegui.create_frame("Mouse selection", WIDTH, HEIGHT)
frame.set_canvas_background("White")

# register event handler
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)

# start frame
frame.start()

例 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Examples of mouse input

import simplegui
import math

# intialize globals
width = 450
height = 300
ball_list = []
ball_radius = 15
ball_color = "Red"

# helper function
def distance(p, q):
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)

# define event handler for mouse click, draw
def click(pos):
remove = [] # 不能在下面的循环中直接删除ball_list的元素
for ball in ball_list:
if distance(ball, pos) < ball_radius:
remove.append(ball)

if remove == []:
ball_list.append(pos)
else:
for ball in remove:
ball_list.pop(ball_list.index(ball))

def draw(canvas):
for ball in ball_list:
canvas.draw_circle([ball[0], ball[1]], ball_radius, 1, "Black", ball_color)

# create frame
frame = simplegui.create_frame("Mouse selection", width, height)
frame.set_canvas_background("White")

# register event handler
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)

# start frame
frame.start()

注意:在遍历一个 list 时,千万不要从里面删除东西,如果需要删除东西,记录下你想要删除的东西,并随后删除它们