-
-
Save johnteee/236f26baf8419c2a2ce37eb87d6c51c1 to your computer and use it in GitHub Desktop.
pinpon_game
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import tkinter | |
| import random | |
| import time | |
| tk=tkinter.Tk() | |
| tk.title("Game") #窗口名稱 | |
| tk.resizable(0,0) #表示畫面大小不能被拉 | |
| tk.wm_attributes("-topmost",1) #視窗移到最上層 | |
| canvas=tkinter.Canvas(tk,width=700,height=700,bd=0) | |
| #大小,邊框厚度為0 | |
| canvas.pack() | |
| tk.update() | |
| class Ball: | |
| def __init__(self, canvas,paddle,color): | |
| self.canvas = canvas | |
| self.id=canvas.create_oval(50,50,75,75,fill=color) | |
| self.paddle=paddle | |
| self.canvas.move(self.id,290,100) | |
| starts=[-3,-2,-1,1,2,3] | |
| random.shuffle(starts) | |
| self.x=starts[0] | |
| self.y=-3 | |
| self.canvas_height=self.canvas.winfo_height() | |
| self.canvas_width=self.canvas.winfo_width() | |
| self.hit_button=False | |
| def hit_paddle(self,pos): | |
| paddle_pos=self.canvas.coords(self.paddle.id) | |
| if pos[2]>=paddle_pos[0] and pos[0]<=paddle_pos[2]: | |
| if pos[3]>=paddle_pos[1] and pos[3]<=paddle_pos[3]: | |
| return True | |
| return False | |
| def draw(self): | |
| self.canvas.move(self.id,self.x,self.y) | |
| pos=self.canvas.coords(self.id) | |
| if pos[1]<=0: | |
| self.y=3 | |
| if pos[3] >=self.canvas_height: | |
| self.y=-3 | |
| if self.hit_paddle(pos)==True: | |
| self.y=-3 | |
| if pos[0]<=0: | |
| self.x=3 | |
| if pos[2] >=self.canvas_height: | |
| self.x=-3 | |
| class Paddle: | |
| def __init__(self, canvas, color): | |
| self.canvas=canvas | |
| self.id=canvas.create_rectangle(0,0,200,20,fill=color) | |
| self.canvas.move(self.id,250,500) | |
| self.x=0 | |
| self.canvas_width=self.canvas.winfo_width() | |
| self.canvas.bind_all('<KeyPress-Left>',self.trun_left) | |
| self.canvas.bind_all('<KeyPress-Right>',self.trun_right) | |
| def draw(self): | |
| self.canvas.move(self.id,self.x,0) | |
| pos=self.canvas.coords(self.id) | |
| if pos[0]<=0: | |
| self.x=0 | |
| if pos[2]>= self.canvas_width: | |
| self.x=0 | |
| def trun_left(self,evt): | |
| self.x=-2 | |
| def trun_right(self,evt): | |
| self.x=2 | |
| paddle=Paddle(canvas,'blue') | |
| ball=Ball(canvas,paddle,'red') | |
| while True: | |
| ball.draw() | |
| paddle.draw() | |
| tk.update_idletasks() | |
| tk.update() | |
| time.sleep(0.02) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment