以下是一個簡單的Python流星雨代碼示例:
import random
import time
# 設置屏幕大小
WIDTH = 80
HEIGHT = 20
# 創建流星
def create_meteor():
x = random.randint(0, WIDTH)
y = random.randint(0, HEIGHT // 2)
speed = random.randint(1, 3)
return {'x': x, 'y': y, 'speed': speed}
# 移動流星
def move_meteor(meteor):
meteor['y'] += meteor['speed']
if meteor['y'] > HEIGHT:
meteor['x'] = random.randint(0, WIDTH)
meteor['y'] = random.randint(0, HEIGHT // 2)
meteor['speed'] = random.randint(1, 3)
# 繪制畫面
def draw_screen(meteors):
screen = [[' '] * WIDTH for _ in range(HEIGHT)]
for meteor in meteors:
x = meteor['x']
y = meteor['y']
screen[y][x] = '*'
for row in screen:
print(''.join(row))
# 游戲循環
def game_loop():
meteors = [create_meteor() for _ in range(10)]
while True:
move_meteor(meteors[0]) # 只移動第一個流星
draw_screen(meteors)
time.sleep(0.1)
if __name__ == '__main__':
game_loop()
這個代碼使用了ASCII字符來繪制流星雨的效果。在游戲循環中,每次移動第一個流星,并重新繪制畫面。流星超過屏幕高度后會重新生成一個位置和速度。