実現したいこと
勉強のためpythonとtkinterでブロック崩しゲームを作成しています。
第一ステップとして、枠の中でボールが跳ね返り続けるプログラムを作成しています。
クラス定義を使ったプログラムにチャレンジしようとしています。
不明点があるので教えてください。
問題点
ボールが動かない
下記コードだと、ボールが動きません。
python
1import tkinter as tk 2 3win_width = 600 4win_height = 400 5 6root = tk.Tk() 7root.title("ブロック崩し") 8cv = tk.Canvas(root, width = win_width, height = win_height) 9cv.pack() 10 11class Ball: 12 def __init__(self, x = 250, y = 250, w = 10, dx = 5, dy = 5, color = "red"): 13 self.x = x # ボールの中心座標x,y 14 self.y = y 15 self.w = 10 # ボールの幅 16 self.dx = dx # ボールの移動量dx,dy 17 self.dy = dy 18 self.color = color 19 self.x1 = self.x - self.w # ボールの左端 20 self.x2 = self.x + self.w # ボールの上端 21 self.y1 = self.y + self.w # ボールの右端 22 self.y2 = self.y - self.w # ボールの下端 23 24 25 26 def draw(self): 27 cv.delete("ball") 28 cv.create_oval(self.x1, self.y1, self.x2, self.y2, fill = self.color, tag = "ball") # ボールを描画 29 30 def move(self): 31 if self.x1 < 0 or self.x2 > win_width: # もしボールの左右端が枠にぶつかったら移動方向を反転 32 self.dx *= -1 33 if self.y1 < 0 or self.y2 > win_height: # もしボールの上下端が枠にぶつかったら移動方向を反転 34 self.dy *= -1 35 36 self.x += self.dx #移動 37 self.y += self.dy #移動 38 39 40 41ball = Ball() 42 43def gameloop(): 44 ball.move() 45 ball.draw() 46 root.after(50, gameloop) 47 48gameloop() 49root.mainloop() 50
ボールが動く
ボールの上下左右端の変数設定コードを、ボールを動かすメソッドmove()
内に書いただけで動きます。
python
1import tkinter as tk 2 3win_width = 600 4win_height = 400 5 6root = tk.Tk() 7root.title("ブロック崩し") 8cv = tk.Canvas(root, width = win_width, height = win_height) 9cv.pack() 10 11class Ball: 12 def __init__(self, x = 250, y = 250, w = 10, dx = 5, dy = 5, color = "red"): 13 self.x = x # ボールの中心座標x,y 14 self.y = y 15 self.w = 10 # ボールの幅 16 self.dx = dx # ボールの移動量dx,dy 17 self.dy = dy 18 self.color = color 19 # self.x1 = self.x - self.w # 20 # self.x2 = self.x + self.w # 21 # self.y1 = self.y + self.w # 22 # self.y2 = self.y - self.w # move()内に移動 23 24 25 26 def draw(self): 27 cv.delete("ball") 28 cv.create_oval(self.x1, self.y1, self.x2, self.y2, fill = self.color, tag = "ball") # ボールを描画 29 30 def move(self): 31 32 self.x1 = self.x - self.w # ボールの左端 33 self.x2 = self.x + self.w # ボールの上端 34 self.y1 = self.y + self.w # ボールの右端 35 self.y2 = self.y - self.w # ボールの下端 36 37 38 39 if self.x1 < 0 or self.x2 > win_width: # もしボールの左右端が枠にぶつかったら移動方向を反転 40 self.dx *= -1 41 if self.y1 < 0 or self.y2 > win_height: # もしボールの上下端が枠にぶつかったら移動方向を反転 42 self.dy *= -1 43 44 self.x += self.dx #移動 45 self.y += self.dy #移動 46 47 48 49ball = Ball() 50 51def gameloop(): 52 ball.move() 53 ball.draw() 54 root.after(50, gameloop) 55 56gameloop() 57root.mainloop() 58
なぜ前者は動かないの
前者のプログラムは、メソッド move()内で、
self.x += self.dx #移動
self.y += self.dy #移動
の部分によって、ボールの中心位置座標が書き換えられています。
それによってself.x1~self.y2も、self.x, self.y を使って計算していますので、値が変わっているはずではないかと考えています。
ボールが動かないのはなぜでしょうか?
最近クラスについて勉強しだしたので、あまりよくわかっていません。
教えていただけると嬉しいです。
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/20 14:21 編集
2019/06/20 16:15 編集
2019/06/23 07:27