I am trying to make a ball move randomly in all direction (up, down, right, left, diagonally) as well as implement a grid using matrices. Each box in the grid will hold a value of 20 and when the ball moves over a box, the value of the box goes down by one.
My main issue is giving the ball more movement. Here is the code:
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()
If anyone can help with than and possibly with the grid/give me some resource to look into how to make a grid with tkinter or help with matrices, that would be cool.
Aucun commentaire:
Enregistrer un commentaire