我想使用tkinter实现记分板。 如果对象子弹和对象敌人之间的距离小于10,我想要制作,我想将分数提高10。 如何添加代码? 提前谢谢。
from tkinter import *
import time
import random
WIDTH = 800
HEIGHT = 800
class Ball:
def __init__(self, canvas, color, size, x, y, xspeed, yspeed):
self.canvas = canvas
self.color = color
self.size = size
self.x = x
self.y = y
self.xspeed = xspeed
self.yspeed = yspeed
self.id = canvas.create_oval(x, y, x+size, y+size, fill=color)
def move(self):
self.canvas.move(self.id, self.xspeed, self.yspeed)
(x1, y1, x2, y2) = self.canvas.coords(self.id)
(self.x, self.y) = (x1, y1)
if x1 <= 0 or x2 >= WIDTH:
self.xspeed = - self.xspeed
if y1 <= 0 or y2 >= HEIGHT:
self.yspeed = - self.yspeed
bullets = []
def fire(event):
bullets.append(Ball(canvas, "red", 10, 150, 250, 10, 0))
def up(event):
spaceship.yspeed-=1
def down(event):
spaceship.yspeed+=1
window = Tk()
canvas = Canvas(window, width=WIDTH, height=HEIGHT)
canvas.pack()
canvas.bind("<Button-1>", fire)
window.bind("<Up>",up)
window.bind("<Down>",down)
spaceship = Ball(canvas, "green", 100, 100, 200, 0, 0)
enemy = Ball(canvas, "red", 100, 500, 200, 5, 0)
while True:
for bullet in bullets:
bullet.move()
if (bullet.x+bullet.size) >= WIDTH:
canvas.delete(bullet.id)
bullets.remove(bullet)
enemy.move()
spaceship.move()
window.update()
time.sleep(0.03)
答案 0 :(得分:0)
有很多方法可以改进你的程序,但我只专注于碰撞方面。
Tkinter canvas有几种方法; onMessageReceived
,{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
和find_closest
(See here)允许您检测对象相对于彼此的位置。 find_enclosed
将是我的第一选择。
find_overlapping
应该采取“敌人”的x,y坐标。和一个光晕距离&#39; (你的不到10个像素)。这将返回附近物体的id。如果其中一个对象是子弹,则在分数中添加10个点。
要修复/处理的其他一些事情