以下爲參照《趣學Python編程》示例源碼打出的反彈的小球遊戲,經自己進行調試,更改,在python2.7上爲可運行程序。適合像我一樣的初學者進行Python體驗,代碼如下:
from Tkinter import *
import randomimport time
class Ball:
def __init__(self,canvas,paddle,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)#得到拍子的座標,並放入到變量paddle_pos中
if pos[2]>=paddle_pos[0] and pos[0]<=paddle_pos[2]:#x果小球的右側大於球拍的左側。。。其中pos[2]包含了小球右側的x座標,pos[0]包含了左側的x座標;paddle_pos[0]球拍左側的的x座標
if pos[3]>=paddle_pos[1] and pos[3]<=paddle_pos[3]:#pos[1]頂部 pos[3]底部
return True
return False
def draw(self):
self.canvas.move(self.id,self.x,self.y)#id是橢圓形的id,還有0指不要水平移動,-1指在屏幕上向上移動1個像素
pos=self.canvas.coords(self.id)#通過ID來返回畫布上任何畫好的東西的當前的x和y座標,那個圓形的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=-3
class 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=2
tk=Tk()
tk.title("Game")
tk.resizable(0,0)#窗口大小不可調整,0,0表示窗口大小在水平方向和垂直方向上都不能改變
tk.wm_attributes("-topmost",1)#把包含我們畫布的窗口放到所有其他窗口之前
canvas=Canvas(tk,width=500,height=400,bd=0,highlightthickness=0)
canvas.pack()#讓畫布按前一行給出的寬度和高度的參數來調整其自身大小
my_image=PhotoImage(file='c:\\135.gif')
canvas.create_image(130,0,anchor=NW,image=my_image)
tk.update()#爲遊戲中的動畫做好初始化
#canvas.create_oval(10,10,25,25,fill='blue')
paddle=Paddle(canvas,'green')
ball=Ball(canvas,paddle,'pink')
while 1:
if ball.hit_bottom==False:
ball.draw()
paddle.draw()
else:
canvas.create_text(250,50,text='Game Over',font=('Courier',30))
tk.update_idletasks()
tk.update()
time.sleep(0.01)