Python 2D Iteration and Animation
Several 2D arrays and Animations hacks are provided to further learn iteration and data in Python. The objective is to build a stronger foundation in iteration and data. Also, it is important to see concepts like printing color and moving objects in terminal, prior to moving to frontend development with JavaScript.
- 2D Programming and Resources
- Monkey Jumpers Poem
- Animation, the Energetic versus Lazy Programmer methods
2D Programming and Resources
There are lots of applications for 2D data. Common terms in 2D are tabular data, row/columns, matrix, etc. Nested iterative loops are often used to find or discover each cell in a 2D array.
- 2D samples and challenges in Jupyter. wget link:https://raw.githubusercontent.com/nighthawkcoders/APCSP/master/_notebooks/2023-05-16-DS-arrays_lab.ipynb- Mario animations in JS, these are markdown code examples.
- Assets metadata yml, wget and place in _data directory; sprite, download and place in images directory
- Code to interact with Sprite Animations runtime, wget code
- Game starters runtime, wget imperative code, wget oop code
"""
* Creator: Nighthawk Coding Society
2D arrays
"""
# Classic nested loops using ij indexes, this shows 2 dimensions
def print_matrix(matrix):
print("Classic nested loops using ij indexes")
for i in range(len(matrix)): # outer loop (i), built on length of matrix (rows)
for j in range(len(matrix[i])): # inner loop (j), built on length of items (columns)
print(matrix[i][j], end=" ") # [i][j] is 2D representation, end changes newline to space
print()
def test_matrices():
# setup some text matrices
keypad = [[" ", " ", " ^", " ", " "],
[" ", " /", "|", "\ ", " "],
[" ", " /", "|", "\ ", " "],
[" ", "/_/_|_\_\ "],
[" ", " ", " | |", " ", " "],
]
keyboard = [["`", 1, " ", 2, " ",3, " ", 4, " ", 5, " ", 6, " ", 7, " ", 8, " ", 9, " ", 0, " ", "-"," ", "="],
[" ", " ", "Q", " ", "W", " ", "E", " ", "R", " ", "T", " ", "Y", " ", "U", " ", "I", " ", " ", "O", " ", "P", " ", "[", " ", "]", " ", "\\"],
[" ", " ", " ", "A", " ", "S", " ", "D", " ", "F", " ", "G", " ", "H", " ", "J", " ", "K", " ", "L", " ", ";", " ", "'"],
[" ", " ", " ", " ", "Z", " ", "X", " ", "C", " ", "V", " ", "B", " ", "N", " ", "M", " ", ",", " ", ".", " ", "/"]]
numbers = [
[0, 1], # binary
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], # decimal
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] # hexadecimal
]
# pack into a list of matrices with titles
matrices = [
["Keypad", keypad],
["Keyboard", keyboard],
["Number Systems", numbers]
]
# loop 2D matrix with returning list in [key, value] arrangement
for title, matrix in matrices: # unpack title and matrix as variables
# formatted message with concatenation
print(title, len(matrix), "x", "~" + str(len(matrix[0])))
# use three different methods
print_matrix(matrix)
# blank link in between
print()
# tester section
if __name__ == "__main__":
test_matrices()
JavaScript 2D array
Example below populate a 2D array. Key concepts are ij loop and assignments. Observe the object that is created in console. Learn the basics of iteration through 2D array in JavaScript.
- Candy challenge:Work of pairs. Create one of the Python examples (christmas tree, keyboard, ...). Use the element.append to output within the notebook. As you work on JavaScript make sure your development enviornment is setup like JavaScript programmer.
%%js
/*
* Creator: Nighthawk Coding Society
Construct a two-dimensional array in JS
*/
var order = [" ","^", " ","/"," |"," \\ ","/"," |"," \\ "," ", "| |", " "];
var arr2D = [];
var rows = 3;
var cols = 4;
var x = 0;
// Loop to initialize 2D array elements
for (var i = 0; i < cols; i++) {
arr2D[i]=[];
for (var j = 0; j < rows; j++) {
arr2D[i][j] = order[j + x];
}
x += 3;
arr2D[i][j] = "<br>";
}
console.log(arr2D);
element.append(arr2D.map(row => row.join('')).join(''));
import time
from IPython.display import clear_output
def main():
Red = "\u001b[31m"
Green = "\u001b[32m"
Yellow = "\u001b[33m"
Blue = "\u001b[34m"
Magenta = "\u001b[35m"
monkeys = [
[
Red + "ʕง ͠° ͟ل͜ ͡°)ʔ ",
Red + " \\_⏄_/ ",
Red + " --0-- ",
Red + " ⎛ ⎞ "
],
[
Green + " ʕ༼ ◕_◕ ༽ʔ ",
Green + " \\_⎏_/ ",
Green + " ++1++ ",
Green + " ⌋ ⌊ "
],
[
Yellow + " ʕ(▀ ⍡ ▀)ʔ",
Yellow + " \\_⎐_/ ",
Yellow + " <-2-> ",
Yellow + " 〈 〉 "
],
[
Blue + "ʕ ͡° ͜ʖ ° ͡ʔ",
Blue + " \\_⍾_/ ",
Blue + " ==3== ",
Blue + " _/ \\_ "
],
[
Magenta + " (◕‿◕✿) ",
Magenta + " \\_⍾_/ ",
Magenta + " ==4== ",
Magenta + " _/ \\_ "
]
]
for i in range(len(monkeys), -1, -1):
clear_output(wait=True)
print("Nursery Rhyme")
print(str(i) + " little monkeys jumping on the bed...")
for part in range(len(monkeys[0])):
for row in range(i - 1, -1, -1):
print(monkeys[row][part], end=" ")
print()
print("\u001b[0m")
time.sleep(2)
clear_output(wait=True)
print("No more monkeys jumping on the bed")
print("0000000000000000000000000000000000")
print(" THE END ")
if __name__ == "__main__":
main()
Animation, the Energetic versus Lazy Programmer methods
Animation is done like the old Disney films, lots of little images put togehter. In these examples we eliminate using a 2D array, but simulate int with a sequence of print statements.
- This 1st sequence is a lot of lines of code.
- The 2nd takes the lazy programmer method to do the same.
- Candy challenge:Make you own ASCII art animation.
"""
* Creator: Nighthawk Coding Society
Sailing Ship Animation (long method)
"""
import time # used for delay
from IPython.display import clear_output # jupyter specific clear
# ANSI Color Codes
Color34 = "\u001b[34m"
Color37 = "\u001b[37m"
# As you can see, its not very optimal
def ship1():
print(" |\ ")
print(" |/ ")
print("\__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
def ship2():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship3():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship4():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship5():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
def ship6():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship7():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship8():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
def ship9():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship10():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship11():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
def ship12():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship13():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship14():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship15():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
def ship16():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship17():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
def ship18():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \u001b[37m")
def ship19():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
def ship20():
print(" |\ ")
print(" |/ ")
print(" \__ |__/ ")
print(" \____/ ")
print("\u001b[34m -------------------------------------------- \u001b[37m")
clear_output(wait=True)
time.sleep(.1)
ship1()
time.sleep(.5)
clear_output(wait=True)
ship2()
time.sleep(.5)
clear_output(wait=True)
ship3()
time.sleep(.5)
clear_output(wait=True)
ship4()
time.sleep(.5)
clear_output(wait=True)
ship5()
time.sleep(.5)
clear_output(wait=True)
ship6()
time.sleep(.5)
clear_output(wait=True)
ship7()
time.sleep(.5)
clear_output(wait=True)
ship8()
time.sleep(.5)
clear_output(wait=True)
ship9()
time.sleep(.5)
clear_output(wait=True)
ship10()
time.sleep(.5)
clear_output(wait=True)
ship11()
time.sleep(.5)
clear_output(wait=True)
ship12()
time.sleep(.5)
clear_output(wait=True)
ship13()
time.sleep(.5)
clear_output(wait=True)
ship14()
time.sleep(.5)
clear_output(wait=True)
ship15()
time.sleep(.5)
clear_output(wait=True)
ship16()
time.sleep(.5)
clear_output(wait=True)
ship17()
time.sleep(.5)
clear_output(wait=True)
ship18()
time.sleep(.5)
clear_output(wait=True)
ship19()
time.sleep(.5)
clear_output(wait=True)
ship20()
time.sleep(.5)
"""
* Creator: Nighthawk Coding Society
Sailing Ship Animation (programatic method)
"""
import time # used for delay
from IPython.display import clear_output # jupyter specific clear
# ANSI Color Codes
OCEAN_COLOR = u"\u001B[34m\u001B[2D"
SHIP_COLOR = u"\u001B[35m\u001B[2D"
RESET_COLOR = u"\u001B[0m\u001B[2D"
def ship_print(position): # print ship with colors and leading spaces according to position
clear_output(wait=True)
print(RESET_COLOR)
sp = " " * position
print(sp + " |\ ")
print(sp + " |/ ")
print(SHIP_COLOR, end="")
print(sp + "\__ |__/ ")
print(sp + " \____/ ")
print(OCEAN_COLOR + "--"*32 + RESET_COLOR)
def ship(): # ship function, loop/controller for animation speed and times
# loop control variables
start = 0 # start at zero
distance = 60 # how many times to repeat
step = 2 # count by 2
# loop purpose is to animate ship sailing
for position in range(start, distance, step):
ship_print(position) # call to function with parameter
time.sleep(.2)
ship() # activate/call ship function
import math
import time
from IPython.display import clear_output # jupyter specific clear
def main():
A = 0
B = 0
i = 0
j = 0
k = 0
z = [0.0] * 1760
b = [' '] * 6272
print("\x1b[2J")
start_time = time.time()
while time.time() - start_time < 10: # Time limit of 5 seconds
b = [' '] * 6272
z = [0.0] * 7040
for j in range(0, int(6.28 * 100), int(0.07 * 100)):
for i in range(0, int(6.28 * 100), int(0.02 * 100)):
c = math.sin(i / 100.0)
d = math.cos(j / 100.0)
e = math.sin(A)
f = math.sin(j / 100.0)
g = math.cos(A)
h = d + 2
D = 1 / (c * h * e + f * g + 5)
l = math.cos(i / 100.0)
m = math.cos(B)
n = math.sin(B)
t = c * h * g - f * e
x = int(40 + 30 * D * (l * h * m - t * n))
y = int(12 + 15 * D * (l * h * n + t * m))
o = x + 80 * y
N = int(8 * ((f * e - c * d * g) * m - c * d * e - f * g - l * d * n))
if 22 > y > 0 and 80 > x > 0 and D > z[o]:
z[o] = D
b[o] = ".,-~:;=!*#$@"[N if N > 0 else 0]
print("\x1b[H")
for k in range(1760):
print(b[k], end='\n' if (k + 1) % 80 == 0 else '')
A += 0.00048
B += 0.00024
time.sleep(0.03)
clear_output(wait=True)
if __name__ == '__main__':
main()