使用 Python 捕捉球遊戲
Python 還可以用來建立電腦遊戲。在這篇文章中,我們將瞭解如何使用 Python 建立球捕捉遊戲。在這個遊戲中,一個球不斷地從畫布視窗的頂部掉落,視窗底部有一個橫條。提供了兩個按鈕用於左右移動橫條。使用滑鼠按鈕按下,我們移動底部的橫條來捕捉下落的球。在不同的時間,球從不同的位置掉落。
方法
構建遊戲的步驟如下所述。
步驟 1 − 繪製一個 tkinter 矩形畫布,可用於容納其他佈局,如各種圖形、文字和影像等。
步驟 2 − 建立將從頂部掉落的球。為此使用 create_oval 方法。它需要 4 個座標來建立一個橢圓,它是圓形和矩形的混合。
步驟 3 − 在底部建立橫條,該橫條將在滑鼠按鈕按下時從左到右移動。可以使用 create_rectangle 方法來實現。
步驟 4 − 使用 canvas.move 方法移動球或橫條。此方法用於與其關聯的物件的垂直和水平移動。
步驟 5 − 建立將用於移動底部橫條的按鈕。將應用事件,這些事件將在單擊按鈕時觸發。
程式
以下是基於上述步驟使用相關方法和物件的完整程式。
示例
#Catching the ball game using Python
from tkinter import Tk, Button, Label
from tkinter import Canvas
from random import randint
base = Tk()
base.title("BALL GAME")
base.resizable(False, False)
color = Canvas(base, width=590, height=610)
color.pack()
standard = 0
length = 5
marks = 0
class model:
def __init__(self, color, m1, n1, m2, n2):
self.m1 = m1
self.n1 = n1
self.m2 = m2
self.n2 = n2
self.color = color
self.circle = color.create_oval(self.m1, self.n1, self.m2, self.n2,fill="blue", tags='dot1')
def Game(self):
offset = 5
global standard
if standard >= 510:
global length, marks, next
if (length - offset <= self.m1 and
length + 40 + offset >= self.m2):
marks += 5
color.delete('dot1')
game_play()
else:
color.delete('dot1')
slide.remove(self)
result()
return
standard += 1
self.color.move(self.circle, 0, 1)
self.color.after(10, self.Game)
class slide:
def __init__(self, color, m1, n1, m2, n2):
self.m1 = m1
self.n1 = n1
self.m2 = m2
self.n2 = n2
self.color = color
self.num = color.create_rectangle(self.m1, self.n1, self.m2, self.n2, fill="green", tags='dot2')
def push(self, num):
global length
if (num == 1):
self.color.move(self.num, 20, 0)
length += 20
else:
self.color.move(self.num, -20, 0)
length -= 20
def remove(self):
color.delete('dot2')
def game_play():
global standard
standard = 0
size = randint(0, 570)
game1 = model(color, size, 20, size + 30, 50)
game1.Game()
def result():
base2 = Tk()
base2.title("THE BALL GAME")
base2.resizable(False, False)
set = Canvas(base2, width=300, height=300)
set.pack()
z = Label(set, text="\nGame over\n\nYou have scored = " + str(marks) + "\n\n")
z.pack()
btx = Button(set, text="Enter if you want to play again", bg="yellow", command=lambda: repeat(base2))
btx.pack()
bty = Button(set, text=" CLOSE ", bg="red",command=lambda: destroy(base2))
bty.pack()
def repeat(base2):
base2.destroy()
function()
def destroy(base2):
base2.destroy()
base.destroy()
def function():
global marks, length
marks = 0
length = 0
x1 = slide(color, 5, 560, 45, 575)
Bt0 = Button(color, text="move right**", bg="pink",command=lambda: x1.push(1))
Bt0.place(x=335, y=580)
Bt1 = Button(color, text="**move left ", bg="pink", command=lambda: x1.push(0))
Bt1.place(x=260, y=580)
game_play()
base.mainloop()
if (__name__ == "__main__"):
function()輸出
執行以上程式碼,我們將得到以下結果:

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP