基本方針
テキスト 「いちばんやさしいPython入門教室」大澤文孝著,(ソーテック社出版,2017)で,せっかく速くしたんで,「もっと増やせね?」というのが動機です.どうせなら「カラーグリグリ」は後付け.
動画の作り方
-
動画は,Narupenが気づかせてくれた
-
ScreenToGifを利用
- 参照: 寝ログ記事
-
quicktime -> giftedを利用
-
cmd-ctrl-esc で録画停止
-
** なんかqiitaに上がらね.
:CUSTOM_ID: なんかqiitaに上がらね
-
位置,速度,カラーの初期値をランダムに
random.randint(0,9) を改良すればいいよね.
random.randint(0, 800), random.randint(0, 600) #x,y位置
random.randint(0, 10)-5 # dx
color1 = "#e8f" # rgb color
これをどうやろう?
colorのrandom化
color1 = "#"+ hex(random.randint(1, 15)).lstrip("0x") + hex(random.randint(1, 15)).lstrip("0x") + hex(random.randint(1, 15)).lstrip("0x")
みたいにね.やってることは,
- "#"というstringを用意して
- 1..15(1..f)の整数を出して,
- hexで"0xe"とかの16進数(hexadecimal)に変換して
- lstripで左(l)の"0x"をstrip(剥がす)1
たくさんのボール
あとはたくさんのボールをballsにappend(追加).
balls = []
for j in range(100):
balls.append(Ball(x, y, dx, dy, color)
うまく生成しない
実は,3回に2回は失敗しています.
File "C:\Users\shige\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: invalid color name "#12"
カラー文字生成で失敗(修正済み,たぶん).
ソースコード
全てを晒しておきます.
# Copyright (c) 2020 daddygongon
# Released under the MIT license
# https://opensource.org/licenses/mit-license.php
import tkinter as tk
import random
speed = 1
size = 10
class Ball:
global speed
def __init__(self, x, y, dx, dy, color):
self.x, self.y = x, y
self.dx, self.dy = dx*speed, dy*speed
self.color = color
self.shape = None
def move(self, canvas):
self.erase(canvas)
self.x += self.dx
self.y += self.dy
self.draw(canvas)
if (self.x >= canvas.winfo_width() or self.x <= 0):
self.dx = -self.dx
if (self.y >= canvas.winfo_height() or self.y <= 0):
self.dy = -self.dy
def erase(self, canvas):
canvas.delete(self.shape)
def draw(self, canvas):
self.shape = canvas.create_oval(self.x - size, self.y - size,
self.x + size, self.y + size,
fill=self.color, width=0)
def loop():
for b in balls:
b.move(canvas)
root.after(10, loop)
def color_maker(init, fin):
color1 = "#"+hex(random.randint(init, fin)
).lstrip("0x")+hex(random.randint(init, fin)
).lstrip("0x") + hex(random.randint(init, fin)
).lstrip("0x")
return color1
root = tk.Tk()
root.geometry("800x600")
canvas = tk.Canvas(root, width=800, height=600, bg=color_maker(1, 2))
canvas.place(x=0, y=0)
balls = []
for j in range(2**8):
# balls.append(Ball(random.randint(390, 410), random.randint(290, 310),
balls.append(Ball(random.randint(0, 800), random.randint(0, 600),
random.randint(0, 10)*2-10, random.randint(0,10)*2-10,
color_maker(8, 15)))
root.after(10, loop)
root.mainloop()
idleでは最後のmainloopもいらないそうです.
- source ~/Desktop/lecture_23s/compA23/d7_11_python/c7_bouncing_256_balls.org