|
All of the following code is from the Animation vs. Coding video, except for most comments, which have been added here for your understanding.
# All comments are preceded by a hashtag symbol and have no effect on how the code operates, just like Python. # <-- THIS symbol precedes all comments, in other words. # Any comments already existing in the video will be noted by a second comment immediately after.
Yellow's Initial Experiments[]
hello # Result: NameError on "hello"!
print() # Result: Prints an empty string.
print("hi")
# Result: Prints "hi".
print("hi")
print("hi")
print("hi")
# Result: Prints "hi" three times.
a = 1 print(a) # Result: Prints "1".
Yellow alters this code a few times to change the value of a directly.
a = 3+2 # 3+2 returns 5 print(a) # Result: Prints "5".
Yellow tries the -, +, and / operands as well.
a = 3//2 # The // operand means integer floor division. The remainder, 2 in this case, is not printed. print(a) # Result: Prints "1".
a = 3+2 b = "string" print(b) # Result: Prints "string".
a = 3+2 b = "string" print(b+"ing") # Combines the value of integer b (the string "string") with "ing" at the end; the + operand with strings just merges the two into a larger string # Result: Prints "stringing".
a = 3+2 b = "string" print(b+b) # Result: Prints "stringstring".
a = 3+2 b = "string" print(b+a) # Result: TypeError on "b+a"!
It tried concatenating a string and a float, which does not work.
a = 3+2 b = "string" print(b+str(a)) # The str() operand makes whatever value is in the parentheses be treated as a string. # Result: Prints "string5".
It's now printing something that is entirely a string.
a = 3+2 b = "string" print(len(b+str(a))) # The len() operand returns the length of the value of whatever is in the parentheses. # Result: Prints "7".
a = "string" b = a[] # Incomplete position operand; there should be an integer in the brackets print() # Result: SyntaxError on "a[]"! # It wouldn't have printed anything anyway, since there is nothing in print().
The Laptop Gone Berserk[]
The laptop types:
a = "string"
b = a[0] # The position operand fetches whatever character is in that position. It is zero-based, meaning 0 will fetch the first item. ("s" in this case.)
print(b)
# Result: Attacks Yellow by printing "s" in his face.
The laptop follows up by altering the position number in a[0] to print-spit "t" and "r" at him.
Laptop types:
a = "string"
for i in a: # For each element, which will be considered "i", in the variable, which in this case is "a" (the string "string")...
print(i)
# Result: Attacks Yellow by printing "s", "t", "r", "i", "n", and "g" at him in that order.
# fun fact: i is often used because it is the first letter of the word "iterator".
# this is because i iterates over the items in the variable.
a = "bark"
while True: # While loops while the condition next to it equals True, so this creates an infinite loop
print(a)
# Result: Attacks Yellow with "bark" continuously
a = "bark"
while True:
print(a.upper()) # .upper gives the value of the string, but in all caps
# Result: More violently attacks Yellow with "BARK" continuously
Hurriedly, Yellow types in:
a = "bark" while a.isdigit(): # .isdigit() returns True if a is a digit (even if a string), False if a is not. print(a.upper()) # Result: IndentationError on print(a.upper())
while expects some indentation so that it knows what to loop over in the while loop. There is none here.
a = "bark"
while a.isdigit(): # a is not a digit, so the code never enters the loop.
print(a.upper())
# Result: Nothing.
Laptop types:
a = "1234"
while a.isdigit(): # a is now a digit, entering the loop.
print(a.upper())
# Result: Yellow gets attacked with "1234"
Yellow, in response:
a = "1234"
while not a.isprintable(): # not just turns the statement True if it was False, False if it was True. (.isprintable is as name implies)
print(a.upper())
# Result: Nothing.
Laptop:
a = "RRRAAAAAAAAAAAAAA"
while not a.isprintable(): # a is still a printable string, so the loop does not get entered
print(a.upper())
# Result: Nothing.
a = "RRRAAAAAAAAAAAAAA"
while not a.isprintable():
print(a.upper())
else: # the section in the else runs if the while loop doesn't run at all.
print(a)
# Result: Yellow gets fully flung away by the force of the string "RRRAAAAAAAAAAAAAA"
bomb = ['BANG', 'BOOM', 'BAM', 'POW', 'POOF', PAH'] # These brackets: [] are for lists print(*bomb) # the asterisk makes it print each item in a list in order print(*bomb) print(*bomb) print(*bomb) # Result: four bombs explode, each exploding into the 6 items of the bomb variable
Shell Shock[]
The laptop starts weaponizing the turtle!
import turtle # importing lets you use commands/functions in the import t = turtle.Turtle() # makes a turtle at the coordinate (0, 0) t.forward(400) # moves turtle in direction it's facing (starts facing to the right) # Result: Yellow gets hit by the turtle as it draws a white straight line
import turtle t = turtle.Turtle() t.forward(400) t.left(90) # turns turtle anti-clockwise 90 degrees. t.forward(800) # Result: Yellow gets hit by the turtle again, then launched upwards. # The turtle's drawing is now the shape of the corner of a square, with equal side lengths
import turtle
t = turtle.Turtle()
t.speed('fast') # 'fast' is the fastest speed with an animation
t.left(135)
t.forward(1280)
# Result: Yellow gets hit into rolling.
# The drawing is now an isoceles equilateral triangle
import turtle
t = turtle.Turtle()
t.speed('fast') # The options are: 'slowest', 'slow', 'normal', 'fast', and 'fastest'
t.right(90)
t.forward(400)
# Result: The turtle zooms past Yellow
Yellow throws the computer up and hits back:
import turtle
t = turtle.Turtle()
t.speed('fast') # You could also enter a number. 1 is slowest, slow is 3, 6 is normal, 10 is fast, 0 is fastest
t.right(135)
t.forward(900)
# Result: The laptop is hit mid-air.
As the laptop runs away:
t.left(85)
while True:
t.right(170)
t.forward(400)
t.left(170)
t.forward(400)
# Result: the turtle zig-zags to the right.
import string as ammo # instead using the word "string", you can write "ammo" gun = list(ammo.uppercase()) # normally, string.uppercase() returns "ABCDEFGHIJKLMNOPQRSTUVWXYZ" print(gun.pop()) # this prints the last letter of the gun variable and pops/deletes the last letter off of it. # Result: prints "Z"
The laptop runs this print(gun.pop()) a few times, printing Z and Y quickly, then 2 groups of 4 letters.
t.pensize(10) # same units as movement units Result: the lines get 10x thicker
t.speed('fastest')
# Normally this would not have any delays at the ends of every line, but there is a one-frame pause for animation purposes.
Laptop uses 5 more ammo from P to L
While lunging, Yellow types:
turtle.bye() # Result: The turtle is deleted
Laptop uses all remaining ammo.
Visualize This![]
(The laptop generates graphs)
import matplotlib as plt # Math/plotting library import numpy as np # For more advanced use of numbers in python val = np.random.randint(1, 10, 10) # makes a list of 10 random numbers between 1 and 10 plt.bar(range(len(val)), val) # plots a bar chart plt.show() # shows everything plotted # Result: a bar chart with 10 bars is made
while True:
val = np.random.randint(1, 10, 10)
plt.show() # Updates the plot
# Result: The bars on the bar chart move up and down a lot
# Again, there is a transition added for animation purposes in the video.
val = np.random.randint(1, 10, 20)
plt.figure(figsize=(10, 5)) # Makes the figure 10 : 5 side lengths ratio
plt.errorbar(range(len(val)), val, val,
fmt='o', capsize=6)
plt.show()
Laptop uses *val a few times, the same way as *bomb, but with numbers
plt.plot(range(20),
color='red')
plt.show()
plt.title(label='TITLE', # The title is literally the word 'TITLE'
fontsize=20,
loc='left'), # Makes the title appear on the left
plt.show()
# Result: 'TITLE' appears above the graph
plt.title(label='TITLE',
fontsize=20,
rotation=90, #
loc='right') # Now it's on the right
plt.show()
def fire(n, c=1)
if c>n:
return
print(' '*c-1+'*'*(2*(n-c)+1))
fire(n, c+1)
# This function uses recursion!
fire(5)
np.arrange(0, 30, 0.1) y = np.cos(x) plt.plot(x, y) # plots the new curvy line plt.show()
Game Over[]
(The laptop creates the Pygame instance)
import pygame
pygame.init()
screen = pygame.display.set_mode((4000, 2000)) # make a display 4000px wide, 2000px high
clock = pygame.time.Clock() # Clock is used for figuring out timing
square_pos = pygame.rect(2950, 1920, 50, 50) # Top left co-ord is (2950, 1920). Sides of 50 length.
while True:
if pygame.event.get(pygame.QUIT): break # If pygame detects quitting by clicking the X, break out of the loop
screen.fill('black') # Fill the screen with black so you can't see the last frame
pygame.draw.rect(screen, 'red', square_pos) # Draw on screen: a 'red' rect with the square_pos information
pygame.display.flip() # Update what you actually see
clock.tick(60) # Wait for a 1/60 seconds, using clock
pygame.quit()
import pygame
pygame.init()
screen = pygame.display.set_mode((4000, 2000))
clock = pygame.time.Clock()
square_pos = pygame.rect(2950, 1920, 50, 50)
while True:
if pygame.event.get(pygame.QUIT): break
keys = pygame.key.get_pressed() # keys = list of all keys being pressed
if keys[pygame.K_UP]: # if up arrow pressed...
square_pos.y -= 20 # move up (y increases going down)
if keys[pygame.K_DOWN]:
square_pos.y += 20
if keys[pygame.K_LEFT]:
square_pos.x -= 20 # move left (x increases going right)
if keys[pygame.K_RIGHT]:
square_pos.x += 20
screen.fill('black')
pygame.draw.rect(screen, 'red', square_pos)
pygame.display.flip()
clock.tick(60)
pygame.quit()
# yellow.get_pos() is used, which doesn't exist in actual python!
import pygame
pygame.init()
screen = pygame.display.set_mode((4000, 2000))
clock = pygame.time.Clock()
square_pos = pygame.rect(2950, 1920, 50, 50)
circle_pos = pygame.Vector2(1500, 1500) # this is for the middle of the circle
circle_spd = pygame.Vector2() # will represent an x and y change per frame
circle_rad = 20
circle_acc = 0.01 # how much the circle is pulled towards yellow
circle_speed_mul = 0.99 # times speed by this to slow down
bounce_str = 1.0 # how much speed the circle keeps from bouncing off a wall
while True:
if pygame.event.get(pygame.QUIT): break
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
square_pos.y -= 20
if keys[pygame.K_DOWN]:
square_pos.y += 20
if keys[pygame.K_LEFT]:
square_pos.x -= 20
if keys[pygame.K_RIGHT]:
square_pos.x += 20
circle_spd *= circle_spd_mul
circle.spd += (yellow.get_pos() - circle_pos)*circle_acc # accelerate towards yellow, faster if further away
if circle_pos[0]<circle_rad: # if touching left wall
circle_pos.update(circle_rad, circle_pos[1]) # move back to stop overlapping with the wall
circle_spd.update(-circle_spd[0]*bounce_str, circle_spd[1]) # bounce by flipping x speed
elif circle_pos[0]>screen.get_width-circle_rad: # right wall
circle_pos.update(screen.getwidth()-circle_rad, circle_pos[1])
circle_spd.update(-circle_spd[0]*bounce_str, circle_spd[1])
elif circle_pos[1]<circle_rad: # top wall
circle_pos.update(circle_pos[0], circle_rad)
circle_spd.update(-circle_spd[0], -circle_spd[1]*bounce_str)
elif circle_pos[1]>screen.get_height-circle_rad: #bottom wall
circle_pos.update(circle_pos[0], screen.get_height()-circle_rad)
circle_spd.update(-circle_spd[0], -circle_spd[1]*bounce_str)
circle_pos = circle_pos + circle_spd
screen.fill('black')
pygame.draw.circle(screen, "blue", circle_pos, circle_rad) # draw "blue" circle around the circle_pos coordinate
pygame.draw.rect(screen, "red", square_pos)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Yellow changes just one character:
import pygame
pygame.init()
screen = pygame.display.set_mode((4000, 2000))
clock = pygame.time.Clock()
square_pos = pygame.rect(2950, 1920, 50, 50)
circle_pos = pygame.Vector2(1500, 1500)
circle_spd = pygame.Vector2()
circle_rad = 20
circle_acc = 0.01
circle_speed_mul = 0.99
bounce_str = 1.0
while True:
if pygame.event.get(pygame.QUIT): break
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
square_pos.y -= 20
if keys[pygame.K_DOWN]:
square_pos.y += 20
if keys[pygame.K_LEFT]:
square_pos.x -= 20
if keys[pygame.K_RIGHT]:
square_pos.x += 20
circle_spd *= circle_spd_mul
circle.spd += (yellow.get_pos() - circle_pos)*circle_acc
if circle_pos[0]<circle_rad:
circle_pos.update(circle_rad, circle_pos[1])
circle_spd.update(-circle_spd[0]*bounce_str, circle_spd[1])
elif circle_pos[0]>screen.get_width-circle_rad:
circle_pos.update(screen.getwidth()-circle_rad, circle_pos[1])
circle_spd.update(-circle_spd[0]*bounce_str, circle_spd[1])
elif circle_pos[1]<circle_rad:
circle_pos.update(circle_pos[0], circle_rad)
circle_spd.update(-circle_spd[0], -circle_spd[1]*bounce_str)
elif circle_pos[1]>screen.get_height-circle_rad:
circle_pos.update(circle_pos[0], screen.get_height()*circle_rad) # <- THIS LINE GETS CHANGED
# the minus is changed to multiplication, changing the y pos a lot
# circle_rad is more than 1, so the circle practically teleports to somewhere like y = 40 000
circle_spd.update(-circle_spd[0], -circle_spd[1]*bounce_str)
circle_pos = circle_pos + circle_spd
screen.fill('black')
pygame.draw.circle(screen, "blue", circle_pos, circle_rad)
pygame.draw.rect(screen, "red", square_pos)
pygame.display.flip()
clock.tick(60)
pygame.quit()
A bit more weaponry[]
def fire(n, c=1)
if c>len(n):
return
print([ch for ch in n])
fire(n, c+1)
# This function prints each character in n, repeating that until c == the length of n
# Result: nothing, since functions just prepare code for later
fire(string.digits) # This prints 100 times! # it prints "0", "1", "2", up to "9" # Then, it prints 0 to 9, 9 more times, since "0123456789" is 10 characters long.
fire(string.ascii_letters) # this prints 52² times, since string.ascii letters is all capital and lower case letters.
def nuke(n):
a = []
for i in range(10):
if n > 1:
a.append(nuke(n-1))
else:
a.append(i)
return a
# this is a very deadly nuke.
# nuke(1) returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# nuke(2) returns [nuke(1), nuke(1), nuke(1), nuke(1), nuke(1), nuke(1), nuke(1), nuke(1), nuke(1), nuke(1)]
# and it just gets more and more lists inside of each other as n gets bigger.
print(nuke(10)) # This will try to print 10 000 000 000 numbers, and the formatting for all those lists too!
| Example output for nuke(2) |
|---|
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] |
| Example output for nuke(3) |
|---|
[[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3,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 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]] |
The laptop types:
GGgggrrRRrRRr!R!!! # Result: SyntaxError on "GGgggrrRRrRRr!R!!!"!
Yellow types:
#GGgggrrRRrRRr!R!!! # The above comment is the only Python comment that appears in the pygame section of the video. # Result: Nothing.
AI[]
Yellow writes an AI that is very complicated, but here is the basic steps that the program does:
- The input text separates into parts of words (tokens), which in turn becomes numbers
- A series of calculations are performed on them to get an output
- The calculations are repeatedly adjusted and tested until there is a good result
And here is the code you can see before the screen fades out:
import numpy as np
import torch
import torch.nn as nn
#define tensors
class TextDataSet(DataSet):
def __init__(self, text, tokenizer seq_len=30):
#create i/o pairs #comment in video
def __len__(self):
def __getitem__(self, idx):
#return tensors X and Y
#define Memory Model for laptop
class NeuralNetworkModel(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden # (comment not in video) It's cut off screen here
#embed network layers
def forward(self, y):
# (comment not in video) The inside of this function can't be seen, because of the fade to black
You can see the whole code after Yellow inputs a command (hello world). Here are all of the paragraphs of code, with no additional comments.
import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchtext from torchtext.data.utils import get_tokenizer from torch.data.utils import DataLoader, Dataset
#define tensors
class TextDataSet(DataSet):
def __init__(self, text, tokenizer seq_length=30):
self.tokenizer = tokenizer
self.seq_length = seq_length
# Tokenize the entire text into a list of words
self.tokens = tokenizer(text)
# Create i/o pairs, where Y is the next word
self.data = []
for i in range(len(self.tokens) - self.seq_length):
X = self.tokens[i:i+self.seq_length]
Y = self.tokens[i+self.seq_length]
self.data.append((X, Y))
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
X, Y = self.data[idx]
return torch.sensor(X), torch.sensor(Y)
#define Memory Model for laptop
class NeuralNetworkModel(nn.Module):
#embed network layers
def forward(self, y):
def num_feed(file_path):
num_string = ""
for data in data_stream:
try:
with open(file_path, 'r') as file:
for line in file:
line = line.strip
if line.isdigit():
num_string += line
except FileNotFoundError:
print(f"File not found: {file_path}")
except Exception as e:
print(f"An error occurred: {e}")
#ASCII conversion
ascii_codes = [num_string[i:i+3] for i in range(0, len(num_string), 3)]
ascii_characters = [chr(int(code)) for code in ascii_codes]
result = .join(ascii_characters)
return result
input_nums = num_feed('world/data/external/assoted_nuke_numbers.text')
#preprocess text
tokenizer = get_tokenizer('basic_english')
dataset = TextDataSet(book_text, tokenizer, seq_length=5)
#vocab to tokens
all_tokens = [token for sentence in dataset for token in sentence[0]]
vocab = set(all_tokens)
vocab_size = len(vocab)
word_to_idx = {word: idx for idx, word in enumerate(vocab)}
idx_to_word = {idx: word for word, idx in word_to_idx.items()}
# token to index
def tokens_to_indices(tokens):
return [word_to_idx[token] for token in tokens]
#dataset to index only
class IndexedTextDataset(TextDataSet):
def __getitem__(self, idx):
X, Y = super().__getitem__(idx)
return torch.sensor(tokens_to_indices(X)), torch.sensor(word_to_idx[idx_to_word[Y]])
indexed_dataset = IndexedDataSet(book_text, tokenizer, seq_length=5)
#create dataloaders
batch_size = 2
data_loader = DataLoader(indexed_dataset, batch_size=batch_size, shuffle=True)
#create dataloaders
embedding_dim = 10
hidden_dim = 50
model = NeuralNetModel(vocab_size, embedding_dim, hidden_dim, seq_length=5)
#loss and optimiser
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
#training loop
epochs = 1000
for epoch in range(epochs):
total_loss = 0
for X, Y in data_loader():
#pass forward
optimiser.zero_grad()
output = model()
#calculate loss
loss = criterion(output, Y)
loss.backward()
#update
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {total_loss/len(data_loader):.4f}")
def predict_next_word(input_sequence):
model.eval()
input_indices = torch.sensor(tokens_to_indices(input_sequence)).unsqueeze(0)
with torch.no_grad():
output = model(input_indices)
_, predicted_idx = torch.max(output, dim=1)
total_loss += loss.item()
return idx_to_word[predicted_index.item()]
input_sequence = input.split()
predicted_word = predict_next_word(input_sequence)
print(f"Input:'{' '.join(input_sequence)}")
laptop_font = pygame.font.Font('Consolas.ttf', 20)
laptop_say = laptop_font.render(predicted_word, True, white, black)
