python第一個遊戲__python

來源:互聯網
上載者:User

球拍接球,球拍可左右移動,球落地,遊戲over。

from Tkinter import *import randomimport timeclass Ball:    def __init__(self,canvas,color):        self.canvas=canvas        self.paddle=paddle        self.id=canvas.create_oval(10,10,25,25,fill=color)        self.canvas.move(self.id,245,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_bottom=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.hit_bottom=True        if self.hit_paddle(pos)==True:            self.y=-3        if pos[0]<=0:            self.x=3        if pos[2]>=self.canvas_width:            self.x=-3class Paddle:    def __init__(self,canvas,color):       self.canvas=canvas       self.id=canvas.create_rectangle(0,0,100,10,fill=color)       self.canvas.move(self.id,200,300)       self.x=0       self.canvas_width=self.canvas.winfo_width()       self.canvas.bind_all('<KeyPress-Left>',self.turn_left)       self.canvas.bind_all('<KeyPress-Right>',self.turn_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        elif pos[2]>=self.canvas_width:            self.x=0    def turn_left(self,evt):        self.x=-2    def turn_right(self,evt):        self.x=2tk=Tk()tk.title("Game")tk.resizable(0,0)tk.wm_attributes("-topmost",1)canvas=Canvas(tk,width=500,height=400,bd=0,highlightthickness=0)canvas.pack()tk.update()paddle=Paddle(canvas,'blue')ball=Ball(canvas,'red')while 1:    if ball.hit_bottom==False:        ball.draw()        paddle.draw()    tk.update_idletasks()    tk.update()    time.sleep(0.01)

結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.