阅读量:0
以下是一个简单的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字符来绘制流星雨的效果。在游戏循环中,每次移动第一个流星,并重新绘制画面。流星超过屏幕高度后会重新生成一个位置和速度。