如何绘制n边的多边形,m次

时间:2015-07-11 12:33:49

标签: python python-2.7 turtle-graphics

我是Python编程的新手,我的任务是开发一个简单的程序,绘制n边的多边形,m次,使下一个多边形的最左边边缘触及最右边的边缘前一个多边形。下面的代码根据用户输入的边数和多边形应出现的次数绘制多边形。

import turtle

def myTurtle():
  num_side = raw_input("Enter the number of sides: " )
  num_shap = raw_input("Enter the number of shapes: " )
  num_sides = int(num_side)
  num_shape = int(num_shap)
  window = turtle.Screen()
  window.bgcolor("red")

  polygon = turtle.Turtle()
  polygon.penup()
  polygon.goto(-200, 200)
  polygon.pendown()
  side_length = 60
  angle = 360.0 // num_sides 
  n = 0

  for j in range(0, num_shape):
    polygon.forward(side_length)
    for i in range(num_sides):
        polygon.pencolor("black")
        polygon.forward(side_length)
        polygon.right(angle)
    n += side_length    
window.exitonclick()

myTurtle()

我现在遇到的问题是让下一个多边形位于前一个多边形的旁边。

我已经能够提出一个更好但仍然不完美的解决方案。只是一些相互接触的多边形。我怎样才能做到这一点?

import turtle, math

def find_lenth(radius, sides):
  angle = float(360 / sides)
  otherangle = float((180 - angle) / 2)
  radangle = float(angle * (math.pi / 180))
  radangle2 = float(otherangle * (math.pi/180))
  angles = math.sin(radangle) / math.sin(radangle2)
  lenth = radius * angles
  return lenth    

def myTurtle():
  num_side = raw_input("Enter the number of sides: " )
  num_shap = raw_input("Enter the number of shapes: " )
  num_sides = int(num_side)
  num_shape = int(num_shap)
  window = turtle.Screen()
  window.bgcolor("red")
  polygon = turtle.Turtle()
  radius = 60
  side_length = find_lenth(radius, num_sides)
  angle = 360.0 // num_sides 
  delta = radius*2  #this value you must count
  colors = ['blue','white','black','green']
  for i in range(num_shape):
    polygon.penup()
    polygon.goto(-400+delta*i, 200)
    polygon.pendown()
    polygon.pencolor(colors[i%4])
    n = 0
    for j in range(num_sides):
      polygon.forward(side_length)
      polygon.right(angle)
  window.exitonclick()

if __name__ == '__main__':
  myTurtle()

1 个答案:

答案 0 :(得分:-1)

此代码将为您绘制一些多边形。要将指针移动到正确的像素值,您需要对其进行计数。

import turtle

def myTurtle():
    num_side = raw_input("Enter the number of sides: " )
    num_shap = raw_input("Enter the number of shapes: " )
    num_sides = int(num_side)
    num_shape = int(num_shap)
    window = turtle.Screen()
    window.bgcolor("red")
    polygon = turtle.Turtle()
    side_length = 60
    angle = 360.0 // num_sides 
    delta = side_length*3  #this value you must count
    colors = ['blue','white','black','green']
    for i in range(num_shape):
        polygon.penup()
        polygon.goto(-400+delta*i, 200)
        polygon.pendown()
        polygon.pencolor(colors[i%4])
        n = 0
        for j in range(num_sides):
            polygon.forward(side_length)
            polygon.right(angle)
    window.exitonclick()

if __name__ == '__main__':
    myTurtle()