圣诞树代码python飘雪花
时间: 2023-12-23 08:27:53 浏览: 36
以下是用Python画圣诞树并添加飘雪花效果的代码:
```python
import random
def draw_tree(height):
stars = 1
for i in range(height):
print((' ' * (height - i)) + ('*' * stars))
stars += 2
def draw_snowflakes(num):
snowflakes = ["❄", "❅", "❆"]
for _ in range(num):
print(random.choice(snowflakes), end="")
print()
height = 5
draw_tree(height)
draw_snowflakes(height * 2)
```
这段代码首先定义了一个`draw_tree`函数,用于画圣诞树。然后定义了一个`draw_snowflakes`函数,用于画飘雪花效果。在主程序中,我们指定了圣诞树的高度为5,然后先画出圣诞树,再根据圣诞树的高度画出相应数量的飘雪花。
相关问题
圣诞树代码html飘雪花代码
以下是圣诞树代码和HTML飘雪花代码的示例:
1. 圣诞树代码
```python
def print_tree(height):
for i in range(height):
print(" " * (height - i - 1) + "*" * (2 * i + 1))
print_tree(5)
```
2. HTML飘雪花代码
```html
<!DOCTYPE html>
<html>
<head>
<style>
canvas { display: block; }
</style>
</head>
<body>
<canvas id="snowCanvas"></canvas>
<script>
const canvas = document.getElementById('snowCanvas');
const ctx = canvas.getContext('2d');
let snowflakes = [];
function createSnowflakes() {
const { innerWidth, innerHeight } = window;
canvas.width = innerWidth;
canvas.height = innerHeight;
for (let i = 0; i < 100; i++) {
snowflakes.push({
x: Math.random() * innerWidth,
y: Math.random() * innerHeight,
radius: Math.random() * 5 + 2,
speedX: Math.random() * 3 - 1.5,
speedY: Math.random() * 3 + 1,
});
}
}
function drawSnowflakes() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
ctx.beginPath();
for (let i = 0; i < snowflakes.length; i++) {
const snowflake = snowflakes[i];
ctx.moveTo(snowflake.x, snowflake.y); ctx.arc(snowflake.x, snowflake.y, snowflake.radius, 0, Math.PI * 2, true);
}
ctx.fill();
moveSnowflakes();
}
function moveSnowflakes() {
for (let i = 0; i < snowflakes.length; i++) {
const snowflake = snowflakes[i];
snowflake.x += snowflake.speedX;
snowflake.y += snowflake.speedY;
if (snowflake.y > canvas.height) {
snowflake.y = 0;
}
}
}
createSnowflakes();
setInterval(drawSnowflakes, 50);
</script>
</body>
</html>
```
圣诞树代码pyhton飘雪花
以下是一个用Python绘制圣诞树并飘雪花的代码示例:
```python
import turtle
import random
# 绘制圣诞树
def draw_tree():
height = 5
stars = 1
for i in range(height):
print((' ' * (height - i)) + ('*' * stars))
stars += 2
# 飘雪花
def snowfall():
turtle.speed(0)
turtle.penup()
turtle.goto(-300, 200)
turtle.pendown()
turtle.color("white")
turtle.shape("turtle")
turtle.shapesize(0.5)
for _ in range(100):
x = random.randint(-400, 400)
y = random.randint(-300, 300)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(10)
turtle.backward(10)
turtle.left(90)
turtle.forward(10)
turtle.backward(10)
turtle.right(90)
# 主函数
def main():
draw_tree()
snowfall()
turtle.done()
# 调用主函数
main()
```