-
Notifications
You must be signed in to change notification settings - Fork 1
/
弹珠游戏.py
94 lines (70 loc) · 2.35 KB
/
弹珠游戏.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from tkinter import *
from random import randint
def getRandomColor():
color = "#"
for j in range(6):
color += toHexChar(randint(0, 15))
return color
def toHexChar(hexValue):
if 0 <= hexValue <= 9:
return chr(hexValue + ord('0'))
else:
return chr(hexValue - 10 + ord('A'))
class Ball:
def __init__(self):
self.x = 0
self.y = 0
self.dx = 2
self.dy = 2
self.radius = 3
self.color = getRandomColor()
class BounceBalls:
def __init__(self):
self.ballList = []
window = Tk()
window.title("弹珠游戏")
self.width = 350
self.height = 150
self.canvas = Canvas(window, bg="white", width=self.width, height=self.height)
self.canvas.pack()
frame = Frame(window)
frame.pack()
btStop = Button(frame, text="Stop", command=self.stop)
btStop.pack(side=LEFT)
btResume = Button(frame, text="Resume", command=self.resume)
btResume.pack(side=LEFT)
btAdd = Button(frame, text="+", command=self.add)
btAdd.pack(side=LEFT)
btRemove = Button(frame, text="-", command=self.remove)
btRemove.pack(side=LEFT)
self.sleepTime = 100
self.isStopped = False
self.animate()
window.mainloop()
def stop(self):
self.isStopped = True
def resume(self):
self.isStopped = False
self.animate()
def add(self):
self.ballList.append(Ball())
def remove(self):
self.ballList.pop()
def animate(self):
while not self.isStopped:
self.canvas.after(self.sleepTime)
self.canvas.update()
self.canvas.delete("ball")
for ball in self.ballList:
self.redisplayBall(ball)
def redisplayBall(self, ball):
if ball.x > self.width or ball.x < 0:
ball.dx = -ball.dx
if ball.y > self.height or ball.y < 0:
ball.dy = -ball.dy
ball.x += ball.dx
ball.y += ball.dy
self.canvas.create_oval(ball.x - ball.radius,
ball.y - ball.radius, ball.x + ball.radius,
ball.y + ball.radius, fill=ball.color, tags="ball")
BounceBalls()