目录
题目要求:
提供用户界面,根据用户输入,生成5组或6组双色球号码数字, 显示在屏幕上,注意不能出现重复的一组数,如果用户没有正确输入组数,提示用户输入错误,效果如下。
设计步骤:
逐步拆分问题,从易到难。
1、绘制一排小球:
用一个生成号码函数生成红球和蓝球对应的随机号码,另一个绘图函数用于绘制小球并将对应的数字标注在小球中心。
2、绘制多排小球:
控制每组号码数字不能重复。
3、编写用户界面:
利用 tkinter库编写对应的用户界面。
4、适当美化
具体解决:
1、如何将号码标注在小球中心?
generate_lotto_numbers()函数生成的包含随机号码通过元组的形式(前面的是红球的随机数字列表,后面的是蓝球的随机整型数字,(如([5, 12, 18, 22, 25, 30], 8)))传递给draw_lotto_balls()函数,根据索引 i 从 numbers 列表中取出对应的字符串号码,然后标注在圆形的中心位置。
2、如何控制小球整齐显示?
每个小球的位置通过其圆心坐标来显示,设置一个初始的间隙值1.2,根据小球的索引,用索引*间隙值找到小球对应x的坐标,目前我们只需要一排小球,Y轴坐标统一设置为0。
图片展示:
代码无注释版 :
import random
import matplotlib.pyplot as plt
# 生成彩票号码
def generate_lotto_numbers():
red_balls = random.sample(range(1, 33), 6)
blue_ball = random.randint(1, 16)
return red_balls, blue_ball
# 绘制彩票球的图形展示
def draw_lotto_balls(red_balls, blue_ball):
fig, ax = plt.subplots()
ax.set_aspect('equal')
colors = ['red'] * 6 + ['blue']
numbers = [str(ball) for ball in red_balls] + [str(blue_ball)]
x_interval = 1.2
for i, ball in enumerate(red_balls + [blue_ball]):
x_pos = i * x_interval
circle = plt.Circle((x_pos, 0), 0.4, color=colors[i])
ax.add_patch(circle)
ax.text(x_pos, 0, numbers[i], ha='center', va='center')
plt.xlim(-1, len(red_balls + [blue_ball]) * x_interval + 1)
plt.ylim(-1, 1)
plt.axis('off')
plt.show()
red_balls, blue_ball = generate_lotto_numbers()
draw_lotto_balls(red_balls, blue_ball)
代码详细注释版:
import random
import matplotlib.pyplot as plt
# 函数功能:生成彩票号码,包括6个红球号码(范围是1到32的不重复随机数)和1个蓝球号码(范围是1到16的随机数)
def generate_lotto_numbers():
# 从1到32中随机选取6个不重复的数作为红球号码
red_balls = random.sample(