[PYTHON] Code of "Programming picture book starting from 10 years old"

"Programming picture book starting from 10 years old" was a very good book, so Copy the Python and JavaScript code for children and parents studying in this book. I would be grateful if you could refer to it when it gets stuck.

By the way, from the appearance of the cover, it looks like an introductory book on scratch and Python, Besides that,

I was surprised that it was written in an easy-to-understand manner. I wanted to read it when I was 10 years old, and I envy the children who can learn from this book. Of course, it's not a stemmer.

Then, I will copy the sutras immediately.

3 Let's play with python

Project 4: Yurei Game

Yurei game.py


# p.96 Yurei Game
# Ghost Game

from random import randint
print('Yurei game')
feeling_brave = True
score = 0
while feeling_brave:
    ghost_door = randint(1, 3)
    print('There are three doors.')
    print('There is a ghost behind one of the doors.')
    print('Now, what number door to open?')
    door = input('1, 2, or 3?')
    door_num = int(door)
    if door_num == ghost_door:
        print('Yurei!')
        feeling_brave = False
    else:
        print('There was no Yurei!')
        print('I put it in the next room.')
        score = score + 1
print('Run away!')
print('Game over!The score is', score, 'is.')

Branch

python


# p.121 Choose one of several processes

a = int(input('a = '))
b = int(input('b = '))
op = input('Add/Pull/Call/War:')
if op == 'Add':
    c = a + b
elif op == 'Pull':
    c = a - b
elif op == 'Call':
    c = a * b
elif op == 'War':
    c = a / b
else:
    c = 'error'
print('answer= ',c)

Repeatedly in python

python


# p.122 Repeat in Python

from turtle import *
forward(100)
right(120)
forward(100)
right(120)
forward(100)
right(120)

python


for i in range(3):
    forward(100)
    right(120)

python


# p.123 Nested structure(nesting)Loop

n = 3
for a in range(1, n + 1):
    for b in range(1, n + 1):
        print(b, 'x', a, '=', b * a)

function

python


# p.130 How to make and call a function

def greeting():
    print('Hello!')

greeting()

python


# p.131 Pass data to a function

def height(m, cm):
    total = (100 * m) + cm
    print(total, 'It's a centimeter high')

height(1,45)

python


# p.131 Returns data from a function

def num_input(prompt):
    typed = input(prompt)
    num = int(typed)
    return num

a = num_input('Please enter a')
b = num_input('Please enter b')
print('a + b =', a + b)

Project 5: Automatic composition machine

python


# pp.132-133 Automatic composition machine

#Create sentences automatically
name = ['Takashi', 'Newton', 'Pascal']
noun = ['Lion', 'Bicycle', 'Airplane']
verb = ['buy', 'Ride around', 'Hit']

from random import randint
def pick(words):
    num_words = len(words)
    num_picked = randint(0, num_words - 1)
    word_picked = words[num_picked]
    return word_picked

print(pick(name), pick(noun), pick(verb), end='。\n')

python


#Continue to write sentences
while True:
    print(pick(name), pick(noun), pick(verb), end='。\n')
    input()

Project 6: Drawing machine

python


# p.140

from turtle import *
reset()
left(90)
forward(100)
right(45)
forward(70)
right(90)
forward(70)
right(45)
forward(100)
right(90)
forward(100)

Function "turtle_controller"

python


# p.142
from turtle import *

def turtle_controller(do, val):
    do = do.upper()
    if do == 'F':
        forward(val)
    elif do == 'B':
        backward(val)
    elif do == 'R':
        right(val)
    elif do == 'L':
        left(val)
    elif do == 'U':
        penup()
    elif do == 'D':
        pendown()
    elif do == 'N':
        reset()
    else:
        print('There was an unknown order')

python


turtle_controller('F' , 100)
turtle_controller('R' , 90)
turtle_controller('F' , 50)

Create function "string_artist"

python


# p.144 
program = 'N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100'
cmd_list = program.split('-')
cmd_list

Write the following source code below the source code on page 142.

python


def string_artist(program):
    cmd_list = program.split('-')
    for command in cmd_list:
        cmd_len = len(command)
        if cmd_len == 0:
            continue
        cmd_type = command[0]
        num = 0
        if cmd_len > 1:
            num_string = command[1:]
            num = int(num_string)
        print(command, ':', cmd_type, num)
        turtle_controller(cmd_type, num)

python


# p.145
string_artist('N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100')

Create an input screen for the user

Enter the source code on pages 142 and 144.

python


# p.146
instructions = '''Enter instructions for the turtle:
Example F100-R45-U-F100-L45-D-F100-R90-B50
N =Start scratching anew
U/D =Lower the pen/increase
F100 =Take 100 steps forward
B50 =Take 50 steps backwards
R90 =Rotate 90 degrees to the right
L45 =Rotate 45 degrees to the left'''
screen = getscreen()
while True:
    t_program = screen.textinput('Drawing machine', instructions)
    print(t_program)
    if t_program == None or t_program.upper() == 'END':
        break
    string_artist(t_program)

python


# p.147
N-L90-F100-R45-F70-R90-F70-R45-F100-R90-F100-
B10-U-R90-F10-D-F30-R90-F30-R90-F30-R90-F3

By the way, if you continue to write the code of Project 6: drawing machine

python


# p.142 Function "turtle_controller」
from turtle import *
def turtle_controller(do, val):
    do = do.upper()
    if do == 'F':
        forward(val)
    elif do == 'B':
        backward(val)
    elif do == 'R':
        right(val)
    elif do == 'L':
        left(val)
    elif do == 'U':
        penup()
    elif do == 'D':
        pendown()
    elif do == 'N':
        reset()
    else:
        print('There was an unknown order')

# p.144 function "string_Make an artist
def string_artist(program):
    cmd_list = program.split('-')
    for command in cmd_list:
        cmd_len = len(command)
        if cmd_len == 0:
            continue
        cmd_type = command[0]
        num = 0
        if cmd_len > 1:
            num_string = command[1:]
            num = int(num_string)
        print(command, ':', cmd_type, num)
        turtle_controller(cmd_type, num)

# p.146 Create an input screen for the user
instructions = '''Enter instructions for the turtle:
Example F100-R45-U-F100-L45-D-F100-R90-B50
N =Start scratching anew
U/D =Lower the pen/increase
F100 =Take 100 steps forward
B50 =Take 50 steps backwards
R90 =Rotate 90 degrees to the right
L45 =Rotate 45 degrees to the left'''
screen = getscreen()
while True:
    t_program = screen.textinput('Drawing machine', instructions)
    print(t_program)
    if t_program == None or t_program.upper() == 'END':
        break
    string_artist(t_program)

Bugs and debugging

python


# p.148

top_num = 5
total = 0
for n in range(top_num):
    total = total + n
print('From 1', top_num, 'Total up to', total)

python


# p.149

top_num = 5
total = 0
for n in range(top_num):
    total = total + n
    print('debug: n=', n, 'total=', total)
    input()
print('From 1', top_num, 'Total up to', total)

python


# p.149

top_num = 5
total = 0
for n in range(1, top_num + 1):
    total = total + n
    print('debug: n=', n, 'total=', total)
    input()
print('From 1', top_num, 'Total up to', total)

Make a window

python


# p.154 Easy window
from tkinter import *
window = Tk()

python


# p.154 Add a button to the window

from tkinter import *
def bAaction():
    print('Thank you!')
def bBaction():
    print('Ouch!That's fucked up!')
window = Tk()
buttonA = Button(window, text='Press!', command=bAaction)
buttonB = Button(window, text='Don't press!', command=bBaction)
buttonA.pack()
buttonB.pack()

python


# p.155 Roll the dice

from tkinter import *
from random import randint
def roll():
    text.delete(0.0, END)
    text.insert(END, str(randint(1, 6)))
window = Tk()
text = Text(window, width=1, height=1)
buttonA = Button(window, text='Press here to roll the dice', command=roll)
text.pack()
buttonA.pack()

Color and coordinates

python


# p.157
from random import *
from tkinter import *
size = 500
window = Tk()
canvas = Canvas(window, width=size, height=size)
canvas.pack()
while True:
    col = choice(['pink', 'orange', 'purple', 'yellow'])
    x0 = randint(0, size)
    y0 = randint(0, size)
    d = randint(0, size/5)
    canvas.create_oval(x0, y0, x0 + d, y0 + d,  fill=col)
    window.update()

Draw a shape

python


# p.158 Draw basic shapes
>>> from tkinter import *
>>> window = Tk()
>>> drawing = Canvas(window, height=500, width=500)
>>> drawing.pack()
>>> rect1 = drawing.create_rectangle(100, 100, 300, 200)
>>> square1 = drawing.create_rectangle(30, 30, 80, 80)
>>> oval1 = drawing.create_oval(100, 100, 300, 200)
>>> circle1 = drawing.create_oval(30, 30, 80, 80)

python


# p.158 Using coordinates
>>> drawing.create_rectangle(50, 50, 250, 350)

python


# p.159 Coloring shapes
>>> drawing.create_oval(30, 30, 80, 80, outline='red', fill='blue')

python


# p.159 Let's write an alien

from tkinter import *
window = Tk()
window.title('alien')
c = Canvas(window, height=300, width=400)
c.pack()
body = c.create_oval(100, 150, 300, 250, fill='green')
eye = c.create_oval(170, 70, 230, 130, fill='white')
eyeball = c.create_oval(190, 90, 210, 110, fill='black')
mouth = c.create_oval(150, 220, 250, 240, fill='red')
neck = c.create_oval(200, 150, 200, 130)
hat = c.create_polygon(180, 75, 220, 75, 200, 20, fill='blue')

Change graphics

python


# p.160 Move shapes
>>> c.move(eyeball, -10,0)
>>> c.move(eyeball, 10,0)

Please enter the source code on p.159.

python


#Try changing the color
def mouth_open():
    c.itemconfig(mouth, fill='black')
def mouth_close():
    c.itemconfig(mouth, fill='red')

python


>>> mouth_open()
>>> mouth_close()

Please enter the source code on p.160.

python


# p.161 Hide the shape
def blink():
    c.itemconfig(eye, fill='green')
    c.itemconfig(eyeball, state=HIDDEN)
def unblink():
    c.itemconfig(eye, fill='white')
    c.itemconfig(eyeball, state=NORMAL)

python


>>> blink()
>>> unblink()

python


# p.161 Talk
words = c.create_text(200, 280, text='I'm an alien!')
def steal_hat():
    c.itemconfig(hat, state=HIDDEN)
    c.itemconfig(words, text='Please change my mind!')

python


>>> steal_hat()

React to the event

python


# p.162 Mouse events

window.attributes('-topmost', 1)
def burp(event):
    mouth_open()
    c.itemconfig(words, text='burp!')
c.bind_all('<Button-1>', burp)

python


# p.163 Keyboard events

def blink2(event):
    c.itemconfig(eye, fill='green')
    c.itemconfig(eyeball, state=HIDDEN)
def unblink2(event):
    c.itemconfig(eye, fill='white')
    c.itemconfig(eyeball, state=NORMAL)
c.bind_all('<KeyPress-a>', blink2)
c.bind_all('<KeyPress-z>', unblink2)

python


# p.163 Move with key operation

def eye_control(event):
    key = event.keysym
    if key == "Up":
        c.move(eyeball, 0, -1)
    elif key == "Down":
        c.move(eyeball, 0, 1)
    elif key == "Left":
        c.move(eyeball, -1, 0)
    elif key == "Right":
        c.move(eyeball, 1, 0)
c.bind_all('<Key>', eye_control)

Project 6: Water can game

python


# p.165 Make windows and water cans

from tkinter import *
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title('Water can game')
c = Canvas(window, width=WIDTH, height=HEIGHT, bg='darkblue')
c.pack()

python


ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill='red')
ship_id2 = c.create_oval(0, 0, 30, 30, outline='red')
SHIP_R = 15
MID_X = WIDTH / 2
MID_Y = HEIGHT / 2
c.move(ship_id, MID_X, MID_Y)
c.move(ship_id2, MID_X, MID_Y)

python


# p.166 Move the water can

SHIP_SPD = 10
def move_ship(event):
    if event.keysym == 'Up':
        c.move(ship_id, 0, -SHIP_SPD)
        c.move(ship_id2, 0, -SHIP_SPD)
    elif event.keysym == 'Down':
        c.move(ship_id, 0, SHIP_SPD)
        c.move(ship_id2, 0, SHIP_SPD)
    elif event.keysym == 'Left':
        c.move(ship_id, -SHIP_SPD, 0)
        c.move(ship_id2, -SHIP_SPD, 0)
    elif event.keysym == 'Right':
        c.move(ship_id, SHIP_SPD, 0)
        c.move(ship_id2, SHIP_SPD, 0)
c.bind_all('<Key>', move_ship)

python


# p.167 Prepare "millet"

from random import randint
bub_id = list()
bub_r = list()
bub_speed = list()
MIN_BUB_R = 10
MAX_BUB_R = 30
MAX_BUB_SPD = 10
GAP = 100
def create_bubble():
    x = WIDTH + GAP
    y = randint(0, HEIGHT)
    r = randint(MIN_BUB_R, MAX_BUB_R)
    id1 = c.create_oval(x - r, y - r, x + r, y + r, outline='white')
    bub_id.append(id1)
    bub_r.append(r)
    bub_speed.append(randint(1, MAX_BUB_SPD))

python


# p.168 Move the millet

def move_bubbles():
    for i in range(len(bub_id)):
        c.move(bub_id[i], -bub_speed[i], 0)

python


from time import sleep, time
BUB_CHANCE = 10
#Main loop
while True:
    if randint(1, BUB_CHANCE) == 1:
        create_bubble()
    move_bubbles()
    window.update()
    sleep(0.01)

python


def get_coords(id_num):
    pos = c.coords(id_num)
    x = (pos[0] + pos[2])/2
    y = (pos[1] + pos[3])/2
    return x, y

python


# p.169 How to foxtail

def del_bubble(i):
    del bub_r[i]
    del bub_speed[i]
    c.delete(bub_id[i])
    del bub_id[i]

python


def clean_up_bubs():
    for i in range(len(bub_id) -1, -1, -1):
        x, y = get_coords(bub_id[i])
        if x < -GAP:
            del_bubble(i)

python


# p.170 Measure the distance between two points

from math import sqrt
def distance(id1, id2):
    x1, y1 = get_coords(id1)
    x2, y2 = get_coords(id2)
    return sqrt((x2 - x1)**2 + (y2 - y1)**2)

python


#Millet

def collision():
    points = 0
    for bub in range(len(bub_id)-1, -1, -1):
        if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]):
            points += (bub_r[bub] + bub_speed[bub])
            del_bubble(bub)
    return points

python


# p.172 Complete the game

c.create_text(50, 30, text='time', fill='white' )
c.create_text(150, 30, text='Score', fill='white' )
time_text = c.create_text(50, 50, fill= 'white' )
score_text = c.create_text(150, 50, fill='white')
def show_score(score):
    c.itemconfig(score_text, text=str(score))
def show_time(time_left):
    c.itemconfig(time_text, text=str(time_left))

python


from time import sleep, time
BUB_CHANCE = 10
TIME_LIMIT = 30 # P.172
BONUS_SCORE = 1000 # P.172
score = 0 # p.171
bonus = 0 # P.172
end = time() + TIME_LIMIT  # P.172

python


# p.173

#Main loop
while time() < end: # P.173
    if randint(1, BUB_CHANCE) == 1:
        create_bubble()
    move_bubbles()
    clean_up_bubs()  # p.169
    score += collision()  # p.171
    if (int(score / BONUS_SCORE)) > bonus:  # p.173
        bonus += 1  # p.173
        end += TIME_LIMIT  # p.173
    show_score(score)  # p.173
    show_time(int(end - time()))  # p.173
    window.update()
    sleep(0.01)

python


# p.173
c.create_text(MID_X, MID_Y, \
    text='Game over', fill='white', font=('Helvetica', 30))
c.create_text(MID_X, MID_Y + 30, \
              text='Score'+ str(score),  fill='white')
c.create_text(MID_X, MID_Y + 45,
              text='Bonus time' + str(bonus*TIME_LIMIT),  fill='white')

That's all there is to it. Below is the completed program.

python


# p.165 Make windows and water cans

from tkinter import *
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title('Water can game')
c = Canvas(window, width=WIDTH, height=HEIGHT, bg='darkblue')
c.pack()

ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill='red')
ship_id2 = c.create_oval(0, 0, 30, 30, outline='red')
SHIP_R = 15
MID_X = WIDTH / 2
MID_Y = HEIGHT / 2
c.move(ship_id, MID_X, MID_Y)
c.move(ship_id2, MID_X, MID_Y)

# p.166 Move the water can

SHIP_SPD = 10
def move_ship(event):
    if event.keysym == 'Up':
        c.move(ship_id, 0, -SHIP_SPD)
        c.move(ship_id2, 0, -SHIP_SPD)
    elif event.keysym == 'Down':
        c.move(ship_id, 0, SHIP_SPD)
        c.move(ship_id2, 0, SHIP_SPD)
    elif event.keysym == 'Left':
        c.move(ship_id, -SHIP_SPD, 0)
        c.move(ship_id2, -SHIP_SPD, 0)
    elif event.keysym == 'Right':
        c.move(ship_id, SHIP_SPD, 0)
        c.move(ship_id2, SHIP_SPD, 0)
c.bind_all('<Key>', move_ship)

# p.167 Prepare "millet"

from random import randint
bub_id = list()
bub_r = list()
bub_speed = list()
MIN_BUB_R = 10
MAX_BUB_R = 30
MAX_BUB_SPD = 10
GAP = 100
def create_bubble():
    x = WIDTH + GAP
    y = randint(0, HEIGHT)
    r = randint(MIN_BUB_R, MAX_BUB_R)
    id1 = c.create_oval(x - r, y - r, x + r, y + r, outline='white')
    bub_id.append(id1)
    bub_r.append(r)
    bub_speed.append(randint(1, MAX_BUB_SPD))

def get_coords(id_num):
    pos = c.coords(id_num)
    x = (pos[0] + pos[2])/2
    y = (pos[1] + pos[3])/2
    return x, y

#Move the millet
def move_bubbles():
    for i in range(len(bub_id)):
        c.move(bub_id[i], -bub_speed[i], 0)

# p.169 How to foxtail

def del_bubble(i):
    del bub_r[i]
    del bub_speed[i]
    c.delete(bub_id[i])
    del bub_id[i]

def clean_up_bubs():
    for i in range(len(bub_id) -1, -1, -1):
        x, y = get_coords(bub_id[i])
        if x < -GAP:
            del_bubble(i)

# p.170 Measure the distance between two points

from math import sqrt
def distance(id1, id2):
    x1, y1 = get_coords(id1)
    x2, y2 = get_coords(id2)
    return sqrt((x2 - x1)**2 + (y2 - y1)**2)

#Millet

def collision():
    points = 0
    for bub in range(len(bub_id)-1, -1, -1):
        if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]):
            points += (bub_r[bub] + bub_speed[bub])
            del_bubble(bub)
    return points

# p.172 Complete the game

c.create_text(50, 30, text='time', fill='white' )
c.create_text(150, 30, text='Score', fill='white' )
time_text = c.create_text(50, 50, fill= 'white' )
score_text = c.create_text(150, 50, fill='white')
def show_score(score):
    c.itemconfig(score_text, text=str(score))
def show_time(time_left):
    c.itemconfig(time_text, text=str(time_left))

from time import sleep, time
BUB_CHANCE = 10
TIME_LIMIT = 30 # P.172
BONUS_SCORE = 1000 # P.172
score = 0 # p.171
bonus = 0 # P.172
end = time() + TIME_LIMIT  # P.172
#Main loop
while time() < end: # P.173
    if randint(1, BUB_CHANCE) == 1:
        create_bubble()
    move_bubbles()
    clean_up_bubs()  # p.169
    score += collision()  # p.171
    if (int(score / BONUS_SCORE)) > bonus:  # p.173
        bonus += 1  # p.173
        end += TIME_LIMIT  # p.173
    show_score(score)  # p.173
    show_time(int(end - time()))  # p.173
    window.update()
    sleep(0.01)

# p.173
c.create_text(MID_X, MID_Y, \
    text='Game over', fill='white', font=('Helvetica', 30))
c.create_text(MID_X, MID_Y + 30, \
              text='Score'+ str(score),  fill='white')
c.create_text(MID_X, MID_Y + 45,
              text='Bonus time' + str(bonus*TIME_LIMIT),  fill='white')

5 Real world programming

Use JavaScript

python


// p.210 Ask the user to enter

<script>
var name = prompt("Please enter your name");
var greeting = "Hello" + name + "!";
document.write(greeting);
alert("Hello World!");
</script>

python


// p.211 events

<button onclick="tonguetwist()">Let's say!</button>
<script>
 function tonguetwist()
 {
  document.write("namamugi namagome namatamago "It's Japanese tongue-twister");  
 }
</script>

python


// p.211 Loop in JavaScript

<script>
for  (var x=0; x<6; x++)
{
 document.write("Number of loops: "+x+"<br>");
}
</script>

Thank you for your support. Let's continue to enjoy programming: thumbsup:

Recommended Posts

Code of "Programming picture book starting from 10 years old"
Script of "Programming book starting from elementary and junior high school students"
Let Code Table of Contents Starting from Zero
Let Code Day 44 "543. Diameter of Binary Tree" starting from zero
Let Code Day4 starting from scratch "938. Range Sum of BST"
Let Code Day87 Starting from Zero "1512. Number of Good Pairs"
Let Code Day56 Starting from Zero "5453. Running Sum of 1d Array"
Let Code Day7 starting from zero "104. Maximum Depth of Binary Tree"
Let Code Day92 Starting from Zero "4. Median of Two Sorted Arrays"
Code wars kata starting from zero
Re: Competitive Programming Life Starting from Zero Chapter 1.2 "Python of Tears"
Let Code Day 35 "160. Intersection of Two Linked Lists" Starting from Zero
Let Code Day 11 Starting from Zero "1315. Sum of Nodes with Even-Valued Grandparent"
Let Code Day6 Starting from Zero "1342. Number of Steps to Reduce a Number to Zero"
Let Code Day75 starting from scratch "15.3 Sum"
"Python AI programming" starting from 0 for windows
Let Code Day 29 "46. Permutations" starting from scratch
Let Code Day10 Starting from Zero "1431. Kids With the Greatest Number of Candies"
Let Code Day58 Starting from Zero "20. Valid Parentheses"
Let Code Day 27 "101. Symmetric Tree" starting from scratch
Let Code Day16 Starting from Zero "344. Reverse String"
Let Code Day49 starting from zero "1323. Maximum 69 Number"
Let Code Day89 "62. Unique Paths" Starting from Zero
Let Code Day 25 "70. Climbing Stairs" starting from scratch
Code wars kata starting from zero Sudoku, Nampre
Let Code Day69 starting from scratch "279. Perfect Squares"
Let Code Day 34 starting from scratch "118. Pascal's Triangle"
Let Code Day85 starting from scratch "6. ZigZag Conversion"
Let Code Day20 starting from scratch "134. Gas Station"
Let Code Day18 starting from zero "53. Maximum Subarray"
Let Code Day 13 "338. Counting Bits" Starting from Zero
Let Code Day 88 "139. Word Break" starting from scratch
Let Code Day 28 "198. House Robber" starting from scratch
Let Code Day71 Starting from Zero "1496. Path Crossing"
Let Code Day 61 "7. Reverse Integer" starting from zero
Let Code Day 39 "494. Target Sum" starting from scratch
Let Code Day 82 "392. Is Subsequence" Starting from Zero
Let Code Day 36 "155. Min Stack" starting from scratch
Let Code Day51 Starting from Zero "647. Palindromic Substrings"
Let Code Day 50 "739. Daily Temperatures" Starting from Zero
Let Code Day 15 "283. Move Zeroes" starting from zero
Let Code Day 17 "169. Majority Element" starting from scratch
Let Code Day14 starting from zero "136. Single Number"
Let Code Day 33 "1. Two Sum" starting from scratch