给你们分享几个有趣好玩的代码
1. 迷你贪吃蛇游戏(Python)
用不到100行代码实现一个终端版的贪吃蛇游戏。
import curses
from random import randint
def main(stdscr):
curses.curs_set(0)
stdscr.nodelay(1)
stdscr.timeout(100)
sh, sw = stdscr.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
snake = [[sh//2, sw//4]]
food = [sh//3, sw//2]
w.addch(food[0], food[1], curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
head = snake[0]
if key == curses.KEY_DOWN:
new_head = [head[0] + 1, head[1]]
elif key == curses.KEY_UP:
new_head = [head[0] - 1, head[1]]
elif key == curses.KEY_LEFT:
new_head = [head[0], head[1] - 1]
elif key == curses.KEY_RIGHT:
new_head = [head[0], head[1] + 1]
if new_head in snake or new_head[0] in [0, sh] or new_head[1] in [0, sw]:
break
snake.insert(0, new_head)
if new_head == food:
food = None
while food is None:
nf = [randint(1, sh-2), randint(1, sw-2)]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
w.addch(new_head[0], new_head[1], curses.ACS_CKBOARD)
w.addstr(sh//2, sw//2, "Game Over!")
w.getch()
curses.wrapper(main)
2. 生成炫酷的二维码(Python)
用 qrcode
和 Pillow
库生成个性化二维码。
import qrcode
from PIL import Image
def generate_custom_qr(data, logo_path=None, output_file="custom_qr.png"):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white").convert('RGB')
if logo_path:
logo = Image.open(logo_path)
basewidth = img.size[0] // 4
wpercent = basewidth / float(logo.size[0])
hsize = int(float(logo.size[1]) * float(wpercent))
logo = logo.resize((basewidth, hsize), Image.ANTIALIAS)
pos = ((img.size[0] - logo.size[0]) // 2, (img.size[1] - logo.size[1]) // 2)
img.paste(logo, pos)
img.save(output_file)
print(f"QR Code saved as {output_file}")
generate_custom_qr("https://yourblog.com", logo_path="path/to/logo.png")
3. 随机生成星空动画(HTML+CSS+JavaScript)
实现一个简单的动态星空背景。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Starry Sky</title>
<style>
body {
margin: 0;
background: black;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="starrySky"></canvas>
<script>
const canvas = document.getElementById("starrySky");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const stars = Array(200).fill().map(() => ({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
r: Math.random() * 2,
d: Math.random() * 0.5,
}));
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
stars.forEach(star => {
ctx.beginPath();
ctx.arc(star.x, star.y, star.r, 0, Math.PI * 2);
ctx.fillStyle = "white";
ctx.fill();
});
}
function update() {
stars.forEach(star => {
star.x += star.d;
star.y -= star.d;
if (star.x > canvas.width || star.y < 0) {
star.x = Math.random() * canvas.width;
star.y = canvas.height;
}
});
}
function animate() {
draw();
update();
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
4. 趣味密码生成器(Python)
一个小工具生成有趣的强密码。
import random
import string
def generate_fun_password(length=12):
words = ["Sun", "Moon", "Star", "Cloud", "Wind", "Tree", "Sky"]
special_chars = "!@#$%^&*"
password = random.choice(words)
password += ''.join(random.choices(string.ascii_letters + string.digits, k=length - len(password) - 1))
password += random.choice(special_chars)
return ''.join(random.sample(password, len(password)))
print("Your fun password:", generate_fun_password())
你觉得哪个更有趣?