Python3使用turtle模块和while循环绘制多角星的代码问题咨询
问题原因分析
- 后续星星无法绘制:计数变量
x在绘制完第一颗星星后未重置为0,且角度计算变量A、B仅在首次绘制前计算,后续更换角数后没有更新对应角度,导致循环不执行或绘制角度错误。 - 填充仅覆盖角:
begin_fill()和end_fill()被放在循环内部,每画一个角就单独执行一次填充,自然只能填充单个角而非整体。
修正后代码
from turtle import * def start(): """This function initializes the window and the turtle. Do not modify this function. """ setup(564, 564) width(7) side_length = 60 # Also the radius of a circle enclosed by the star. penup() goto(0, -side_length) # Start at the bottom of the star. pendown() def draw_star(points, line_color, fill_color, pos_x, pos_y, side_length=60): # 移动到指定绘制位置 penup() goto(pos_x, pos_y) pendown() # 重置海龟朝向,避免上一次绘制的角度残留 setheading(0) # 计算当前星星的对应角度 A = 360 / points B = 2 * A x = 0 # 设置颜色,整颗星星只执行一次开始填充 color(line_color, fill_color) begin_fill() while x < points: left(A) forward(side_length) right(B) forward(side_length) x += 1 # 整颗星星绘制完成后再结束填充 end_fill() def main(): side_length = 60 # 绘制第一颗星星 points = int(input('How many points would you like on your star? ')) draw_star(points, 'blue', 'red', 0, -side_length) # 绘制第二颗星星 points = int(input('How many points would you like on your star? ')) draw_star(points, 'green', 'yellow', 2*side_length, 2*side_length) # 绘制第三颗星星 points = int(input('How many points would you like on your star? ')) draw_star(points, 'orange', 'purple', -2*side_length, 2*side_length) # Do not change anything after this line. if __name__ == '__main__': start() main() done()
优化说明
将重复的星星绘制逻辑封装为独立函数,每次绘制前自动重置计数变量、角度参数和海龟朝向,避免重复代码的同时也避免了变量复用导致的逻辑错误。填充逻辑调整为整颗星星绘制前后各执行一次,即可实现整体填充效果。
内容的提问来源于stack exchange,提问作者Skantrow
相关产品推荐
相关产品推荐

