python實(shí)現(xiàn)簡單反彈球游戲
python簡單游戲-反彈球,供大家參考,具體內(nèi)容如下
tkinter實(shí)現(xiàn),直接貼上代碼
from tkinter import*import timeimport randomclass Ball: def __init__(self,canvas,paddle,color):self.canvas = canvasself.paddle = paddleself.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 = -3self.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 Truereturn 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 = 4if pos[3] >= self.canvas_height: self.hit_bottom=Trueif self.hit_paddle(pos)==True: self.y=-4if pos[0] <= 0: self.x = 4if pos[2] >= self.canvas_width: self.x = -4class Paddle: def __init__(self,canvas,color):self.canvas = canvasself.id = canvas.create_rectangle(0,0,100,10,fill=color)self.canvas.move(self.id,200,400)self.x=0self.canvas_width = self.canvas.winfo_width()canvas.bind_all(’<KeyPress-Left>’,self.turn_left)canvas.bind_all(’<KeyPress-Right>’,self.turn_right)self.hit_bottom = False def draw(self):self.canvas.move(self.id,self.x,0)pos = self.canvas.coords(self.id)if pos[0] <= 0: self.x = 0elif pos[2] >= self.canvas_width: self.x = 0 def turn_left(self,evt):self.x=-7 def turn_right(self,evt):self.x=7 tk = Tk()tk.title('反彈吧!球球')#tk.resizable(0,0)tk.wm_attributes('-topmost',1)canvas = Canvas(tk,width=650,height=600,bd=0,highlightthickness=0)canvas.pack()tk.update()paddle=Paddle(canvas,’blue’)ball = Ball(canvas,paddle,’red’)while 1: if ball.hit_bottom==False:ball.draw()paddle.draw() tk.update_idletasks() tk.update() time.sleep(0.01)
效果:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解CSS偽元素的妙用單標(biāo)簽之美2. XML入門的常見問題(四)3. ASP基礎(chǔ)知識VBScript基本元素講解4. 利用CSS3新特性創(chuàng)建透明邊框三角5. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼6. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法7. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達(dá)式8. HTML5 Canvas繪制圖形從入門到精通9. XHTML 1.0:標(biāo)記新的開端10. JSP的Cookie在登錄中的使用
