python tkinter 시도

#Game
from tkinter import *
import random
import time

class Ball:    #      
    #self -->   java  this
    #self.attribute  -->           
    #self.method() -->       
    def __init__(self,canvas,paddle,color): #     (          ,  java      )
        self.canvas = canvas
        self.paddle = paddle
        self.id = self.canvas.create_oval(10,10,25,25,fill=color)  #     ,     (x1,y1,x2,y2)     ,         
        #self.canvas.move(self.id,200,200)   self.id(  )     200,     200
        starts = [-3,-2,-1,1,2,3] #      
        random.shuffle(starts) #    starts   
        self.x = starts[0] 
        self.y = starts[1]
        self.canvas_width = self.canvas.winfo_width()  #       
        self.canvas_height = self.canvas.winfo_height() #       

    def hit_paddle(self,pos):
        pd_pos  = self.canvas.coords(self.paddle.id) #       
        if pos[0] >= pd_pos[0] and pos[0] <= pd_pos[2]:  
            if pos[1] >= pd_pos[1] and pos[1] <= pd_pos[3]:
                return True
    
    def draw(self):
        self.canvas.move(self.id,self.x,self.y)
        pos = self.canvas.coords(self.id)
        if pos[0] <= 0:
            self.x = 3
        if pos[2] >= self.canvas_width:
            self.x = -3
        if self.hit_paddle(pos) == True:
            self.y = -3
        if pos[1] <=0:
            self.y = 3
        if pos[3] >= self.canvas_height:
            self.y = -3
            
class Paddle:
    def __init__(self,canvas,color):
        self.canvas = canvas
        self.id = self.canvas.create_rectangle(0,0,100,10,fill=color)
        self.canvas.move(self.id,0,300)
        self.x = 0
        self.canvas_width = self.canvas.winfo_width()
        #    
        self.canvas.bind_all('',self.turn_left)  #      ',self.turn_right) #      ->     turn_right  

    def turn_left(self,evt):
        self.x = -3

    def turn_right(self,evt):
        self.x = 3

    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   

tk = Tk()
tk.title("Game")  #     
tk.resizable(0,0)   #      
tk.wm_attributes("-topmost",1) #        
canvas = Canvas(tk,width=500,height=400,bd=0) #      ,      、 、    
canvas.pack() #          
canvas.update()  #    

paddle = Paddle(canvas,'blue')  #    Paddle  
ball = Ball(canvas,paddle,'red')  #    Ball  

while 1:
    ball.draw()
    paddle.draw()
    tk.update_idletasks()
    tk.update()
    time.sleep(0.01)

좋은 웹페이지 즐겨찾기