Sunday, September 13, 2020

Numworks: Generating a Colorful Matrix

Numworks:  Generating a Colorful Matrix 

(updated 10/18/2021)


Introduction

Today's script generates a 3 x 3 matrix of random integers from 1 - 9 which each of the numbers are assigned a color.  The numbers are displayed in a 3 x 3 grid using the 320 x 240 pixel screen.  

The colors which are assigned to each number are:

1:  Shamrock Green  (0, 158, 96)

2:  Denim Blue (21, 96, 189)

3:  Navy Blue (0, 0, 128)

4:  Indigo (75, 0, 130)

5:  Red (255, 0, 0)

6:  Rose (255, 0, 127)

7:  Brown (101, 67, 33)

8:  Orange (255, 127, 39)

9:  Gold (255, 223, 0)


Numworks Python Script:  colormtx.py


from math import *

from random import *

from kandinsky import *


# 2020-08-25 EWS


# color arrays

# red

mr = [ 0, 21, 0, 75, 255, 255, 101, 255, 255 ]

# green

mg = [ 158, 96, 0, 0, 0, 0, 67, 127, 223 ]

# blue 

mb = [ 96, 189, 128, 130, 0, 127, 33, 39, 0 ]


# set up matrix

mat = [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]


# generate random numbers, assign colors 

for r in range(3): 

 for c in range(3):

  mat[ r ][ c ] = randint(1,9)

  x = 80 + 80 * c

  y = 60 + 60 * r

  s = mat[ r ][ c ]

  draw_string(str(s), x, y, color(mr[s-1], mg[s-1], mb[s-1]))


Download the code here:  https://my.numworks.com/python/ews31415/colormtx


Gratitude to Brian who let me know about my typo on the last line, it was missing the final right parenthesis.  


Remember that the index of arrays and matrices go from 0 to n-1.  

Examples






Eddie

All original content copyright, © 2011-2020.  Edward Shore.   Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited.  This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author. 


Spotlight: Akron Brass FireCalc Pocket Computer

Spotlight: Akron Brass FireCalc Pocket Computer Welcome to a special Monday Edition of Eddie’s Math and Calculator blog. Thi...