首页 > 解决方案 > 为随机化添加更多运动,添加带有矩阵的网格:Tkinter、Python

问题描述

我试图让球在所有方向(上、下、右、左、对角线)上随机移动,并使用矩阵实现网格。网格中的每个框的值都为 20,当球移过一个框时,框的值减 1。

我的主要问题是给球更多的运动,不仅仅是对角线。这是代码:

from tkinter import *
from random import randint
import time

class Ball: 
    def __init__(self,canvas,color):
        width = 1280
        height = 720        
        self.alive = True
        self.canvas = canvas 
        self.id = canvas.create_oval(30, 30, 50, 50, fill=color) 
        self.canvas.move(self.id, 640, 360)
        self.vx = randint(0,2)
        self.vy = randint(0,2)
        self.canvas_width = self.canvas.winfo_width() 
        self.canvas_height = self.canvas.winfo_height() 

    def move(self): 
        self.canvas.move(self.id, self.vx, self.vy) 
        pos = self.canvas.coords(self.id) 
        if pos[0] <= 0:
            self.vx = 1
        if pos[2] >= self.canvas_width:
            self.vx = -1
        if pos[1] <= 0:
            self.vy = 1
        if pos[3] >= self.canvas_height: 
            self.vy = -1

    def kill(self):
        self.alive = False

def main():
    tk = Tk()
    tk.title("Bee Ball")
    tk.resizable(False, False)
    tk.wm_attributes("-topmost", 1)
    canvas = Canvas(tk, bg="white", width=1280, height=720, bd=0, highlightthickness=0)
    canvas.pack()
    tk.update()

    tk.protocol("WM_DELETE_WINDOW", lambda: ball1.kill())

    ball1 = Ball(canvas, "black")
    while ball1.alive:
        tk.update()
        ball1.move()
        time.sleep(0.005)
    tk.destroy()

if __name__ == "__main__":
    main()

如果有人可以帮助并可能帮助网格/给我一些资源来研究如何用 tkinter 制作网格或帮助矩阵,那会很酷。

标签: pythontkinterrandom

解决方案


推荐阅读