tkinter孤胆枪影游戏代码
时间: 2023-10-09 17:07:29 浏览: 135
Tkinter编程代码实例
5星 · 资源好评率100%
以下是一个简单的使用Tkinter实现的孤胆枪影游戏代码:
```python
import tkinter as tk
import random
# 游戏常量
WIDTH = 600
HEIGHT = 400
PLAYER_SPEED = 5
BULLET_SPEED = 7
ENEMY_SPEED = 3
ENEMY_FREQ = 100 # 敌人出现的频率(每100帧出现一个敌人)
ENEMY_SCORE = 10 # 击败敌人得到的分数
# 游戏状态
score = 0
player_alive = True
bullets = []
enemies = []
# 创建主窗口
root = tk.Tk()
root.title("孤胆枪影")
root.geometry(f"{WIDTH}x{HEIGHT}")
# 创建画布
canvas = tk.Canvas(root, bg="white")
canvas.pack(expand=True, fill=tk.BOTH)
# 创建玩家角色
player = canvas.create_rectangle(WIDTH//2-20, HEIGHT-50, WIDTH//2+20, HEIGHT-10, fill="blue")
# 创建分数标签
score_label = tk.Label(root, text=f"得分:{score}")
score_label.pack(side=tk.TOP)
# 处理按键事件
def on_key_press(event):
global player_alive, bullets
if player_alive:
x, y = canvas.coords(player)
if event.keysym == "Left":
if x > 0:
canvas.move(player, -PLAYER_SPEED, 0)
elif event.keysym == "Right":
if x < WIDTH-40:
canvas.move(player, PLAYER_SPEED, 0)
elif event.keysym == "space":
# 创建新的子弹对象
bullet = canvas.create_rectangle(x+18, y-10, x+22, y, fill="red")
bullets.append(bullet)
canvas.move(bullet, 0, -BULLET_SPEED)
elif event.keysym == "Escape":
player_alive = False
# 处理游戏循环
def loop():
global score, player_alive, bullets, enemies
if player_alive:
# 创建新的敌人对象
if random.randint(0, ENEMY_FREQ) == 0:
enemy_x = random.randint(0, WIDTH-30)
enemy = canvas.create_rectangle(enemy_x, 0, enemy_x+30, 30, fill="red")
enemies.append(enemy)
# 移动子弹
for bullet in bullets:
canvas.move(bullet, 0, -BULLET_SPEED)
# 检测子弹是否击中敌人
for enemy in enemies:
if canvas.coords(bullet)[1] < canvas.coords(enemy)[3] and \
canvas.coords(bullet)[0] > canvas.coords(enemy)[0] and \
canvas.coords(bullet)[2] < canvas.coords(enemy)[2]:
score += ENEMY_SCORE
score_label.config(text=f"得分:{score}")
canvas.delete(bullet)
bullets.remove(bullet)
canvas.delete(enemy)
enemies.remove(enemy)
break
# 检测子弹是否超出画布
if canvas.coords(bullet)[1] < 0:
canvas.delete(bullet)
bullets.remove(bullet)
# 移动敌人
for enemy in enemies:
canvas.move(enemy, 0, ENEMY_SPEED)
# 检测敌人是否撞到玩家
if canvas.coords(enemy)[3] > canvas.coords(player)[1] and \
canvas.coords(enemy)[0] < canvas.coords(player)[2] and \
canvas.coords(enemy)[2] > canvas.coords(player)[0]:
player_alive = False
canvas.create_text(WIDTH//2, HEIGHT//2, text="游戏结束", font=("Arial", 30), fill="red")
break
# 检测敌人是否超出画布
if canvas.coords(enemy)[3] > HEIGHT:
canvas.delete(enemy)
enemies.remove(enemy)
# 继续游戏循环
root.after(10, loop)
else:
# 游戏结束
canvas.create_text(WIDTH//2, HEIGHT//2, text="游戏结束", font=("Arial", 30), fill="red")
# 绑定按键事件
root.bind("<KeyPress>", on_key_press)
# 启动游戏循环
loop()
# 进入主事件循环
root.mainloop()
```
注意,这个代码只是一个简单的示例,并没有考虑到很多细节问题,如:子弹和敌人的数量限制、敌人的移动方式、玩家的生命值等等。如果想要实现更完整的孤胆枪影游戏,需要进行更多的开发工作。
阅读全文