簡體   English   中英

Python Tkinter 彈跳球游戲重啟

[英]Python Tkinter bounce ball game restart

我一直在閱讀一本名為“Python for kids”的書,其中逐步介紹了如何創建彈跳球游戲。 最終代碼如下所示:

from Tkinter import *
import random

tk = Tk()
tk.title("Paddleball Game")
tk.resizable(0,0) # tk window cannot be resized in x or y
tk.wm_attributes("-topmost", 1)

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) #no borders around the canvas
canvas.pack()
tk.update()


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)
        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):
        if self.hit_bottom == False:

            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.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

            if ball.hit_bottom == False:
                self.canvas.after(10, self.draw) # miliseconds, function

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):
        if ball.hit_bottom == False:

            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

            self.canvas.after(10, self.draw)

    def turn_left(self, event):
        self.pos = self.canvas.coords(self.id)

        if self.pos[0] >= 1:
            self.x = -3

    def turn_right(self, event):
        self.pos = self.canvas.coords(self.id)

        if self.pos[2] <= self.canvas_width-1:
            self.x = 3

paddle = Paddle(canvas, "blue")
ball = Ball(canvas, paddle, "red")


def start_game(event):
    ball.draw()

canvas.bind_all("<Button-1>", start_game)
paddle.draw()

tk.mainloop()

現在,在閱讀了這本書並理解了大部分內容之后,我嘗試單獨重新創建游戲並添加一些額外的東西。 1)當我輸了時顯示游戲結束, 2)計算分數並顯示它, 3)延遲開始(1 秒), 4)在我輸了之后停止球和槳的移動。 此外,我這樣做是為了當我輸了時, 5)如果我再次單擊 window,游戲結束文本消失,分數變為零,球拍和球再次開始移動。

但是,我希望球從原來的位置開始,而不是從底部開始,如果可能的話,當我輸了時,顯示一個按鈕,這樣當我按下它時,游戲就會重新開始。

我的代碼是這樣的:

from Tkinter import *
import random
import time

root = Tk()
root.title("Testing... testing...")
root.resizable(0,0)
root.wm_attributes("-topmost", -1)

canvas = Canvas(root, width=500, height=400, bd=0,highlightthickness=0)
canvas.pack()

root.update()

count = 0
lost = False

class Ball:
    def __init__(self, canvas, paddle, color):
        self.canvas = canvas
        self.paddle = paddle
        self.id = canvas.create_oval(0, 0, 15, 15, fill=color)
        self.canvas.move(self.id, 245, 200)

        starts_x = [-3, -2, -1, 1, 2, 3]
        random.shuffle(starts_x)

        self.x = starts_x[0]
        self.y = -3

        self.canvas_height = self.canvas.winfo_height()
        self.canvas_width = self.canvas.winfo_width()


    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.y = -3

        if pos[0] <= 0:
            self.x = 3
        if pos[2] >= self.canvas_width:
            self.x = -3

        self.paddle_pos = self.canvas.coords(self.paddle.id)


        if pos[2] >= self.paddle_pos[0] and pos[0] <= self.paddle_pos[2]:
            if pos[3] >= self.paddle_pos[1] and pos[3] <= self.paddle_pos[3]:
                self.y = -3
                global count
                count +=1
                score()


        if pos[3] <= self.canvas_height:
            self.canvas.after(10, self.draw)
        else:
            game_over()
            global lost
            lost = True


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.move_left)
        self.canvas.bind_all("<KeyPress-Right>", self.move_right)

    def draw(self):
        self.canvas.move(self.id, self.x, 0)

        self.pos = self.canvas.coords(self.id)

        if self.pos[0] <= 0:
            self.x = 0
        if self.pos[2] >= self.canvas_width:
            self.x = 0
        global lost
        if lost == False:
            self.canvas.after(10, self.draw)

    def move_left(self, event):
        if self.pos[0] >= 0:
            self.x = -3

    def move_right(self, event):
        if self.pos[2] <= self.canvas_width:
            self.x = 3


def start_game(event):
    global lost, count
    lost = False
    count = 0
    score()
    canvas.itemconfig(game, text=" ")

    time.sleep(1)
    paddle.draw()
    ball.draw()


def score():
    canvas.itemconfig(score_now, text="score: " + str(count))

def game_over():
    canvas.itemconfig(game, text="Game over!")


paddle = Paddle(canvas, "blue")
ball = Ball(canvas, paddle, "red")


score_now = canvas.create_text(430, 20, text="score: " + str(count), fill = "red", font=("Arial", 16))
game = canvas.create_text(250, 150, text=" ", fill="red", font=("Arial", 20))


canvas.bind_all("<Button-1>", start_game)

root.mainloop()

任何人都可以幫助我嗎? 謝謝。

編輯:我想我需要一種方法來在我輸球后取消畫球並在比賽開始時重新畫球。 但我不確定該怎么做......

我嘗試在 start_game function 中插入ball = Ball(canvas, paddle, "red")但這會繪制一個新球並將舊球保持在底部......

如果其他人試圖解決這個問題但不能,我找到了一個解決方案。

我編輯了兩件事,如下:

在 Ball 類的 draw() 函數中,編輯了以下幾行:

if pos[3] <= self.canvas_height:
            self.canvas.after(10, self.draw)
        else:
            self.canvas.move(self.id, 245, 200) #added this line
            game_over()
            global lost
            lost = True

還編輯了 start_game() 函數如下:

def start_game(event):
    global lost, count, ball #added ball here
    if lost == True: # added this if
        ball = Ball(canvas, paddle, "red")

    lost = False #and finally changed the lost var BEFORE drawing the paddle which has a check of lost var in order to move.
    paddle.draw()
    ball.draw()
    count = 0

    score()
    canvas.itemconfig(game, text=" ")

    time.sleep(1)

歡迎提供更多幫助/答案!

另外,如果您需要“取消繪制”球,請使用canvas.delete(ball.id)並關閉我的頭頂canvas.itemconfig(state=Tkinter.HIDDEN)應該可以工作

我和你在同一個地方,但后來我開始研究圖書館 Tkinter 和幾本書我想出了簡單快速的解決方案讓你在主循環中讓你恢復。我基本上在比賽結束后,移動球來修復指向槳上方並繼續。 有時你不需要完全停止並重新啟動所有,只需要重新調整終點在不同的坐標,然后當你點擊鼠標/按鈕時游戲將恢復並且分數將被重置。這是我使用的代碼:我添加了新的function 是 class 到 rest 在 memory 和屏幕上的得分值。 右上角:class 得分:def reset(self): self.score = 0 self.canvas.itemconfig(self.id, text=self.score) TotalScoreValue = self.score

然后在任何 class 之外我定義了單獨的 function 由“重置按鈕”使用並清除所有。 清晰明確():

canvas.coords(ball.id ,330.0, 130.0, 345.0, 145.0)
score.reset()
ball.hit_bottom = False
paddle.started = False
tk.update_idletasks()
tk.update()
time.sleep(0.01)

btn = Button(tk, text ='click me',command=clear) btn.pack()

這里的關鍵是“canvas.coords(ball.id,330.0, 130.0, 345.0, 145.0)”以及重置“hit bottom”和 paddle_started ball.hit_bottom = False paddle.started = False 的狀態

在此之后我們需要手動根據用戶需求(在主循環之外) rest canvas by: tk.update_idletasks() tk.update()

並且球出現在 position 組的球拍上方,分數被重置(很少有其他消息再次被隱藏)然后相同的主循環等待用戶通過按下鼠標按鈕等再次開始游戲。在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM