tkinter做圆圈战争游戏代码
时间: 2024-02-04 16:43:47 浏览: 107
以下是一个简单的圆圈战争游戏的Tkinter代码:
```python
import tkinter as tk
import random
# 游戏窗口大小
WIDTH = 600
HEIGHT = 600
# 玩家圆圈大小和速度
PLAYER_RADIUS = 20
PLAYER_SPEED = 5
# 敌人圆圈大小和速度
ENEMY_RADIUS = 10
ENEMY_SPEED = 3
# 玩家初始位置和颜色
PLAYER_START_X = WIDTH // 2
PLAYER_START_Y = HEIGHT // 2
PLAYER_COLOR = 'blue'
# 敌人初始数量
NUM_ENEMIES = 10
# 玩家得分
SCORE = 0
class CircleWars:
def __init__(self, master):
self.master = master
master.title('Circle Wars')
master.geometry(f'{WIDTH}x{HEIGHT}')
# 创建画布
self.canvas = tk.Canvas(master, width=WIDTH, height=HEIGHT)
self.canvas.pack()
# 创建玩家圆圈
self.player = self.canvas.create_oval(
PLAYER_START_X - PLAYER_RADIUS,
PLAYER_START_Y - PLAYER_RADIUS,
PLAYER_START_X + PLAYER_RADIUS,
PLAYER_START_Y + PLAYER_RADIUS,
fill=PLAYER_COLOR
)
# 创建敌人圆圈
self.enemies = []
for i in range(NUM_ENEMIES):
x = random.randint(0, WIDTH)
y = random.randint(0, HEIGHT)
enemy = self.canvas.create_oval(
x - ENEMY_RADIUS,
y - ENEMY_RADIUS,
x + ENEMY_RADIUS,
y + ENEMY_RADIUS,
fill='red'
)
self.enemies.append(enemy)
# 绑定键盘事件
self.canvas.bind('<Key>', self.move_player)
self.canvas.focus_set()
# 显示得分
self.score_text = self.canvas.create_text(
50, 50,
text=f'Score: {SCORE}',
fill='white',
font=('Arial', 24)
)
# 启动游戏循环
self.game_loop()
def move_player(self, event):
# 移动玩家圆圈
if event.keysym == 'Up':
self.canvas.move(self.player, 0, -PLAYER_SPEED)
elif event.keysym == 'Down':
self.canvas.move(self.player, 0, PLAYER_SPEED)
elif event.keysym == 'Left':
self.canvas.move(self.player, -PLAYER_SPEED, 0)
elif event.keysym == 'Right':
self.canvas.move(self.player, PLAYER_SPEED, 0)
# 检查是否碰到敌人圆圈
self.check_collisions()
def check_collisions(self):
global SCORE
# 获取玩家圆圈的坐标和半径
x1, y1, x2, y2 = self.canvas.coords(self.player)
player_x = (x1 + x2) / 2
player_y = (y1 + y2) / 2
player_r = (x2 - x1) / 2
# 检查每个敌人圆圈是否与玩家圆圈相交
for enemy in self.enemies:
x1, y1, x2, y2 = self.canvas.coords(enemy)
enemy_x = (x1 + x2) / 2
enemy_y = (y1 + y2) / 2
enemy_r = (x2 - x1) / 2
# 如果相交,则玩家失败
if (enemy_x - player_x) ** 2 + (enemy_y - player_y) ** 2 <= (enemy_r + player_r) ** 2:
self.canvas.delete(self.player)
self.canvas.create_text(
WIDTH // 2, HEIGHT // 2,
text='Game Over',
fill='white',
font=('Arial', 48)
)
# 更新得分
SCORE += 1
self.canvas.itemconfig(self.score_text, text=f'Score: {SCORE}')
def game_loop(self):
# 移动每个敌人圆圈
for enemy in self.enemies:
dx = random.randint(-ENEMY_SPEED, ENEMY_SPEED)
dy = random.randint(-ENEMY_SPEED, ENEMY_SPEED)
self.canvas.move(enemy, dx, dy)
# 检查是否碰到敌人圆圈
self.check_collisions()
# 继续游戏循环
self.master.after(50, self.game_loop)
# 启动游戏
root = tk.Tk()
game = CircleWars(root)
root.mainloop()
```
这个游戏包括一个玩家圆圈和多个敌人圆圈。玩家使用方向键控制圆圈移动,当玩家碰到敌人圆圈时,游戏结束。每次玩家移动,得分加1。游戏循环每50毫秒运行一次,移动敌人圆圈并检查碰撞。
阅读全文