GRAV变量不起作用?

时间:2018-05-02 20:09:53

标签: python python-3.x tkinter

这个程序不起作用,我试图改变对我来说似乎有什么不妥。我试图简单地制作一个重力工作的游戏,不知道我是否需要改变一切,或者只是两个引号到两个撇号

from tkinter import *
HEIGHT = 500
WIDTH = 800
GRAV = 0
Q_PRESSED = False
# to make the window
window = Tk()
window.title("jumpy jump")
c = Canvas(window, width=WIDTH, height=HEIGHT, bg='white')
c.pack()
# to create the sprite
dude_id = c.create_rectangle(0, 30, 15, 100, outline='limegreen', 
fill='limegreen')
dude_id2 = c.create_rectangle(45, 30, 60, 100, outline='limegreen', 
fill='limegreen')
dude_id3 = c.create_oval(0, 0, 60, 60, outline='limegreen', 
fill='limegreen')
def is_collided_with(dude, floor):
    return self.rect.colliderect(dude.rect)
MID_X = WIDTH / 2
MID_Y = HEIGHT / 2
c.move(dude_id, MID_X, MID_Y)
c.move(dude_id2, MID_X, MID_Y)
c.move(dude_id3, MID_X, MID_Y)
floor_id = c.create_rectangle(0, 485, 800, 500, fill='black')
while Q_PRESSED != False:
    if not dude.is_collided_with(floor):
        GRAV =+ 1
        c.move(dude_id, 0, GRAV)
        c.move(dude_id2, 0, GRAV)
        c.move(dude_id3, 0, GRAV)
    if dude.is_collided_with(floor):
    GRAV =-2
    # to move
    def move_dude(event):
        if event.keysym == 'q':
            Q_PRESSED = True
        if event.keysym == 'Left':
            c.move(dude_id, -10, GRAV)
            c.move(dude_id2, -10, GRAV)
            c.move(dude_id3, -10, GRAV)
        if event.keysym == 'Right':
            c.move(dude_id, 10, GRAV)
            c.move(dude_id2, 10, GRAV)
            c.move(dude_id3, 10, GRAV)
    c.bind_all('<key>', move_dude)

我对一本书有一些帮助,对于绑定关键内容,但它是为孩子或初学者制作的,因为我对python很新。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

我不相信这是一个单行解决方案,因为您的代码存在多个与tkinter有关的问题,而且不一定是您的重力问题:

  • 什么是self.rect.colliderect(),一个PyGame工件?

  • c.bind_all('<key>', move_dude)应该使用<Key>

  • move_dude()似乎是避免声明的内在功能 Q_PRESSED全球。

  • 没有致电mainloop()

我对代码的最小修改,以展示我相信你想要实现的运动:

from tkinter import *

HEIGHT = 500
WIDTH = 800
GRAVITY = 0

def is_collided_with(dude, floor):
    return dude in c.find_overlapping(*c.bbox(floor))

def move_dude(event):
    global GRAVITY

    if is_collided_with(dude_id, floor_id):
        GRAVITY = 0
    else:
        GRAVITY += 1

    if event.keysym == 'q':
        exit()

    if event.keysym == 'Left':
        c.move(dude_id, -10, GRAVITY)
    elif event.keysym == 'Right':
        c.move(dude_id, 10, GRAVITY)

# to make the window
window = Tk()
window.title("jumpy jump")

c = Canvas(window, width=WIDTH, height=HEIGHT, bg='white')
c.pack()

# to create the sprite
dude_id = c.create_rectangle(0, 30, 15, 100, outline='green', fill='green')
c.move(dude_id, WIDTH / 2, HEIGHT / 2)

floor_id = c.create_rectangle(0, 485, 800, 500, fill='black')

c.bind_all('<Key>', move_dude)

window.mainloop()