初識python:tkinter 實現 彈球小游戲(面向對象)


使用蹩腳式面相對象,實現彈球小游戲(非面向對象實現,主要介紹tk基礎用法)。

#!/user/bin env python
# author:Simple-Sir
# time:2020/8/7 10:09

import tkinter,time,random

# 創建顏色列表
COLOR = ['#f173ac','#73b9a2','#fdb933','#d71345','#fffef9','#afdfe4','#ffe600']

# 創建窗口
tk = tkinter.Tk()  # 聲明一個TK,初始化一個“窗口”(畫一個窗口)
tk.title('彈球游戲')  # 窗口名稱
tk.resizable(width=False,height=False)  # 窗口是否可變(長、寬),也可用0,1表示
tk.wm_attributes('-topmost',1)  # 窗口永遠在前

# 創建畫布
canvas = tkinter.Canvas(tk,width=600,height=500,bd=0)  # 創建一個“畫布”
canvas.pack()  # 將畫布添加到窗口中
tk.update()


# 創建背景
class Bg():
    def __init__(self,canvas,file):
        self.filename = tkinter.PhotoImage(file=file)  # 獲取一張圖片
        canvas.create_image(300, 250,image=self.filename)  # 將圖片添加到畫布,作為背景

# 創建球
class Ball():
    def __init__(self,canvas,COLOR):
        self.COLOR = COLOR
        self.id_ball = canvas.create_oval(10,10,30,30, fill=random.choice(COLOR), width=0)  # 定義一個球
        canvas.move(self.id_ball,random.randint(-10,300),random.randint(-20,300))
        self.ball_p_text = canvas.create_text(120, 20, text='球的坐標:{0}'.format(canvas.coords(self.id_ball)), fill='white')
        self.x = 1
        self.y = 1
        self.score = 0
        self.level = 1
        self.wh = canvas.winfo_height()  # 獲取窗口高度(update刷新之后才能獲取)
        self.ww = canvas.winfo_width()  # 獲取窗口寬度(update刷新之后才能獲取)


    def run_ball(self):
        p_ball = canvas.coords(self.id_ball)
        if p_ball[0] <= 0:  # 當球落到右邊框時:左上角x坐標判斷
            self.x = 1
        elif p_ball[2] >= self.ww:  # 當球落到右邊框時,右下角x坐標判斷
            self.x = -1
        if p_ball[1] <= 0:  # 當球落到上邊框時,左上角y坐標判斷
            self.y = 1
        elif p_ball[3] >= self.wh:  # 當球落到下邊框時,右下角y坐標判斷
            self.y = -1

    def touch(self):
        p_ball = canvas.coords(self.id_ball)
        canvas.itemconfig(self.ball_p_text,text='球的坐標:{0}'.format(p_ball))
        p_paddle = canvas.coords(paddle.id_paddle)  # 獲取木板的坐標
        if p_ball[2] >= p_paddle[0] and p_ball[2] <= p_paddle[2] and p_ball[3] == p_paddle[1]:  # 球與模板接觸:球的右下角x坐標在木板右上角x坐標內,且球的右下角x坐標在木板左下角x坐標內,球的右下角y坐標等於木板的左上角y坐標
            self.y = -1  # 讓球向上移動
            self.score += 10  # 得分加10分
            canvas.itemconfig(self.id_ball, fill=random.choice(self.COLOR))  # 修改球的顏色,隨機顏色
            canvas.itemconfig(paddle.id_paddle, fill=random.choice(self.COLOR))  # 修改木板的顏色,隨機顏色
            if self.score > 0 and self.score % 50 == 0:  # 每50分升一級
                self.level += 1  # 升級
        canvas.move(self.id_ball, self.x, self.y)  # 移動



class Paddle():
    def __init__(self,canvas,COLOR):
        self.canvas=canvas
        self.COLOR=COLOR
        self.x = 0
        self.id_paddle = canvas.create_rectangle(0,400,150,420,fill=random.choice(COLOR),width=0)  # 定義木板
        self.canvas.move(self.id_paddle,225,0)
        self.ww = canvas.winfo_width()  # 獲取窗口寬度(update刷新之后才能獲取)
        self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
        self.canvas.bind_all('<KeyPress-Right>', self.turn_right)

    def run_paddle(self):
        canvas.move(self.id_paddle, self.x, 0)  # 先移動,再判斷位置。若先判斷,在移動,則位置永遠是0或最大
        p_paddle = canvas.coords(self.id_paddle)  # 獲取木板的坐標
        if p_paddle[0] <= 0 or p_paddle[2] >= self.ww:
            self.x = 0

    def turn_left(self,event):
        p_paddle = canvas.coords(self.id_paddle)  # 獲取木板的坐標
        if p_paddle[0] <= 0:
            self.x = 0
        else:
            self.x = -2

    def turn_right(self,event):
        p_paddle = canvas.coords(self.id_paddle)  # 獲取木板的坐標
        if p_paddle[2] >= self.ww:
            self.x = 0
        else:
            self.x = 2


class Score():
    def __init__(self,canvas):
        canvas.create_text(400, 20, text='關卡:',fill='white',font=('宋體', '15'))
        canvas.create_text(500, 20, text='得分:',fill='white',font=('宋體', '15'))
        self.id_level = canvas.create_text(440, 20, text=1,fill='white',font=('宋體', '15'))
        self.id_score = canvas.create_text(540, 20, text=0,fill='white',font=('宋體', '15'))

    def update_lv_sc(self):
        canvas.itemconfig(self.id_level, text=ball.level)  # 修改等級
        canvas.itemconfig(self.id_score, text=ball.score)  # 修改分數

class Sys_game():
    is_start = False
    def __init__(self,canvas):
        self.id_start_game = canvas.create_text(300, 200, text='Start Game !', font=('宋體', '30'), fill='white')
        canvas.bind_all('<Button-1>', self.start_game)
        self.wh = canvas.winfo_height()  # 獲取窗口高度(update刷新之后才能獲取)

    def start_game(self,event):
        if self.is_start:
            self.is_start = False
            canvas.itemconfig(self.id_start_game,text='Stop Game !',state='normal',fill='red')
        else:
            self.is_start = True
            canvas.itemconfig(self.id_start_game,state='hidden')

    def is_play(self):
        p_ball = canvas.coords(ball.id_ball)
        if p_ball[3] == self.wh:  # 當球與下邊框接觸時,游戲失敗。
            canvas.create_text(300, 250, text='Game Over !', font=('宋體', '30'), fill='red')  # 添加游戲結束界面
            self.is_start = False

# 搞起
bg = Bg(canvas,'bg.png')
ball = Ball(canvas,COLOR)
paddle = Paddle(canvas,COLOR)
score = Score(canvas)
sys_game = Sys_game(canvas)
while 1:
    sys_game.is_play()
    if sys_game.is_start == True:
        tk.update()
        ball.run_ball()
        ball.touch()
        score.update_lv_sc()
        paddle.run_paddle()
        time.sleep(0.01/ball.level)
    else:
        tk.update()
彈球小游戲

運行結果:

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM