2017-06-14 77 views
0

我想使用tkinter实现记分板。 如果对象子弹与对象敌人之间的距离小于10,我想让分数增加10。 如何添加代码? 预先感谢您。如何在tkinter中创建scoreborad

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

你为什么用'pygame'标记你的问题,因为你没有在代码中使用它?你还应该添加'python'标签。另外,我没有看到你的代码尝试实现记分板。如果您告诉我们您做了什么并告诉我们您卡在哪里,而不是要求人们为您编写代码,您将获得更多帮助。请参阅https://stackoverflow.com/help/asking和https://stackoverflow.com/help/how-to-ask。 –

回答

0

有许多方法可以改进您的程序,但我只专注于碰撞方面。

Tkinter帆布有几种方法; find_closest,find_enclosedfind_overlappingSee here)以允许您检测对象相互之间的关系。 find_closest将是我的第一选择。

find_closest应该采用'敌人'的x,y坐标和'晕轮距离'(您的小于10像素)。这将返回附近对象的ID。如果其中一个对象是子弹,则为分数添加10分。

一些其他的东西来修复/工作在

  • 你没有tkinter.mainloop。你应该
  • 你通过改变速度而不是xy坐标来移动飞船的方法很差,并且以一个非常快速移动的飞船结束。