0

I am trying to animate the below diamond pattern in such a way that, It will first print the centre "star" and then its 4 neighbours and so on.

               
               
       *       
               
               
               
       *       
    *  *  *    
       *       
               

       *       
    *  *  *    
 *  *  *  *  * 
    *  *  *    
       *       

I tried clearing the console but it did not work. Is there any other way to do it?

here is the code:

import os
import sys
import numpy as np

def get_string(pattern, num):
    string = ""
    for i in range(num):
        for j in range(num):
            if pattern[i][j] == 0:
                string += "   "
            else:
                string += " * "
        string += "\n"
    return string


num = 5
pattern = np.zeros((num, num))

loc = (num // 2)
pattern[loc, loc] = 1
string = get_string(pattern, num)
os.system("clear")
sys.stdout.write("\r" + string)
sys.stdout.flush()


for k in range(1, loc+1):
    for i in range(num):
        for j in range(num):
            eclu = abs(i - loc) + abs(j - loc)
            if eclu == k:
                pattern[i, j] = 1
    string = get_string(pattern, num)
    os.system("clear")
    sys.stdout.write("\r" + string)
    sys.stdout.flush()
Vishal T
  • 49
  • 7

1 Answers1

0

Use terminal codes to print at exatly the right location, rather than trying to write and then clear the terminal (effectively doing the job of your terminal yourself). Something like:

from blessings import Terminal
term = Terminal()
print(term.move(3,4),"*")
print(term.move(6,7),"*")

Of course, using a loop to work out where to place.

You don't have to use blessings: there are other libraries, or you can do it by hand. But blessings is quick and portable. Of course, you have to pip install blessings first.

References

https://github.com/erikrose/blessings

https://wiki.bash-hackers.org/scripting/terminalcodes

2e0byo
  • 5,305
  • 1
  • 6
  • 26