本文將介紹利用Python畫多種不同的愛心形態,表白代碼看這一篇文章就夠啦,有感興趣的朋友可以收藏起來,

1、三維愛心
效果圖:

首先安裝matplotlib
參考代碼:
#!/usr/bin/env python3
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
def heart_3d(x,y,z):
return (x**2+(9/4)*y**2+z**2-1)**3-x**2*z**3-(9/80)*y**2*z**3
def plot_implicit(fn, bbox=(-1.5, 1.5)):
''' create a plot of an implicit function
fn ...implicit function (plot where fn==0)
bbox ..the x,y,and z limits of plotted interval'''
xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
A = np.linspace(xmin, xmax, 100) # resolution of the contour
B = np.linspace(xmin, xmax, 40) # number of slices
A1, A2 = np.meshgrid(A, A) # grid on which the contour is plotted
for z in B: # plot contours in the XY plane
X, Y = A1, A2
Z = fn(X, Y, z)
cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))
# [z] defines the only level to plot
# for this contour for this value of z
for y in B: # plot contours in the XZ plane
X, Z = A1, A2
Y = fn(X, y, Z)
cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))
for x in B: # plot contours in the YZ plane
Y, Z = A1, A2
X = fn(x, Y, Z)
cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))
# must set plot limits because the contour will likely extend
# way beyond the displayed level. Otherwise matplotlib extends the plot limits
# to encompass all values in the contour.
ax.set_zlim3d(zmin, zmax)
ax.set_xlim3d(xmin, xmax)
ax.set_ylim3d(ymin, ymax)
plt.show()
if __name__ == '__main__':
plot_implicit(heart_3d)
#!/usr/bin/env python3
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
def heart_3d(x,y,z):
return (x**2+(9/4)*y**2+z**2-1)**3-x**2*z**3-(9/80)*y**2*z**3
def plot_implicit(fn, bbox=(-1.5, 1.5)):
''' create a plot of an implicit function
fn ...implicit function (plot where fn==0)
bbox ..the x,y,and z limits of plotted interval'''
xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
A = np.linspace(xmin, xmax, 100) # resolution of the contour
B = np.linspace(xmin, xmax, 40) # number of slices
A1, A2 = np.meshgrid(A, A) # grid on which the contour is plotted
for z in B: # plot contours in the XY plane
X, Y = A1, A2
Z = fn(X, Y, z)
cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))
# [z] defines the only level to plot
# for this contour for this value of z
for y in B: # plot contours in the XZ plane
X, Z = A1, A2
Y = fn(X, y, Z)
cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))
for x in B: # plot contours in the YZ plane
Y, Z = A1, A2
X = fn(x, Y, Z)
cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))
# must set plot limits because the contour will likely extend
# way beyond the displayed level. Otherwise matplotlib extends the plot limits
# to encompass all values in the contour.
ax.set_zlim3d(zmin, zmax)
ax.set_xlim3d(xmin, xmax)
ax.set_ylim3d(ymin, ymax)
plt.show()
if __name__ == '__main__':
plot_implicit(heart_3d)
2、紅色愛心
效果圖:

參考代碼:
import turtle
turtle.bgcolor("black")
turtle.pensize(2)
sizeh = 1.2
def curve():
for ii in range(200):
turtle.right(1)
turtle.forward(1 * sizeh)
turtle.speed(0)
turtle.color("red", "red")
turtle.begin_fill()
turtle.left(140)
turtle.forward(111.65 * sizeh)
curve()
turtle.left(120)
curve()
turtle.forward(111.65 * sizeh)
turtle.end_fill()
turtle.hideturtle()
3、Love字體愛心
效果圖:

參考代碼:
import time
words = input('請輸出想要表達的文字:')
#例子:words = "Dear lili, Happy Valentine's Day! Lyon Will Always Love You Till The End! ? Forever! ?"
for item in words.split():
#要想實作列印出字符間的空格效果,此處添加:item = item+' '
letterlist = []#letterlist是所有列印字符的總list,里面包含y條子串列list_X
for y in range(12, -12, -1):
list_X = []#list_X是X軸上的列印字串列,里面裝著一個String類的letters
letters = ''#letters即為list_X內的字串,實際是本行要列印的所有字符
for x in range(-30, 30):#*是乘法,**是冪次方
expression = ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3
if expression <= 0:
letters += item[(x-y) % len(item)]
else:
letters += ' '
list_X.append(letters)
letterlist += list_X
print('\n'.join(letterlist))
time.sleep(1.5);
但是,有點太單調了點,來,將代碼簡單改造一下,實作動態輸出心形的,代碼如下:
import time
words = input('請輸出想要表達的文字:')
for item in words.split():
print('\n'.join([''.join([(item[(x-y) % len(item)] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(12, -12, -1)]))
time.sleep(1.5)
4、粉色桃心
效果圖:

參考代碼:
# -*- coding:utf-8 -*-
import turtle
import time
# 畫愛心的頂部
def LittleHeart():
for i in range(200):
turtle.right(1)
turtle.forward(2)
# 輸入表白的陳述句,默認I Love you
love = input('請輸入表白陳述句,默認為輸入為"I Love you": ')
# 輸入署名或者贈誰,沒有不執行
me = input('請輸入您心上人的姓名或者昵稱: ')
if love == '':
love = 'I Love you'
# 視窗大小
turtle.setup(width=800, height=500)
# 顏色
turtle.color('red', 'pink')
# 筆粗細
turtle.pensize(5)
# 速度
turtle.speed(1)
# 提筆
turtle.up()
# 隱藏筆
turtle.hideturtle()
# 去到的坐標,視窗中心為0,0
turtle.goto(0, -180)
turtle.showturtle()
# 畫上線
turtle.down()
turtle.speed(1)
turtle.begin_fill()
turtle.left(140)
turtle.forward(224)
# 呼叫畫愛心左邊的頂部
LittleHeart()
# 呼叫畫愛右邊的頂部
turtle.left(120)
LittleHeart()
# 畫下線
turtle.forward(224)
turtle.end_fill()
turtle.pensize(5)
turtle.up()
turtle.hideturtle()
# 在心中寫字 一次
turtle.goto(0, 0)
turtle.showturtle()
turtle.color('#CD5C5C', 'pink')
# 在心中寫字 font可以設定字體自己電腦有的都可以設 align開始寫字的位置
turtle.write(love, font=('gungsuh', 30,), align="center")
turtle.up()
turtle.hideturtle()
time.sleep(2)
# 在心中寫字 二次
turtle.goto(0, 0)
turtle.showturtle()
turtle.color('red', 'pink')
turtle.write(love, font=('gungsuh', 30,), align="center")
turtle.up()
turtle.hideturtle()
# 寫署名
if me != '':
turtle.color('black', 'pink')
time.sleep(2)
turtle.goto(180, -180)
turtle.showturtle()
turtle.write(me, font=(20,), align="center", move=True)
# 點擊視窗關閉
window = turtle.Screen()
window.exitonclick()
5、火柴人愛心
效果圖:

參考代碼:
#2.14
from turtle import *
from time import sleep
def go_to(x, y):
up()
goto(x, y)
down()
def head(x,y,r):
go_to(x,y)
speed(1)
circle(r)
leg(x,y)
def leg(x,y):
right(90)
forward(180)
right(30)
forward(100)
left(120)
go_to(x,y-180)
forward(100)
right(120)
forward(100)
left(120)
hand(x,y)
def hand(x,y):
go_to(x,y-60)
forward(100)
left(60)
forward(100)
go_to(x, y - 90)
right(60)
forward(100)
right(60)
forward(100)
left(60)
eye(x,y)
def eye(x,y):
go_to(x-50,y+130)
right(90)
forward(50)
go_to(x+40,y+130)
forward(50)
left(90)
def big_Circle(size):
speed(20)
for i in range(150):
forward(size)
right(0.3)
def line(size):
speed(1)
forward(51*size)
def small_Circle(size):
speed(10)
for i in range(210):
forward(size)
right(0.786)
def heart(x, y, size):
go_to(x, y)
left(150)
begin_fill()
line(size)
big_Circle(size)
small_Circle(size)
left(120)
small_Circle(size)
big_Circle(size)
line(size)
end_fill()
def main():
pensize(2)
color('red', 'pink')
head(-120, 100, 100)
heart(250, -80, 1)
go_to(200, -300)
write("To: 智慧與美貌并存的", move=True, align="left", font=("楷體", 20, "normal"))
done()
main()
動圖如下:

6、簡單愛心
效果圖:

參考代碼:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import turtle
import time
# 畫心形圓弧
def hart_arc():
for i in range(200):
turtle.right(1)
turtle.forward(2)
def move_pen_position(x, y):
turtle.hideturtle() # 隱藏畫筆(先)
turtle.up() # 提筆
turtle.goto(x, y) # 移影片筆到指定起始坐標(視窗中心為0,0)
turtle.down() # 下筆
turtle.showturtle() # 顯示畫筆
# 初始化
turtle.setup(width=800, height=500) # 視窗(畫布)大小
turtle.color('red', 'pink') # 畫筆顏色
turtle.pensize(3) # 畫筆粗細
turtle.speed(1) # 描繪速度
# 初始化畫筆起始坐標
move_pen_position(x=0,y=-180) # 移影片筆位置
turtle.left(140) # 向左旋轉140度
turtle.begin_fill() # 標記背景填充位置
# 畫心形直線( 左下方 )
turtle.forward(224) # 向前移影片筆,長度為224
# 畫愛心圓弧
hart_arc() # 左側圓弧
turtle.left(120) # 調整畫筆角度
hart_arc() # 右側圓弧
# 畫心形直線( 右下方 )
turtle.forward(224)
turtle.end_fill() # 標記背景填充結束位置
# 點擊視窗關閉程式
window = turtle.Screen()
window.exitonclick()
7、一箭雙心
效果圖:

參考代碼:
from turtle import *
from time import sleep
def go_to(x, y):
up()
goto(x, y)
down()
def big_Circle(size): #函式用于繪制心的大圓
speed(1)
for i in range(150):
forward(size)
right(0.3)
def small_Circle(size): #函式用于繪制心的小圓
speed(1)
for i in range(210):
forward(size)
right(0.786)
def line(size):
speed(1)
forward(51*size)
def heart( x, y, size):
go_to(x, y)
left(150)
begin_fill()
line(size)
big_Circle(size)
small_Circle(size)
left(120)
small_Circle(size)
big_Circle(size)
line(size)
end_fill()
def arrow():
pensize(10)
setheading(0)
go_to(-400, 0)
left(15)
forward(150)
go_to(339, 178)
forward(150)
def arrowHead():
pensize(1)
speed(1)
color('red', 'red')
begin_fill()
left(120)
forward(20)
right(150)
forward(35)
right(120)
forward(35)
right(150)
forward(20)
end_fill()
def main():
pensize(2)
color('red', 'pink')
#getscreen().tracer(30, 0) #取消注釋后,快速顯示圖案
heart(200, 0, 1) #畫出第一顆心,前面兩個引數控制心的位置,函式最后一個引數可控制心的大小
setheading(0) #使畫筆的方向朝向x軸正方向
heart(-80, -100, 1.5) #畫出第二顆心
arrow() #畫出穿過兩顆心的直線
arrowHead() #畫出箭的箭頭
go_to(400, -300)
write("author:520Python", move=True, align="left", font=("宋體", 30, "normal"))
done()
main()

點擊領取.福利多多
①行業咨詢、大佬在線專業解答有
②Python開發環境安裝教程有
③Python400集自學視頻有
④軟體開發常用詞匯有
⑤Python學習路線圖有
⑥3000多本Python電子書有 如果你用得到的話可以直接拿走,在我的QQ技術交流群里群號:675240729(純技術交流和資源共享,廣告勿入)以自助拿走
這篇文章到這里結束了,更多有關Python精彩內容可以關注小編看小編主頁或點擊上分福利多多,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/286957.html
標籤:python
