分(fēn)享幾個好玩的代碼

給你們分(fēn)享幾個有(yǒu)趣好玩的代碼

1. 迷你貪吃蛇遊戲(Python)

用(yòng)不到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)

用(yòng) qrcodePillow 庫生成個性化二維碼。

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)

一個小(xiǎo)工(gōng)具(jù)生成有(yǒu)趣的強密碼。

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())

你覺得哪個更有(yǒu)趣?