示例#1
0
def drunkard_walk(x, y, n):
    """
    x, y: the original location
    n: the number of intersections(steps)
    return the distance after n intersections(steps) from the origin
    """
    drunk = turtle.turtle()
    print(drunk)
    a = [x]
    b = [y]
    for i in range(n):
        if random.randrange(2) == 0:
            movementx = random.choice([1, -1])
            x = x + movementx
            if movementx == 1:
                drunk.seth(0)
                drunk.fd(100)
            if movementx == -1:
                drunk.seth(180)
                drunk.fd(100)

        elif random.randrange(2) == 1:
            movementy = random.choice([1, -1])
            y = y + movementy
            if movementy == 1:
                drunk.seth(90)
                drunk.fd(100)
            if movementy == -1:
                drunk.seth(270)
                drunk.fd(100)
    a.append(x)
    b.append(y)
    turtle.mainloop()
    return math.sqrt((a[0] - a[1])**2 + (b[0] - b[1])**2)
示例#2
0
    def load(self, accountID, lat, long):
        with open('csvdata/accounts.csv', 'r') as f:
            lines = f.readlines()
            f.close()

        line = lines[accountID]

        lineData = []
        chunk = ""

        line = line[:len(line) - 3]
        for i in line:
            if i == ",":
                lineData.append(chunk)
                chunk = ""
            else:
                chunk = chunk + i
        lineData.append(chunk)
        api = pgoapi.PGoApi()
        api.activate_signature(
            "/home/nate/spyder workspace/pgo_unofficial/pgoapi/libencrypt.so")
        api.set_authentication(provider="ptc",
                               username=lineData[0],
                               password=lineData[1])

        # in CSV file, format is:
        # user,pass,lat,long
        turt = turtle.turtle(api, float(lineData[2]), float(lineData[3]),
                             accountID, lineData[0], lineData[1], plt)
        time.sleep(1)
        turt.latitude = lat
        turt.longitude = long
        turt.player.set_position(lat, long, 0)
        self.turtles.append(turt)
def spiral_relative(linesize = 100, angle = 20, outer = 10):
	t = turtle("spiral_relative.svg")
	t.pendown()
	
	for i in range(outer):
		for j in range(4):
			t.forward(linesize)
			t.right(90)
			
		d = math.radians(angle)
		# degree = angle ACD
		# BC = AD
		#A---D 
		# | /
		#C|/
		# |
		#B----
		# AC + AD = linesize
		# AD / AC = tan (degree)
		# CD = AD / sin (degree)
		
		ad = linesize * math.tan(d) / (1 + math.tan(d))
		ac = linesize - ad
		cd = ad / math.sin(d) #math.sqrt(ac ** 2  + ad ** 2)
				
		t.forward(ad)
		t.right(angle)
		linesize = cd
	t.save()
def star_pentagon_relative(linesize = 100):
	
	t = turtle("pentagon_relative.svg", linesize, linesize, 0, True)
	for i in range(5):
		t.forward(linesize)
		t.right(360.0 / 5)
	
	# A   B  C
	# ----===
	#     \ |
	#      \|D
	# I need to rotate to go from A to D
	# The triangle ABD is over two vertices ->
	#  B is inner angle and the remaining angles are the same
	t.right( 36 ) # 180 - 108 (inner angle) / 2
	#I also need to expand linesize - it has to be distance from A to D:
	# linesize = AB = BD
	# BC = BD * cos(72)
	# CD = BD * sin(72)
	# AD = sqrt((ab + bc)^2 + CD^2)
	bc = linesize * math.cos(math.pi / 180.0 * 72)
	cd = linesize * math.sin(math.pi / 180.0 * 72)
	ad = math.sqrt((linesize + bc) ** 2 + cd ** 2)
	
	for i in range(5):
		t.forward(ad)
		t.left(3 * 360.0 / 5)
	t.save()
def main():
    window = turtle.Screen()
    nico = turtle.turtle()

    make_square(nico)

    turtle.mainloop()
示例#6
0
def polygon(n, linesize = 100):
	inner_angle = (n - 2) * 180 / n
	
	t = turtle("polygon_"+str(n)+".svg", linesize, linesize, 0, True)
	for i in range(n):
		t.forward(linesize)
		t.right(180.0 - inner_angle) #Also 360.0 / n
	t.save()
示例#7
0
def star(n, k, linesize = 100):
	t = turtle("star_"+str(n)+"_"+str(k)+".svg", linesize, linesize, 0, True)
	
	for i in range(n):
		t.forward(linesize)
		t.left(k * 360.0 / n)
		
	t.save()
def flower(n = 12, diameter = 200):
	t = turtle("flower_relative.svg", diameter / 4.0 + 20, diameter / 4.0 + 20, 0, True)
	degree = 360.0 / n
	length = diameter / float(n)
	
	for i in range(n):
		for j in range(n):
			t.forward(length)
			t.right(degree)
		t.right(degree)
	t.save()
示例#9
0
  def add_available_animal(self):
    Selena = cat("Selena", "calico cat", 1, 10, "female", "tuna", "loving")
    Wuffles = dog("Wuffles", "yorkshire terrier dog", 2, 12, "male", "beef-flavored dog food", "playful")
    Roddy = fish("Roddy", "goldfish", 1/2, 1, "male", "fish flakes", "docile")
    Chipper = hamster("Chipper", "syrian hamster", 3, 5, "male", "sunflower seeds", "hyper")
    Lisa = turtle("Lisa", "box turtle", 30, 2, "female", "fresh vegetables and bugs", "curious")

    self.available_animals = {
      'cat': Selena,
      'dog': Wuffles,
      'fish': Roddy,
      'hamster': Chipper,
      'turtle':  Lisa
    }
示例#10
0
def circles(n, down = False, linesize = 10):
	t = turtle("circle_"+str(n)+".svg", linesize, linesize, 0, True)
	
	angle = 360.0 / n
	absolute = 0
	
	for i in range(n * 5):
		diff = linesize * (math.sin(math.radians(absolute)) if down else math.cos(math.radians(absolute)))
		t.forward(linesize + diff)
		t.right(angle)
		absolute += angle
		if absolute >= 360.0:
			absolute = 0
	
	t.save()
def triangle_relative(length = 200, triangles = 15):
	t = turtle("triangle_relative.svg", 20, 20 + length * math.sqrt(3) / 2, 0, True)
	move = length / triangles
	
	while (length > 0):
		for i in range(3):
			t.forward(length)
			t.left(120)
		t.penup()
		t.left(30)
		t.forward(move)
		t.right(30)
		t.pendown()
		
		length -= math.cos( math.radians(30) ) * move * 2
	t.save()
示例#12
0
def draw_art():
	windows = turtle.screen()
	window.bgcolor("red")
	# create the turtle brad - draw squares
	brad = turtle.turtle()
	brad.shape("turtle")
	brad.color("yellow")
	brad.speed.(2)
	for i in range(1,37):
		draw_square(brad)
		brad.right(10)
	# create the turtle angie - drawa circles
	angie.turtle.Turtle()
	angie.shape("arrove")
	angie.color("blue")
	angie.circle(100)

	window.exitonclick()
示例#13
0
def bush(n, linesize = 100, t = False, recurse = 0):
	if recurse == n:
		return
	
	if not t:
		t = turtle("bush_"+str(n)+".svg", linesize, linesize * 2, 90, True)
	
	angle = 360.0 / n
	
	t.forward(linesize)
	t.left(angle)
	bush(n, linesize / 2.0, t, recurse + 1)
	t.right(angle + 180 + angle)
	bush(n, linesize / 2.0, t, recurse + 1)
	t.left(angle)
	t.forward(linesize)
	
	if not recurse:
		t.save()
def showmontepi(numdarts):
    scn = turtle.screen()
    t = turtle.turtle()

    scn.setworldcoordinates(-2, -2, 2, 2)

    t.penup()
    t.goto(-1, 0)
    t.pendown()
    t.goto(1, 0)

    t.penup()
    t.goto(0, 1)
    t.pendown()
    t.goto(0, -1)

    inCircle = 0
    t.penup()

    for i in range(numDarts):
        x = random.random()
        y = random.random()

        distance = math.sqrt(x**2 + y**2)

        t.goto(x, y)

        if distance <= 1:
            inCircle = inCircle + 1
            t.color("blue")
        else:
            t.color("red")

        t.dot()

        pi = inCircle / numDarts * 4
        scn.exitonclick()
        return pi

    showMontePi(1000)

    t.pendown()
示例#15
0
def test(d):
	t = turtle(h=d)
		
	t.turn(0)
	t.turn(30)
	t.turn(0)
	
	t.setAxis('X')
	
	t.turn(30)
	t.turn(30)
	
	t.setAxis('Y')
	
	t.turn(-90)
	t.turn(-90)
	t.turn(90)
	t.turn(0)
	t.turn(90)
	
	return t.getNodes()
示例#16
0
文件: turtle.py 项目: Tesla2fox/ASCII
def main():
    p = turtle()
    p.color("green")
    p.pensize(5)
    #p.setundobuffer(None)
    p.hideturtle(
    )  #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
    #because hiding the turtle speeds up the drawing observably.
    #p.speed(10)
    # p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
    p.speed(10)
    #TurtleScreen methods can then be called for that object.
    p.left(90)  # Turn turtle left by angle units. direction 调整画笔

    p.penup()  #Pull the pen up – no drawing when moving.
    p.goto(
        0, -200
    )  #Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
    p.pendown(
    )  # Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
    #否则turtle一移动就会自动的把线画出来

    #t = tree([p], 200, 65, 0.6375)
    t = tree([p], 200, 65, 0.6375)
示例#17
0
print(dates)

# In[12]:

a2 = pd.DataFrame(pd_random.randn(6, 4), index=dates, columns=list('ABCD'))
print(a2)

# In[21]:

a2 = pd.DataFrame({
    'A': 1.,
    'B': pd.Timestamp('20190601'),
    'C': pd.Series(1, index=list(range(4)), dtype='float32'),
    'D': np.array([3] * 4, dtype='int32'),
    'E': pd.Categorical(["test", "train", "test", "train"]),
    'F': "foo"
})
print(a2)

# In[22]:

#Step 1: Make All the turtle package to be imported
import turtle as tt
#turtle method creates an dreturns the object
a1 = tt.turtle()
#forward method moves 100 pixel
tt.format(100)
tt.done()

# In[ ]:
示例#18
0
import turtle
obj=turtle.turtle()
win = turtle.screen()

def semi_circle(col,rad,val):
    obj.color('col')
    obj.circle(rad,-180)
    obj.up()
    obj.setpos(val, 0)
    obj.down()
    obj.right(180)

col = ['violet','indigo','blue','green','yellow','orange','red']

win.bgcolor('black')
obj.right(90)
obj.width(10)
obj.speed(1)
semi_circle(col[i], 10*(i+8), 10*(i+1))
for i in range(7):


obj.hidetutle


turtle.done()
 def setDYPL( self, obj ):
     print("Got a DYPL instance: ")
     self.t = turtle(obj)
示例#20
0
文件: câu 1.py 项目: tuantuka/b-i-8
import turtle
window = turtle.screen()
window.bgcolor("lighblack")
painter= turtle.turtle()
painter.fillcolor('yellow')
painter.pencolor('blue')
painter.pensize(3)
def drawsq(t,s):
    for i n range(4):
        t.forward(s)
        t.left(90)
for i in range ( 1,180 ):
    painter.left(18)
    drawsq(painter,200)
示例#21
0
#Getting a screen | canvas
s=turtle.Screen()
s.title("Snake game")
s.bgcolor("gray")
s.setup(width=600,height=600)

#create snake head
head=turtle.Turtle()
head.speed(0)
head.color("white")
head.shape("circle")
head.fillcolor("black")
head.penup()
head.goto(0,0)
head.direction="stop"

#snake food
food=turtle.turtle()
food.speed(0)
food.color("green")
food.shape("square")
food.fillcolor("red")
food.penup()
food.ht()
food.goto(0,200)
food.st()

#score
sb=turtle.Turtle()
sb.shape("square")
示例#22
0
jumsu=55
res=''
if jumsu >= 60:
    res="합격"
else:
    res="불합격"
print(res)

res = '합격' if jumsu>=60 else '불합격'


import turtle

swidth, sheight = 500, 500

turtle.turtle('무지개색 원그리기')
turtle.shape('turtle')
turtle.setup(width=swidth+50, height=sheight+50)
turtle.screensize(swidth, sheight)
turtle.penup()
turtle.goto(0, -sheight/2)
turtle.pendown()
turtle.speed(10)

for radius in range(1, 250):
    if radius % 6 == 0:
        turtle.pencolor('red')
    elif radius % 5 == 0:
        turtle.pencolor('orange')
    elif radius % 4 == 0:
        turtle.pencolor('yellow')
screen_width = 400
screen_height = 400
letter_list =  ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
#


active_letter = []
apple_list = []
number_of_apples = 5

wn = trtl.Screen()
wn.addshape(apple_image) # Make the screen aware of the new file
wn.setup(width=1.0, height=1.0)

wn.bgpic("background.gif")
apple = trtl.turtle()
apple.penup()
wn.tracer(False)



apple = trtl.Turtle()
drawer = trtl.Turtle()
# given a turtle, set that turtle to be shaped by the image file
def draw_apple(active_apple):
  active_apple.shape(apple_image)
  active_apple.showturtle()
  draw_letter(active_apple, letter)
  wn.update()

draw_apple(apple)
示例#24
0
def turtle(sectors=16):
    energy, emission, direction, elevation, azimuth = _turtle.turtle(
        sectors=str(sectors), energy=1)
    sources = zip(energy, direction)
    return sources
示例#25
0
import turtle as t

playerA_score = 0
playerB_score = 0

window = t.Screen()
window.title("Pong Game")
window.bgcolor("black")
window.setup(width=800, height=600)
window.tracer(0)

#creating leftpaddle

leftpaddle = t.turtle()
leftpaddle.speed(0)
leftpaddle.shape("square")
leftpaddle.color("green")
leftpaddle.shapesize(stretch_wid=5, stretch_len=1)
leftpaddle.penup()
leftpaddle.goto(-350, 0)

#creating rightpaddle

rightpaddle = t.turtle()
rightpaddle.speed(0)
rightpaddle.shape("square")
rightpaddle.color("green")
rightpaddle.shapesize(stretch_wid=5, stretch_len=1)
rightpaddle.penup()
rightpaddle.goto(350, 0)
# from turtle import *

# color('red', 'yellow')
# begin_fill()
# while True:
# 	forward(200)
# 	left(170)
# 	if abs(pos()) < 1:
# 		break

# end_fill()
# done()

import turtle

triple = turtle.turtle()

for i in range(20):
    triple.forward(i * 10)
    triple.right(144)

turtle.done()
示例#27
0
import turtle

myTurtle = turtle.turtle()
myTurtle.circle(50)
示例#28
0
def polyline(tur,n,length,angle):
    for i in range(n):
        tur.fd(length)
        tur.lt(angle)

def polygon(tur,n,length):
    angle=360/n
    polyline(tur,n,length,angle)

def arc(tur,r,angle):
    arc_length=2*math.pi*r*abs(angle)/360
    n=int(arc_length/4)+1
    len=arc_length/n
    step_angle=float(angle)/n

    tur.lt(step_angle/2)
    polyline(tur,n,len,sturep_angle)
    tur.rt(step_angle/2)


#Running turestur program

bob=turtle.turtle()
#square(bob,100)
#polenygon(bob,10,100)



turtle.mainloop()

示例#29
0
import turtle

niki = turtle.turtle()


def square(length):
    for i in range(4):
        niki.fd(length)
        niki.lt(90)


square(100)
示例#30
0
import turtle as t:

Tom = t.turtle()

示例#31
0
####
#터틀 그래픽으로 사각형 그리기
import turtle

p = turtle.turtle()

for k in range(0, 3):
    for i in range(4):
        p.forward(40)
        p.left(90)
    p.left(20)

####
#1부터 100까지 어떤 배수의 합 구하기(몇 배수인지는 입력받기)
step = int(input("어떤배수의 합을 구할까요?:"))
number = 0
for i in range(0, 101, step):
    number += i
print("1부터 100까지의 모든 ", step, "의 배수의 합은", number, "입니다.")

####
#자리수의 합 계산하기
number = input("정수를 입력하세요 : ")
num_sum = 0
for i in range(len(number)):
    num_sum += int(number[i])
print("자리수의 합은", num_sum, "입니다.")

####
#문자열 조사
string = input("문자열을 입력하세요 : ")
示例#32
0
import time
import turtle
time1 = input('What is the time you want to set?')
time_floated = float(time1)
time.sleep(time_floated)
print('Time is up!')

fred = turtle.turtle()
fred.circle(150)
fred.up()
fred.left(90)
fred.forward(150)
fred.down()
fred.forward(150)
fred.left(180)
fred.forward(150)
fred.left(25)

示例#33
0
import turtle,random
class Cell:
  def__init__(self,size,t,x,y):
    self.x=x
    self.y=y
    self.t=t
    self.size=size
  def draw_square(self):
    for side in range(4):
      self.t.fd(self.size)
      self.t.left(90)
      
      
  def draw_snake()(self)
    for side in range(5):
      cell=cell(10,turtle.turtle(),i*10,i*10)
      cell.draw_square()
      cell.draw_snake()
      cell=Cell(10,turtle.Turtle(),0,0)
      cell.draw_square()
 class food:
    def__init__(self):
    self.cell=Cell(x,y)
    
    
    
    
    
    
    
    
示例#34
0
Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:07:06) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import turtle
my_turtle = turtle.turtle()
my_turtle.forward(100)
示例#35
0
	def draw(self, col, lSentence, angle, d):
		characters = list(lSentence)
		stack = []
		
		a = 0
		accumAngle = ""
		finishedAccumAng = False
		
		t = turtle(h=d)
		# Set whether to add spheres between cylinders
		t.setRounded(rd = self.spheres)
		# Set whether to print the debug log
		t.setDebug(self.debug)
		# Set a pencolor
		if col is not "":
			t.pencolor(col);
		# Percentage of cylinder reduction
		percentReduction = 0.20
		# Increase cylinder height by 30%
		cylScale = 1.3
		
		for c in characters:
			a = int(accumAngle) if (accumAngle is not '') else angle
			
			if (c == 'F' or c == 'f'):
				t.forward(d)
				a = 0

			if (finishedAccumAng):
				accumAngle = ""

			if (c.isdigit()):
				accumAngle = accumAngle + c
			
			elif (c == '('):
				finishedAccumAng = False
			
			elif (c == ')'):
				finishedAccumAng = True
			
			elif (c == 'L'):
				t.addLeaf(r = 1)

			elif (c == '+'):
				t.yaw(a)
			
			elif (c == '-'):
				t.yaw(-a)
			
			elif (c == '&'):
				t.pitch(a)
			
			elif (c == '^'):
				t.pitch(-a)
			
			elif (c == "\\"):
				t.roll(a)
			
			elif (c == '/'):
				t.roll(-a)
			
			elif (c == '|'):
				a = 180
				t.yaw(a)
			
			elif (c == ">"):
				t.r -= percentReduction * t.r
			
			elif (c == "<"):
				t.r += (percentReduction * t.r)
			
			elif (c == '"'):
				t.h += (cylScale * t.h)
			
			elif (c == '['):
				tup = (t.curPoint, t.rotVector, t.rotMatrix, t.r)
				stack.append(tup)
			
			elif (c == ']'):
				val = stack.pop()
				t.penup()
				t.setposition(val[0][0], val[0][1], val[0][2])
				t.pendown()
				t.rotVector = val[1]
				t.rotMatrix = val[2]
				t.r = val[3]

			else:
				continue
		return t.getNodes()
import turtle

window = turtle.Screen()
babbage = turtle.turtle()
babbage.left(90)
babbage.forward(100)
babbage.right(90)
babbage.circle(10)
window.exitonclick()
示例#37
0
for x in range (100):
  turtle.forward (5 + x)
  turtle.right (15)
  turtle.color (colors[x%6])
  turtle.done

# 4.) Draw a Hexagon Shape.
for x in range (6):
    turtle.forward (100)
    turtle.right (60)

turtle.exitonclick()

# 5.) Draw a grid of dots. 5 dots wide and 7 dots high.
grid = turtle.turtle()
dot_distance = 10
width = 5
height = 7
grid.penup ()
grid.setposition (100, 0)

for y in range (height):
    for x in range (width):
      grid.dot ()
      grid.forward (dot_distance)

grid.backward (dot_distance * width)
grid.right (90)
grid.forward (dot_distance)
grid.left (90)
示例#38
0
print(f'The simple interest is {simple_interest}')
'''

#IN AND IS OPERATOR
'''
a = 's'
b = 'computers'

if a in b:
    print('WOKRS')
else:
    print('DOESNT WORK')

c = 's'
if a is c:
    print('WORKS')
else:
    print('DOESNT')
'''

#EXPONENTS, DIVISION/MULTIPLICATION/MODULUS ADDITION/SUBTRACTION ---> BODMAS IN PYTHON

#PUNCTUATING
import re
import turtle
noel = turtle.turtle()

text = 'The;quick;brown;fox;jumps;over;the;lazy*dog'
print(re.split(';|,|\*|\n', text))
示例#39
0
	def __init__(self):
		self.stochastic = False
		self.spheres = False
		self.debug = False
		self.turtle = turtle()
示例#40
0
文件: light.py 项目: DrXav/scanalea
def turtle(sectors=16):
    energy, emission, direction, elevation, azimuth = _turtle.turtle(sectors=str(sectors), energy=1) 
    sources = zip(energy, direction)
    return sources
示例#41
0
	def draw(self, filename, start):
		t = turtle(filename, start[0], start[1])
		t.pendown()
		for i in self.state:
			self.semantics[i](t)
		t.save()