2016-02-05 81 views
-1

我在Python(tkinter)中创建一个游戏,但我从来没有用Python编写过。 我尝试移动的物体椭圆称为“地雷”在Python中移动对象?

def create_mines(): 
    x1 = randint(600,800) 
    y1 = randint(600,800) 
    x2 = randint(600,800) 
    y2 = randint(600,800) 
    r = randint(5,100) 
    mine = c.create_oval(x1,y1, x2, y2) 
    bubble_r.append(r) 
    bubble_id.append(mine) 

列表名称bubble_id,每个矿井存储在列表中。我试图将椭圆移动到画布的顶部,我的指示是使用for循环移动它们。我是否使用for循环遍历列表?我如何确保在整个程序的运行时间里矿井继续向上移动?此外,我已经给出的基本代码不带任何参数。

回答

0

您使用for循环来创建更多地雷并使用地雷遍历列表。

您必须使用root.after来反复运行能够以小步移动地雷的功能。这样你就不会停止主循环。

import tkinter as tk 
import random 

# --- functions --- 

def create_mines(canvas): 

    bubbles = [] 

    for __ in range(10): 

     x = random.randint(0, 400) 
     y = random.randint(0, 400) 
     r = random.randint(5, 10) 

     mine = canvas.create_oval(x-r, y-r, x+r, y+r) 

     bubbles.append([mine, r]) 

    return bubbles 


def moves_mines(canvas, bubbles): 

    for mine, r in bubbles: 

     #canvas.move(mine, 0, -1) 

     # get position 
     x1, y1, x2, y2 = canvas.coords(mine) 

     # change 
     y1 -= 1 
     y2 -= 1 

     # if top then move to the bottom 
     if y2 <= 0: 
      y1 = 300 
      y2 = y1 + 2*r 

     # set position 
     canvas.coords(mine, x1, y1, x2, y2) 

    # run after 40ms - it gives 25FPS 
    root.after(40, moves_mines, canvas, bubbles) 

# --- main --- 

root = tk.Tk() 

canvas = tk.Canvas(root) 
canvas.pack() 

bubbles = create_mines(canvas) 

# run after 40ms - it gives 25FPS 
root.after(40, moves_mines, canvas, bubbles) 

root.mainloop()