drawing a point on the screen every 17ms in Python?

后端 未结 3 605
旧时难觅i
旧时难觅i 2020-12-04 01:01

I managed to string together a script that receives commands from an iOS app setting velocity and a direction.

The thing is I do not have the actual device, so my ap

3条回答
  •  暖寄归人
    2020-12-04 01:16

    You could use your terminal as a "window" and draw a "circle" in it. As a very simple (and unreliable) "timer", time.sleep() function could be used:

    #!/usr/bin/env python
    """Print red circle walking randomly in the terminal."""
    import random
    import time
    from blessings import Terminal # $ pip install blessings colorama
    import colorama; colorama.init() # for Windows support (not tested)
    
    directions = [(-1, -1), (-1, 0), (-1, 1),
                  ( 0, -1),          ( 0, 1),
                  ( 1, -1), ( 1, 0), ( 1, 1)]
    t = Terminal()
    with t.fullscreen(), t.hidden_cursor():
        cur_y, cur_x = t.height // 2, t.width // 2 # center of the screen
        nsteps = min(cur_y, cur_x)**2 # average distance for random walker: sqrt(N)
        for _ in range(nsteps):
            y, x = random.choice(directions)
            cur_y += y; cur_x += x # update current coordinates
            print(t.move(cur_y, cur_x) +
                  t.bold_red(u'\N{BLACK CIRCLE}')) # draw circle
            time.sleep(6 * 0.017) # it may sleep both less and more time
            print(t.clear) # clear screen
    

    To try it, save the code into random-walker.py and run it:

    $ python random-walker.py
    

    I don't know whether it works on Windows.

提交回复
热议问题