最近,我嘗試使用Python編寫一個飄動的黨旗,來慶祝我們偉大祖國的生日。在代碼中使用了turtle庫來實現畫圖功能,下面是我的代碼實現。
import turtle # 畫矩形,用于黨旗的紅色底色 def draw_rectangle(x, y, width, height): turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.begin_fill() turtle.fillcolor("red") turtle.fd(width) turtle.right(90) turtle.fd(height) turtle.right(90) turtle.fd(width) turtle.right(90) turtle.fd(height) turtle.right(90) turtle.end_fill() # 畫星星,用于黨旗的黃色五角星 def draw_star(x, y, radius): turtle.setpos(x, y) # 此處通過循環來繪制五角星 pt = turtle.pos() pc = turtle.color() angle = turtle.heading() turtle.penup() y = y + radius turtle.setpos(x, y) turtle.pendown() turtle.color("yellow", "yellow") turtle.begin_fill() turtle.right(angle) turtle.right(72) for i in range(5): turtle.forward(radius) turtle.right(144) turtle.end_fill() turtle.penup() turtle.setpos(pt) turtle.setheading(angle) turtle.color(pc[0], pc[1]) # 主函數 def main(): turtle.speed(0) # 先畫紅色底色 draw_rectangle(-270, 150, 540, 300) # 再畫大黃色五角星 turtle.width(5) turtle.color("yellow", "yellow") turtle.penup() turtle.goto(-100, 70) turtle.pendown() turtle.begin_fill() turtle.circle(50) turtle.end_fill() # 最后畫四個小黃色五角星 turtle.width(3) draw_star(-180, 150, 30) draw_star(-60, 200, 30) draw_star(-60, 100, 30) draw_star(-180, 50, 30) turtle.hideturtle() turtle.done() if __name__ == '__main__': main()
通過以上代碼,我們可以實現一個飄動的黨旗,并且可以修改代碼中的各個參數來實現不同的效果。
上一篇oracle 0640