Hi! Hope you're enjoying this blog. I have a new home at www.goldsborough.me. Be sure to also check by there for new posts <3

Friday, February 7, 2014

Matrix rain in Python

Feeling Matrixy? How about making it digitally rain - in Python.



On the wikipedia article about the matrix digital rain, I found out what letters are typically used for that matrix effect, namely a form of Katakana (Japanese) letters. Moreover, it is useful to know the ord() and the chr() functions. The former transforms a character into its Unicode equivalent and chr() does the opposite: it transforms a number into a Unicode character.

The code is a piece of cake, for Python 3.x:


import time,random

items = [chr(i) for i in range(0x30a1, 0x30ff + 1)] # katakana


for i in range(1,11): # spaces and numbers
    items.append(str(i))
    items.append(" "*i)

def rain(row,column):         # rows,columns
     for i in range(row): #for every row
             s = ''      #new string
             for j in range(column): #for every column (or character)
                     ri = random.randrange(len(items)) #random index
                     s += items[ri]
             print(s)
             time.sleep(0.05) # change this to whatever makes the rain a good speed




For Python 2.x, do this for the unicode:


items = [unichr(i) for i in range(0x30a1,0x30ff + 1)]



First, import random and time. Then we need to add all the Unicode Katakana characters to the items list, the list where all possible items are stored. This is done via a list comprehension that goes through the range of the Katakana Unicode values. These values are in hexadecimal. You could also just do:


items = [chr(i) for i in range(12449,12544)]


I did it this way because those are the official Unicode values and the range of the Katakana characters is between 0x30a1 and 0x30ff. Next we put some numbers and spacing in.

The function takes the number or rows and the number of columns as a parameter. Then it loops through the ranges and fills a string with characters. This is done by getting a random index and adding the character at that position in items to the string. At the end of the row, we print out the string. The time.sleep() is there so you can control the speed of the rain.

Do not do this in IDLE! IDLE is just too slow, it won't look good. The best thing is to do it in your terminal. If your terminal let's you change the layout, try to get that black background/neon green text look.

6 comments :

  1. items = [chr(i) for i in range(0x30a1,0x30ff + 1) )] # katakana it does not like the ) in-between the ) and the ]

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Is their any way to change the font to numbers or something?

    ReplyDelete
  4. I didn't worked in my python 3.7

    ReplyDelete