python - 为随机化添加更多运动,添加带有矩阵的网格: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 制作网格或帮助矩阵,那会很酷。
解决方案
推荐阅读
- keras - 在keras中将连接输入传递给LSTM的问题
- amazon-web-services - 无服务器框架、yaml 和 AWS lambda/DynamoDB 概念
- aws-sdk-go - S3 PutObject 附加查询参数
- r - 如何在 R 中查看日期 plot3D 而不是 5 位整数
- javascript - 我无法理解缩小的 javascript “ let {styles:t={}} = e ”
- javascript - 在 Node.js SDK 中编写异步函数的首选方式
- c - 我应该避免使用守卫宏吗?
- laravel - 为什么我不能通过中间件('auth:api') 并获得 {"message":"Unauthenticated."} 尽管我发送了正确的个人访问令牌?
- python - 如何在 Google Cloud Functions 上使用 Python asyncio?
- r - 如何在R中将两行组合成一个列值