python打地鼠小游戏带有界面
时间: 2023-07-08 13:55:54 浏览: 108
Python小游戏源码-打地鼠游戏源码
5星 · 资源好评率100%
好的,下面是一个使用Python Tkinter库实现带有界面的打地鼠小游戏示例:
```python
import random
import tkinter as tk
import time
class MoleGame:
def __init__(self):
self.game_time = 30
self.score = 0
self.holes = [tk.PhotoImage(file='hole.png') for i in range(9)]
self.mole = tk.PhotoImage(file='mole.png')
self.root = tk.Tk()
self.root.title('打地鼠游戏')
self.root.resizable(False, False)
self.canvas = tk.Canvas(self.root, width=500, height=500)
self.canvas.pack()
self.score_label = tk.Label(self.root, text='得分:0', font=('Arial', 20))
self.score_label.pack()
self.time_label = tk.Label(self.root, text='时间:{}'.format(self.game_time), font=('Arial', 20))
self.time_label.pack()
self.start_button = tk.Button(self.root, text='开始游戏', font=('Arial', 20), command=self.start_game)
self.start_button.pack()
def start_game(self):
self.start_button.config(state='disabled')
self.canvas.delete('all')
self.score = 0
self.score_label.config(text='得分:{}'.format(self.score))
start_time = time.time()
while time.time() - start_time < self.game_time:
self.canvas.delete('mole')
hole = random.randint(0, 8)
x = hole % 3 * 150 + 75
y = hole // 3 * 150 + 75
self.canvas.create_image(x, y, image=self.mole, tag='mole')
self.root.update()
self.root.after(1000)
self.canvas.delete('mole')
self.canvas.create_image(x, y, image=self.holes[hole], tag='mole')
self.canvas.bind('<Button-1>', lambda event, hole=hole: self.hit_mole(event, hole))
self.root.update()
self.root.after(1000)
self.canvas.unbind('<Button-1>')
self.start_button.config(state='normal')
self.canvas.delete('all')
self.canvas.create_text(250, 200, text='游戏结束,你的得分是:{}'.format(self.score), font=('Arial', 20))
def hit_mole(self, event, hole):
x = hole % 3 * 150 + 75
y = hole // 3 * 150 + 75
if event.x < x - 50 or event.x > x + 50 or event.y < y - 50 or event.y > y + 50:
return
self.canvas.delete('mole')
self.canvas.create_image(x, y, image=self.holes[hole], tag='mole')
self.score += 1
self.score_label.config(text='得分:{}'.format(self.score))
def run(self):
self.root.mainloop()
if __name__ == '__main__':
game = MoleGame()
game.run()
```
这个游戏使用了Tkinter库来创建游戏界面,使用了PhotoImage类加载了地鼠和洞口的图片。游戏开始后,每秒钟会在9个洞口中随机生成一个地鼠,玩家需要点击打中地鼠,每打中一个地鼠得到1分。游戏时间为30秒,时间到了游戏结束,输出得分。
阅读全文