python打地鼠游戏代码
时间: 2023-07-09 14:34:20 浏览: 54
以下是一个简单的Python打地鼠游戏代码示例:
```python
import tkinter as tk
import random
class Game(tk.Tk):
def __init__(self):
super().__init__()
self.score = 0
self.canvas = tk.Canvas(self, width=400, height=400)
self.canvas.pack()
self.score_text = self.canvas.create_text(10, 10, anchor='nw', text='Score: 0')
self.holes = []
for i in range(3):
hole = self.canvas.create_oval(100 * i + 50, 300, 100 * i + 150, 400, fill='brown')
self.holes.append(hole)
self.mouse = None
self.canvas.bind('<Button-1>', self.hit)
self.after(1000, self.spawn_mouse)
def spawn_mouse(self):
if self.mouse:
self.canvas.delete(self.mouse)
hole = random.choice(self.holes)
x1, y1, x2, y2 = self.canvas.coords(hole)
x = random.randint(int(x1), int(x2))
y = random.randint(int(y1), int(y2))
self.mouse = self.canvas.create_oval(x - 10, y - 10, x + 10, y + 10, fill='gray')
self.after(1000, self.spawn_mouse)
def hit(self, event):
if not self.mouse:
return
x, y = event.x, event.y
mx1, my1, mx2, my2 = self.canvas.coords(self.mouse)
if mx1 <= x <= mx2 and my1 <= y <= my2:
self.canvas.delete(self.mouse)
self.mouse = None
self.score += 1
self.canvas.itemconfigure(self.score_text, text='Score: {}'.format(self.score))
if __name__ == '__main__':
game = Game()
game.mainloop()
```
运行这段代码后,你会看到一个简单的打地鼠游戏界面。每隔一段时间,地鼠会从三个洞中的一个出现,你需要在它出现后尽快点击它,以获得分数。游戏会在你点击了所有的地鼠后结束。