Tanabata confession code collection

​Source   : Baidu animation

insert image description here

The annual Qixi Festival is coming again, I found that there are many well-written Python confession codes on the Internet, and I feel that the drawn pictures are very beautiful. I sorted it out and picked some codes that I think are good and some original ones that I think are good to share with you. I have tested all of these, and it can indeed be generated~, choose a favorite method to send you the TA picture.

More original confession codes: Bixin, Eternal Heartbeat, Only You in My Eyes, Confession Fireworks, This is my so-and-so see the article link at the end of this article.


  

1. Entry level

  

1. Draw a heart with one line of code

  

print('\n'.join([''.join([('Love'[(x-y)%4]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(15,-15,-1)]))

renderings
  
insert image description here

  

2. Use the turtle library to draw love and add text

  

import turtle
import math
turtle.pen()
t=turtle
t.up()
t.goto(0,150)
t.down()
t.color('red')
t.begin_fill()
t.fillcolor('red')
t.speed(1)
t.left(45)
t.forward(150)
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(250+math.sqrt(2)*100)
t.right (90)
t.speed(2)
t.forward(250+100*math.sqrt(2))
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(150)
t.end_fill()
t.goto(-10,0)
t.pencolor('white')
#L
t.pensize(10)
t.goto(-50,0)
t.goto(-50,80)
t.up ()
#I
t.goto(-100,0)
t.down()
t.goto(-160,0)
t.goto(-130,0)
t.goto(-130,80)
t.goto(-160,80)
t.goto(-100,80)
t.up()
#O
t.goto(10,25)
t.down()
t.right(45)
t.circle(25,extent=180)
t.goto(60,55)
t.circle(25,extent=180)
t.goto(10,25)
t.up()
t.goto(75,80)
t.down()
t.goto(100,0)
t.goto(125,80)
t.up()
t.goto(180,80)
t.down()
t.goto(140,80)
t.goto(140,0)
t.goto(180,0)
t.up()
t.goto(180,40)
t.down()
t.goto(140,40)
#U
t.up()
t.goto(-40,-30)
t.down()
t.goto(-40,-80)
t.circle(40,extent=180)
t.goto(40,-30)
t.hideturtle()

renderings
  
insert image description here

  
  

Second, the advanced class

  

1. Draw a rose with the turtle library version 1

  

#!/usr/bin/env python
# coding: utf-8

#绘制玫瑰花并添加文字
import turtle 
# 设置画布大小
# turtle.screensize(canvwidth=None, canvheight=None, bg=None)
turtle.setup(width=0.6, height=0.6)
# 设置初始位置
turtle.penup()
turtle.left(90)
turtle.fd(200)
turtle.pendown()
turtle.right(90)

# 输出文字
printer = turtle.Turtle()
printer.hideturtle()
printer.penup()
printer.back(200)
printer.write("赠给亲爱的 XX\n\n", align="right", font=("楷体", 16, "bold"))
printer.write("from XXX", align="center", font=("楷体", 12, "normal"))

# 花蕊
turtle.fillcolor("red")
turtle.begin_fill()
turtle.circle(10, 180)
turtle.circle(25, 110)
turtle.left(50)
turtle.circle(60, 45)
turtle.circle(20, 170)
turtle.right(24)
turtle.fd(30)
turtle.left(10)
turtle.circle(30, 110)
turtle.fd(20)
turtle.left(40)
turtle.circle(90, 70)
turtle.circle(30, 150)
turtle.right(30)
turtle.fd(15)
turtle.circle(80, 90)
turtle.left(15)
turtle.fd(45)
turtle.right(165)
turtle.fd(20)
turtle.left(155)
turtle.circle(150, 80)
turtle.left(50)
turtle.circle(150, 90)
turtle.end_fill()

# 花瓣1
turtle.left(150)
turtle.circle(-90, 70)
turtle.left(20)
turtle.circle(75, 105)
turtle.setheading(60)
turtle.circle(80, 98)
turtle.circle(-90, 40)

# 花瓣2
turtle.left(180)
turtle.circle(90, 40)
turtle.circle(-80, 98)
turtle.setheading(-83)

# 叶子1
turtle.fd(30)
turtle.left(90)
turtle.fd(25)
turtle.left(45)
turtle.fillcolor("green")
turtle.begin_fill()
turtle.circle(-80, 90)
turtle.right(90)
turtle.circle(-80, 90)
turtle.end_fill()
turtle.right(135)
turtle.fd(60)
turtle.left(180)
turtle.fd(85)
turtle.left(90)
turtle.fd(80)

# 叶子2
turtle.right(90)
turtle.right(45)
turtle.fillcolor("green")
turtle.begin_fill()
turtle.circle(80, 90)
turtle.left(90)
turtle.circle(80, 90)
turtle.end_fill()
turtle.left(135)
turtle.fd(60)
turtle.left(180)
turtle.fd(60)
turtle.right(90)
turtle.circle(200, 60)

turtle.done()

renderings
  
picture

  
  

2. Draw a rose with the turtle library version 2

  

# -*- coding: UTF-8 -*-
'''
代码用途 :画玫瑰花
作者     :阿黎逸阳
博客     :  https://blog.csdn.net/qq_32532663/article/details/106176609
'''
import os
import time
import pygame
import turtle as t 

#播放音乐
print('播放音乐')
pygame.mixer.init()
pygame.mixer.music.load(r"F:\公众号\62.玫瑰花\Eran - 春の思い出.mp3") 
pygame.mixer.music.set_volume(0.5) 
pygame.mixer.music.play(1, 10)

t.title('阿黎逸阳的代码公众号')
t.speed(3)
t.setup(startx=0, starty = 0, width=800, height = 600)
#画爱心
def red_heart():
    t.penup()
    t.goto(0, 200)
    t.pendown()
    t.pensize(2)
    t.color('black', 'red')   
    t.begin_fill()
    t.setheading(110)
    t.circle(30, 150)
    t.left(15)
    t.circle(50, 70)
    t.circle(-50, 30)
    t.left(100)
    t.circle(-50, 30)
    t.right(10)
    t.circle(50, 70)
    t.left(5)
    t.circle(29, 175)
    t.end_fill()
def top_arc():
    #画花上面的部分
    t.penup()
    t.goto(18, 224)
    t.pendown()
    t.begin_fill()
    t.setheading(125)
    t.pensize(2)
    t.color('black', 'red')
    t.circle(25, 125)
    t.color('red')
    t.circle(25, 360-125)
    t.end_fill()
def under_arc():
    #画下弧线
    t.penup()
    t.goto(-58, 190)
    t.pendown()
    t.begin_fill()
    t.color('black', 'red')
    t.setheading(290)
    t.circle(-120, 50)
    t.circle(60, 120)
    t.setheading(-10)
    t.circle(60, 120)
    t.left(4)
    t.circle(-120, 50)
    t.end_fill()
def stamen():
    #画花蕊
    t.penup()
    t.goto(0, 185)
    t.pendown()
    t.setheading(90)
    t.circle(5, 270)
    t.right(5)
    t.circle(100, 8)
    #t.right(10)
    t.circle(10, 180)
    t.circle(100, 8)
    t.right(10)
    t.circle(15, 160)
    t.circle(80, 5)
    t.right(34)
    t.circle(-30, 80)
    #画花身
    t.right(10)
    t.circle(100, 82)
    #画竖线
    t.penup()
    t.goto(-10, 183)
    t.pendown()
    t.setheading(-90)
    t.forward(15)
    t.penup()
    t.goto(-21, 179)
    t.pendown()
    t.setheading(-90)
    t.forward(25)
    t.penup()
    t.goto(18, 185)
    t.pendown()
    t.setheading(-90)
    t.forward(29)
print('画心')
red_heart()
print('画顶部弧线')
top_arc()
print('画下弧线')
under_arc()
print('画心')
red_heart()
print('画花蕊')
stamen() 
# 写文字
t.hideturtle()
t.penup()
t.goto(-200, -200)
t.pendown()
t.write("赠给亲爱的 XX\n\n", align="right", font=("楷体", 16, "bold"))
t.penup()
t.goto(-200, -200)
t.pendown()
t.write("from XXX", align="right", font=("楷体", 12, "normal"))

effect video
  

draw roses

Note: If you need the video source code, please reply "Rose 2" in the official account, and you can get it for free.

  

3. Use the turtle library to draw love and add text

  

import turtle
import random

def love(x, y):  # 在(x,y)处画爱心lalala
    lv = turtle.Turtle()
    lv.hideturtle()
    lv.up()
    lv.goto(x, y)  # 定位到(x,y)

    def curvemove():  # 画圆弧
        for i in range(20):
            lv.right(10)
            lv.forward(2)

    lv.color('red', 'pink')
    lv.speed(10000000)
    lv.pensize(1)
    # 开始画爱心lalala
    lv.down()
    lv.begin_fill()
    lv.left(140)
    lv.forward(22)
    curvemove()
    lv.left(120)
    curvemove()
    lv.forward(22)
    lv.write("YZ", font=("Arial", 12, "normal"), align="center")  # 写上表白的人的名字
    lv.left(140)  # 画完复位
    lv.end_fill()


def tree(branchLen, t):
    if branchLen > 5:  # 剩余树枝太少要结束递归
        if branchLen < 20:  # 如果树枝剩余长度较短则变绿
            t.color("green")
            t.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))
            t.down()
            t.forward(branchLen)
            love(t.xcor(), t.ycor())  # 传输现在turtle的坐标
            t.up()
            t.backward(branchLen)
            t.color("brown")
            return
        t.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))
        t.down()
        t.forward(branchLen)
        # 以下递归
        ang = random.uniform(15, 45)
        t.right(ang)
        tree(branchLen - random.uniform(12, 16), t)  # 随机决定减小长度
        t.left(2 * ang)
        tree(branchLen - random.uniform(12, 16), t)  # 随机决定减小长度
        t.right(ang)
        t.up()
        t.backward(branchLen)

myWin = turtle.Screen()
t = turtle.Turtle()
t.hideturtle()
t.speed(1000)
t.left(90)
t.up()
t.backward(200)
t.down()
t.color("brown")
t.pensize(32)
t.forward(60)
tree(100, t)
myWin.exitonclick()

renderings
picture

  
  

3. High-end version

  

1. Confessions under the stars

  

"""
代码用途:表白
作者:阿黎逸阳
"""

def bgpic(self, picname=None):
        """Set background image or return name of current backgroundimage.

        Optional argument:
        picname -- a string, name of a gif-file or "nopic".

        If picname is a filename, set the corresponding image as background.
        If picname is "nopic", delete backgroundimage, if present.
        If picname is None, return the filename of the current backgroundimage.

        Example (for a TurtleScreen instance named screen):
        >>> screen.bgpic()
        'nopic'
        >>> screen.bgpic("landscape.gif")
        >>> screen.bgpic()
        'landscape.gif'
        """
        if picname is None:
            return self._bgpicname
        if picname not in self._bgpics:
            self._bgpics[picname] = self._image(picname)
        self._setbgpic(self._bgpic, self._bgpics[picname])
        self._bgpicname = picname
# coding: utf-8
import pygame  
import os     
import sys
from pygame.locals import *
os.chdir('F:/微信公众号/Python/29.加载音乐')  
os.getcwd()                                  
pygame.init()                              
pygame.mixer.init()                          
pygame.mixer.music.load("告白.mp3")          
#pygame.mixer.music.set_volume(0.4)            
pygame.mixer.music.play()                    
bg_size = width, height = 300, 200            
bg_rgb = (255, 255, 255)
screen1 = pygame.display.set_mode(bg_size)
pygame.display.set_caption("告白音乐")
clock = pygame.time.Clock()                  
play_image = pygame.image.load("开始和暂停按钮2.png").convert_alpha()  
pause_image = pygame.image.load("开始和暂停按钮2.png").convert_alpha() 
pause_rect = pause_image.get_rect()        
print(pause_rect.width,pause_rect.height)    
pause_rect.left, pause_rect.top = (width - pause_rect.width) // 2, (height - pause_rect.height) // 2
from turtle import *
from random import random,randint
os.chdir('F:/微信公众号/Python/0.已发表') 
screen = Screen()
width ,height = 900,700
screen.setup(width,height)       
screen.title("告白")      
screen.bgcolor("black")  
screen.bgpic(r'./星空下互相告白的两个人2.gif')
screen.mode("logo")           
screen.delay(0)              
printer = Turtle()    
printer.hideturtle()
printer.penup()
printer.color('red')
printer.goto(-100,-350)
printer.write("In the whole universe\n\n",move = True, align="left", font=("Italic", 30, "bold"))
printer.goto(-50,-400)
printer.write("YZ I only love you!\n\n",move = True, align="left", font=("Italic", 30, "bold"))
t = Turtle(visible = False,shape='circle')
t.pencolor("white")       
t.fillcolor("white")      
t.penup()                 
t.setheading(-90)         
t.goto(width/2,randint(-height/2,height/2))
stars = []
for i in range(300):
    star = t.clone()       
    s =random()/3
    if  s>0.01 and s<0.03:
        star.pencolor("black")
        star.fillcolor("black")
    elif s>0.03 and s<0.04:
        star.pencolor("lightcoral")
        star.fillcolor("lightcoral")    
    elif s>0.05 and s<0.1:
        star.pencolor("green")
        star.fillcolor("green")
    elif s>0.15 and s<0.16:
        star.pencolor("yellow")
        star.fillcolor("yellow")
    elif s>0.19 and s<0.2:
        star.pencolor("red")
        star.fillcolor("red")
    elif s>0.21 and s<0.22:
        star.pencolor("purple")
        star.fillcolor("purple")
    elif s>0.29 and s<0.3:
        star.pencolor("darkorange")
        star.fillcolor("darkorange")   
    elif s>0.31 and s<0.32:
        star.pencolor("red")
        star.fillcolor("yellow")
    elif s>0.32 and s<0.33:
        star.pencolor("yellow")
        star.fillcolor("white")
    star.shapesize(s,s)
    star.speed(int(s*30))   
    star.setx(width/2 + randint(1,width))   
    star.sety( randint(-height/2,height/2))  
    #star.showturtle()     
    stars.append(star)      
i = 0
pause = False      
while True:
    i += 0
    for star in stars:

        star.setx(star.xcor() - 3 * star.speed())
        if star.xcor()<-width/2:
            star.hideturtle()
            star.setx(width/2 + randint(1,width))
            star.sety( randint(-height/2,height/2))
            star.showturtle()
    if i>= 100:
        break

    # 查找队列事件
    for event in pygame.event.get():
        # 查找点击关闭窗口事件
        if event.type == QUIT:               
            sys.exit
        # 查找鼠标左右击事件
        if event.type == MOUSEBUTTONDOWN:       
            if event.button == 1:             
                pause = not pause
            if event.button == 3:            
                pause = not pause

        if event.type == KEYDOWN:
            if event.key == K_SPACE:      
                pause = not pause
    screen1.fill(bg_rgb)
    if pause:
        pygame.mixer.music.pause()
        screen1.blit(pause_image, pause_rect)
    else:
        pygame.mixer.music.unpause()
        screen1.blit(play_image, pause_rect)
    pygame.display.flip()
    clock.tick(30)

Effect picture
  
picture
  
Note: If you need the source code and photos of the above picture, please reply "Confession under the Starry Sky" in the official account, and you can get it for free.
  
  

2. Photo Wall

  

#!/usr/bin/env python
# encoding: utf-8
from PIL import Image
import cv2
import os
os.chdir(r"F:\微信公众号\Python\30.520表白\代码\照片墙\new")
img = cv2.imread("start.jpg")      
height,width,channels = img.shape  
unit_size = 120                    
y_index = height//unit_size        
x_index = width//unit_size
new_img = Image.new('RGB',(width,height),'#FFFFFF')        
pic_list = []                     
for item in os.listdir("small_pictures"):
    if item.endswith(".jpg") or item.endswith(".JPG") : 
        pic_list.append(item)       
total = len(pic_list)  
x=0
y=0
for i in range(x_index*y_index):
    print(f"目前进度{
      
      i}/{
      
      x_index*y_index}")     
    test = Image.open("small_pictures/" + pic_list[i%total]).resize((unit_size,unit_size), Image.ANTIALIAS)  
    new_img.paste(test,(x*unit_size,y*unit_size))  
    x+=1
    if x==x_index:
        x=0
        y+=1
print("素材图合成完毕!")
new_img.save("out.jpg",quality=100)  
src1 = cv2.imread("start.jpg")      
src2 = cv2.imread("out.jpg")        
result = cv2.addWeighted(src1,0.7,src2,0.3,0) 
cv2.imwrite("result.jpg",result)

Rendering 1
  
picture
  

Rendering 2
  
picture

Note: If you need the source code and photos of the photo wall, please reply "photo wall" in the official account, and you can get it for free.
  
More articles about Tanabata confession are as follows:
  
Python version Bixin
  
Tanabata confession rose
  
eternal heart
  
Valentine's Day confession fireworks
  
My eyes are only you
  
Confession-Angel
  
in white with music character painting + color character painting-Valentine's Day confession code
  
teaches you how to use Python show love, sprinkle dog food - this is my so-and-so
  
If you are interested, you can go to the article page to read, I wish you all a happy Qixi Festival, and lovers will get married eventually.
  

参考文献
https://zhuanlan.zhihu.com/p/77129961
https://www.cnblogs.com/ooo888ooo/p/10629205.html
https://www.zhihu.com/question/306127738/answer/558080822?utm_source=wechat_session&utm_medium=social&utm_oi=1090367802518536192

[ Limited time free access to the group ] The group provides recruitment information related to learning Python, playing with Python, risk control modeling, artificial intelligence, and data analysis, excellent articles, learning videos, and can also exchange related problems encountered in learning and work. Friends who need it can add WeChat ID 19967879837, and add time to note the groups they want to join, such as risk control modeling.
  
You may be interested in:
Drawing Pikachu in PythonUsing
Python to draw word cloudsPython
face recognition - you are the only one in my eyesPython
draws a beautiful starry sky map (beautiful background)
Use the py2neo library in Python to operate neo4j and build an association mapPython
romance Confession source code collection (love, rose, photo wall, confession under the stars)

Guess you like

Origin blog.csdn.net/qq_32532663/article/details/132390098