前提・実現したいこと
リンクにある本にあった問題です。たのしいプログラミングpythonではじめよう!
ボールが下に落ちたら止まるようになっているゲームで、今の状態だとウインドウを開いてすぐに動き始めるので、それを左クリックしたら動き出すようにしたいです。
発生している問題・エラーメッセージ
ソースコード内のメモになっているところまでは自力で考えました。
関数の本体のに何を入れればいいのかがわかりません。
該当のソースコード
Python
1from tkinter import* 2import random 3import time 4 5class Ball: 6 def __init__(self, canvas, paddle, color): 7 self.canvas = canvas 8 self.paddle = paddle 9 self.id = canvas.create_oval(10, 10, 25, 25, fill=color) 10 self.canvas.move(self.id, 245, 100) 11 starts = [-3, -2, -1, 1, 2, 3] 12 random.shuffle(starts) 13 self.x = starts[0] 14 self.y = -3 15 self.canvas_height = self.canvas.winfo_height() 16 self.canvas_width = self.canvas.winfo_width() 17 self.hit_bottom = False 18 19 def hit_paddle(self, pos): 20 paddle_pos = self.canvas.coords(self.paddle.id) 21 if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]: 22 if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]: 23 return True 24 return False 25 26 def draw(self): 27 self.canvas.move(self.id, self.x, self.y) 28 pos = self.canvas.coords(self.id) 29 if pos[1] <=0: 30 self.y = 3 31 if pos[3] >= self.canvas_height: 32 self.hit_bottom = True 33 if self.hit_paddle(pos) == True: 34 self.y = -3 35 if pos[0] <= 0: 36 self.x = 3 37 if pos[2] >= self.canvas_width: 38 self.x = -3 39 40class Paddle: 41 def __init__(self, canvas, color): 42 self.canvas = canvas 43 self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color) 44 self.canvas.move(self.id, 200, 300) 45 self.x = 0 46 self.canvas_width = self.canvas.winfo_width() 47 self.canvas.bind_all('<KeyPress-Left>',self.turn_left) 48 self.canvas.bind_all('<KeyPress-Right>',self.turn_right) 49 #self.canvas.bind_all('<Button-1>',self.game_start) 50 51 def draw(self): 52 self.canvas.move(self.id, self.x, 0) 53 pos = self.canvas.coords(self.id) 54 if pos[0] <= 0: 55 self.x = 0 56 elif pos[2] >= self.canvas_width: 57 self.x = 0 58 59 def turn_left(self, evt): 60 self.x = -2 61 def turn_right(self, evt): 62 self.x = 2 63 #def game_start(self, evt): 64 #self. = 65 66tk = Tk() 67tk.title("Game") 68tk.resizable(0, 0) 69tk.wm_attributes("-topmost", 1) 70canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) 71canvas.pack() 72tk.update() 73 74paddle = Paddle(canvas, 'royalblue') 75ball = Ball(canvas, paddle, 'deeppink') 76 77while True: 78 if ball.hit_bottom == False: 79 ball.draw() 80 paddle.draw() 81 tk.update_idletasks() 82 tk.update() 83 time.sleep(0.01)
ソースコードは、<code>ボタンを押して、’’’の枠の中に貼り付けてください