用 python 写一个爱心代码
时间: 2023-12-09 08:36:29 浏览: 108
python爱心表白代码
以下是两种Python实现爱心的代码:
1.基于Python实现动态漂浮爱心的源码
```python
import random as ra
import math
import os
import time
class Heart():
#每个爱心(爱心类)
def __init__(self):
self.r = ra.randint(10,15) #爱心的半径
self.x = ra.randint(-1000,1000) #爱心的横坐标
self.y = ra.randint(-1000,1000) #爱心的纵坐标
self.color = (ra.randint(0,255),ra.randint(0,255),ra.randint(0,255)) #爱心的颜色
def draw(self,canvas):
#绘制爱心
for i in range(0,360,10):
x = int(self.r*math.sin(math.radians(i))**3)
y = int(self.r*math.cos(math.radians(i))**3)
canvas.set_at((self.x+x,self.y-y),self.color)
def main():
#初始化pygame
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()
#设置窗口大小
screen = pygame.display.set_mode((800,600))
#设置窗口标题
pygame.display.set_caption("Floating Hearts")
#设置背景颜色
screen.fill((255,255,255))
#创建爱心列表
hearts = []
for i in range(50):
hearts.append(Heart())
#循环绘制爱心
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#清空屏幕
screen.fill((255,255,255))
#绘制爱心
for heart in hearts:
heart.draw(screen)
heart.y -= 1
if heart.y < -1000:
heart.y = 600
#更新屏幕
pygame.display.update()
#延时
time.sleep(0.01)
if __name__ == '__main__':
main()
```
2.一行Python代码实现爱心
```python
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)]))
```
阅读全文