Starfield with UFOs




""" Random Stars and UFOs """

import tkinter as tk
import random, time
 
root = tk.Tk()
root.geometry('800x800')
root.title("Star Field")

canvas = tk.Canvas(root, width=700, height=700, bg='black')
canvas.pack(anchor = tk.CENTER, expand = True)

color = ['green', 'blue', 'gray']

""" Create Stars """ 
for y in range(700):
    for x in range(700):
        if random.randrange(10000) < 2: # upper limit not inclusive
            canvas.create_rectangle(x, y, x+3, y+3, fill='white')
        elif random.randrange(10000) < 20:
            canvas.create_rectangle(x, y, x+2, y+2, fill='white')

""" Create Saucer Traffic """
while True:
    y = random.randrange(700)
    c = color[random.randint(0, 2)] # both limits inclusive
    r = random.randint(0, 1)
    direction = 0

    if r == 1:
        saucer = canvas.create_oval(750, y, 760, y+4, fill=c)
        direction = -1
    else:
        saucer = canvas.create_oval(-60, y, -50, y+4, fill=c)
        direction = 1

    for i in range(800):
        canvas.move(saucer, direction, 0)
        canvas.update()
        time.sleep(.05)
    
    canvas.delete(saucer)   # off the screen, so delete
       
root.mainloop()

Back to Tom Fangrow's Home Page