tkinter游戏代码
时间: 2023-09-12 17:10:28 浏览: 63
以下是一个简单的 tkinter 游戏代码,可以用来实现一个“打地鼠”的小游戏。
```python
import tkinter as tk
import random
class Game:
def __init__(self, master):
self.master = master
self.master.title("打地鼠")
self.master.geometry("500x500")
self.score = 0
self.holes = []
self.create_board()
self.create_holes()
self.create_score_label()
self.start_game()
def create_board(self):
self.board = tk.Canvas(self.master, width=500, height=400, bg="green")
self.board.pack()
def create_holes(self):
for i in range(3):
hole = Hole(self.board)
self.holes.append(hole)
def create_score_label(self):
self.score_label = tk.Label(text="得分:0")
self.score_label.pack()
def start_game(self):
self.update_score()
self.move_moles()
self.master.mainloop()
def update_score(self):
self.score_label.config(text="得分:" + str(self.score))
def move_moles(self):
for hole in self.holes:
hole.move_mole()
self.master.after(500, self.move_moles)
class Hole:
def __init__(self, board):
self.board = board
self.x = random.randint(0, 450)
self.y = random.randint(0, 350)
self.mole = None
self.create_hole()
def create_hole(self):
self.hole = self.board.create_oval(self.x, self.y, self.x+50, self.y+50, fill="brown")
self.board.tag_bind(self.hole, "<Button-1>", self.hit_mole)
def create_mole(self):
self.mole = self.board.create_oval(self.x, self.y, self.x+50, self.y+50, fill="white")
def remove_mole(self):
if self.mole:
self.board.delete(self.mole)
self.mole = None
def move_mole(self):
if random.random() < 0.1:
self.remove_mole()
self.create_mole()
def hit_mole(self, event):
if self.mole:
self.board.delete(self.mole)
self.mole = None
app.score += 1
app.update_score()
if __name__ == "__main__":
root = tk.Tk()
app = Game(root)
```
这个游戏中,有三个地洞,每个地洞里有时会出现一只地鼠,玩家需要点击地鼠来得分。每击中一只地鼠,得分就会加一。
阅读全文