Почему мои фигуры не перемещаются с canvas.move ()? - PullRequest
0 голосов
/ 20 января 2020

Я полный новичок в python. Я пытаюсь сделать игру, и я впервые использую Tkinter и canvas et c. и, если возможно, я хотел бы получить максимально простой ответ, но я ценю любой ответ Так что проблема в том, что когда я запускаю свой код, я не получаю никаких ошибок, но ничего не происходит с canvas.move (). Ни пули, ни квадрат. Но когда я помещаю оператор print, где находится canvas.move, он печатает, показывая, что код достигает этой точки, а canvas.move просто не выполняется. Мой код очень грязный, но вот он.

from tkinter import *
import time
import random

def clicked():
    global count
    global canvas
    global prompts
    global start_button
    count=count+1
    if(count <= len(prompts)-1):
        canvas.itemconfig(line_1, text=prompts[count])
        if(count==1):
            canvas.delete(title_square)
            canvas.delete(title)
            start_button["text"]="Next"
    else:
        start_button["command"]=the_name
        the_name()

def the_name():
    global name_entry
    name_entry=Entry(window)
    canvas.create_window(377, 280, window=name_entry)
    if (name_entry==""):
        pass
    else:
        start_button["command"]=retrieve_input

def retrieve_input():
    global name_entry
    global word
    word=name_entry.get()
    name_entry.destroy()
    if(word==""):
          start_button["command"]=the_name
          the_name()
    else:
        start_button["command"]=begin_level1
        begin_level1()

def begin_level1():
    global word
    global canvas
    global start_button
    prompt2=["Welcome player! To help "+word+" proceed \nyou have to dodge the bullets for 30 seconds. \nUse the arrow keys to move"]
    start_button["text"]="Begin Level 1"
    canvas.itemconfig(line_1, text=prompt2[0])
    start_button["command"]=level1

def level1():
    global canvas
    global start_button
    global canvas2
    global square
    global start_time
    start_button.destroy()
    canvas.destroy()
    canvas2=Canvas(window, width=750, height=500, bg="#00ccff")
    canvas2.pack()
    start_time=time.time()
    canvas2.bind("<KeyPress>", key_press)
    canvas2.bind("<KeyRelease>", key_release)
    hero()
    bullets()

def hero():
    global canvas2
    global square
    global squareright
    global squareleft
    global squaretop
    global squarebottom
    squareleft=377
    squareright=squareleft+25
    squaretop=375
    squarebottom=squaretop+25
    square=canvas2.create_rectangle(squareleft, squaretop, squareright, squarebottom, fill="yellow")

def key_press(event):
    global leftmove
    global rightmove
    global upmove
    global downmove
    if event.keysym=="Left":
        leftmove=1
        rightmove=0
    elif event.keysym=="Right":
        rightmove=1
        leftmove=0

    elif event.keysym=="Up":
        upmove=1
        downmove=0
    elif event.keysym=="Down":
        upmove=0
        downmove=1

def key_release(event):
    global leftmove
    global rightmove
    global upmove
    global downmove
    if event.keysym=="Left":
        leftmove=0
    elif event.keysym=="Right":
        rightmove=0
    elif event.keysym=="Up":
        upmove=0
    elif event.keysym=="Down":
        downmove=0

def move():
    global leftmove
    global rightmove
    global upmove
    global downmove
    global square
    if (global_variable.leftmove==1):
        canvas.move(square, -6, 0)
    if (global_variable.rightmove==1):
        canvas.move(square, 6, 0)
    if (global_variable.upmove==1):
        canvas.move(square, 0, -6)
    if (global_variable.downmove==1):
        canvas.move(square, 0, 6)




def bullets():
    global canvas2
    global squareright
    global squareleft
    global squaretop
    global squarebottom
    bullet1top=random.randint(10, 490)
    bullet1bottom=bullet1top+20
    bullet1left=-50
    bullet1right=bullet1left+50
    bullet2top=random.randint(10, 490)
    bullet2bottom=bullet2top+20
    bullet2right=800
    bullet2left=bullet2right-50
    bullet3top=random.randint(10, 490)
    bullet3bottom=bullet3top+20
    bullet3left=-100
    bullet3right=bullet3left+50
    bullet4top=random.randint(10, 490)
    bullet4bottom=bullet4top+20
    bullet4right=850
    bullet4left=bullet4right-50
    bullet5top=random.randint(10, 490)
    bullet5bottom=bullet5top+20
    bullet5left=-150
    bullet5right=bullet5left+50
    bullet6top=random.randint(10, 490)
    bullet6bottom=bullet6top+20
    bullet6right=900
    bullet6left=bullet6right-50
    bullet7top=random.randint(10, 490)
    bullet7bottom=bullet7top+20
    bullet7left=-200
    bullet7right=bullet7left+50
    bullet8top=random.randint(10, 490)
    bullet8bottom=bullet8top+20
    bullet8right=950
    bullet8left=bullet8right-50
    bullet9top=random.randint(10, 490)
    bullet9bottom=bullet9top+20
    bullet9left=-250
    bullet9right=bullet9left+50
    bullet10top=random.randint(10, 490)
    bullet10bottom=bullet10top+20
    bullet10right=1000
    bullet10left=bullet10right-50
    bullet1=canvas2.create_oval(bullet1left, bullet1top, bullet1right, bullet1bottom, fill="red")
    bullet2=canvas2.create_oval(bullet2left, bullet2top, bullet2right, bullet2bottom, fill="red")
    bullet3=canvas2.create_oval(bullet3left, bullet3top, bullet3right, bullet3bottom, fill="red")
    bullet4=canvas2.create_oval(bullet4left, bullet4top, bullet4right, bullet4bottom, fill="red")
    bullet5=canvas2.create_oval(bullet5left, bullet5top, bullet5right, bullet5bottom, fill="red")
    bullet6=canvas2.create_oval(bullet6left, bullet6top, bullet6right, bullet6bottom, fill="red")
    bullet7=canvas2.create_oval(bullet7left, bullet7top, bullet7right, bullet7bottom, fill="red")
    bullet8=canvas2.create_oval(bullet8left, bullet8top, bullet8right, bullet8bottom, fill="red")
    bullet9=canvas2.create_oval(bullet9left, bullet9top, bullet9right, bullet9bottom, fill="red")
    bullet10=canvas2.create_oval(bullet10left, bullet10top, bullet10right, bullet10bottom, fill="red")
    bulletmove()

def bulletmove():
    for i in range(0, 100):
        if((bullet1right!=squareleft and bullet1right!=squareright and bullet1right!=squaretop and bullet1right!=squarebottom) and
          (bullet1left!=squareleft and bullet1left!=squareright and bullet1left!=squaretop and bullet1left!=squarebottom) and
          (bullet1top!=squareleft and bullet1top!=squareright and bullet1top!=squaretop and bullet1top!=squarebottom) and
          (bullet1bottom!=squareleft and bullet1bottom!=squareright and bullet1bottom!=squaretop and bullet1bottom!=squarebottom) and
          (bullet2right!=squareleft and bullet2right!=squareright and bullet2right!=squaretop and bullet2right!=squarebottom) and
          (bullet2left!=squareleft and bullet2left!=squareright and bullet2left!=squaretop and bullet2left!=squarebottom) and
          (bullet2top!=squareleft and bullet2top!=squareright and bullet2top!=squaretop and bullet2top!=squarebottom) and
          (bullet2bottom!=squareleft and bullet2bottom!=squareright and bullet2bottom!=squaretop and bullet2bottom!=squarebottom) and
          (bullet3right!=squareleft and bullet3right!=squareright and bullet3right!=squaretop and bullet3right!=squarebottom) and
          (bullet3left!=squareleft and bullet3left!=squareright and bullet3left!=squaretop and bullet3left!=squarebottom) and
          (bullet3top!=squareleft and bullet3top!=squareright and bullet3top!=squaretop and bullet3top!=squarebottom) and
          (bullet3bottom!=squareleft and bullet3bottom!=squareright and bullet3bottom!=squaretop and bullet3bottom!=squarebottom) and
          (bullet4right!=squareleft and bullet4right!=squareright and bullet4right!=squaretop and bullet4right!=squarebottom) and
          (bullet4left!=squareleft and bullet4left!=squareright and bullet4left!=squaretop and bullet4left!=squarebottom) and
          (bullet4top!=squareleft and bullet4top!=squareright and bullet4top!=squaretop and bullet4top!=squarebottom) and
          (bullet4bottom!=squareleft and bullet4bottom!=squareright and bullet4bottom!=squaretop and bullet4bottom!=squarebottom) and
          (bullet5right!=squareleft and bullet5right!=squareright and bullet5right!=squaretop and bullet5right!=squarebottom) and
          (bullet5left!=squareleft and bullet5left!=squareright and bullet5left!=squaretop and bullet5left!=squarebottom) and
          (bullet5top!=squareleft and bullet5top!=squareright and bullet5top!=squaretop and bullet5top!=squarebottom) and
          (bullet5bottom!=squareleft and bullet5bottom!=squareright and bullet5bottom!=squaretop and bullet5bottom!=squarebottom) and
          (bullet6right!=squareleft and bullet6right!=squareright and bullet6right!=squaretop and bullet6right!=squarebottom) and
          (bullet6left!=squareleft and bullet6left!=squareright and bullet6left!=squaretop and bullet6left!=squarebottom) and
          (bullet6top!=squareleft and bullet6top!=squareright and bullet6top!=squaretop and bullet6top!=squarebottom) and
          (bullet6bottom!=squareleft and bullet6bottom!=squareright and bullet6bottom!=squaretop and bullet6bottom!=squarebottom) and
          (bullet7right!=squareleft and bullet7right!=squareright and bullet7right!=squaretop and bullet7right!=squarebottom) and
          (bullet7left!=squareleft and bullet7left!=squareright and bullet7left!=squaretop and bullet7left!=squarebottom) and
          (bullet7top!=squareleft and bullet7top!=squareright and bullet7top!=squaretop and bullet7top!=squarebottom) and
          (bullet7bottom!=squareleft and bullet7bottom!=squareright and bullet7bottom!=squaretop and bullet7bottom!=squarebottom) and
          (bullet8right!=squareleft and bullet8right!=squareright and bullet8right!=squaretop and bullet8right!=squarebottom) and
          (bullet8left!=squareleft and bullet8left!=squareright and bullet8left!=squaretop and bullet8left!=squarebottom) and
          (bullet8top!=squareleft and bullet8top!=squareright and bullet8top!=squaretop and bullet8top!=squarebottom) and
          (bullet8bottom!=squareleft and bullet8bottom!=squareright and bullet8bottom!=squaretop and bullet8bottom!=squarebottom) and
          (bullet9right!=squareleft and bullet9right!=squareright and bullet9right!=squaretop and bullet9right!=squarebottom) and
          (bullet9left!=squareleft and bullet9left!=squareright and bullet9left!=squaretop and bullet9left!=squarebottom) and
          (bullet9top!=squareleft and bullet9top!=squareright and bullet9top!=squaretop and bullet9top!=squarebottom) and
          (bullet9bottom!=squareleft and bullet9bottom!=squareright and bullet9bottom!=squaretop and bullet9bottom!=squarebottom) and
          (bullet10right!=squareleft and bullet10right!=squareright and bullet10right!=squaretop and bullet10right!=squarebottom) and
          (bullet10left!=squareleft and bullet10left!=squareright and bullet10left!=squaretop and bullet10left!=squarebottom) and
          (bullet10top!=squareleft and bullet10top!=squareright and bullet10top!=squaretop and bullet10top!=squarebottom) and
          (bullet10bottom!=squareleft and bullet10bottom!=squareright and bullet10bottom!=squaretop and bullet10bottom!=squarebottom)):
            canvas2.move(bullet1, 2, 0)
            canvas2.move(bullet2, -2, 0)
            canvas2.move(bullet3, 2, 0)
            canvas2.move(bullet4, -2, 0)
            canvas2.move(bullet5, 2, 0)
            canvas2.move(bullet6, -2, 0)
            canvas2.move(bullet7, 2, 0)
            canvas2.move(bullet8, -2, 0)
            canvas2.move(bullet9, 2, 0)
            canvas2.move(bullet10, -2, 0)



        else:
            canvas2.destroy()
            print("YOU HAVE LOST AND THE SQUARES SUFFERED FOREVER!!!! Please close the game and start again")







word=""
name_entry=""
count=0
canvas2=""
leftmove=0
rightmove=0
upmove=0
downmove=0
start_time=0
end_time=0
square=""
squareleft=0
squareright=0
squaretop=0
squarebottom=0
bullet1right=0
bullet1left=0
bullet1top=0
bullet1bottom=0
bullet2right=0
bullet2left=0
bullet2top=0
bullet2bottom=0
bullet3right=0
bullet3left=0
bullet3top=0
bullet3bottom=0
bullet4right=0
bullet4left=0
bullet4top=0
bullet4bottom=0
bullet5right=0
bullet5left=0
bullet5top=0
bullet5bottom=0
bullet6right=0
bullet6left=0
bullet6top=0
bullet6bottom=0
bullet7right=0
bullet7left=0
bullet7top=0
bullet7bottom=0
bullet8right=0
bullet8left=0
bullet8top=0
bullet8bottom=0
bullet9right=0
bullet9left=0
bullet9top=0
bullet9bottom=0
bullet10right=0
bullet10left=0
bullet10top=0
bullet10bottom=0
bullet1=0
bullet2=0
bullet3=0
bullet4=0
bullet5=0
bullet6=0
bullet7=0
bullet8=0
bullet9=0
bullet10=0



window=Tk()
window.title("The Square's Journey")
canvas=Canvas(window, width=750, height=500, bg="black")
canvas.pack()
title=canvas.create_text(375, 100, fill="white", font="Times 50 bold", text="The Square's Journey")
title_square=canvas.create_rectangle(300, 200, 450, 350, fill="yellow")
start_button=Button(window, text="Start journey", bg="white", fg="blue", command=clicked)
canvas_widget=canvas.create_window(377, 400, window=start_button)



prompts=["","Once upon a time, there was a kingdom of quadrilaterals. \nIn this kingdom, the squares are bullied by others, \nespecially rectangles.",
         "In order to save the squares, you must help the square \nfind the legendary blue paint to liberate the squares.","Please enter the name of the square"]


line_1=canvas.create_text(375, 200, fill="white", font="Times 20", text="")


window.mainloop()

Извините за беспокойство, и, пожалуйста, дайте мне знать, если вам нужна какая-либо другая информация.

1 Ответ

0 голосов
/ 21 января 2020

Здесь вы go, я очистил ваш код, создав классы. Теперь вместо глобальных переменных вы можете использовать атрибуты класса. Я думаю, что вы упустили метод canvas.focus_force(), чтобы вы могли использовать привязки клавиш. Этот метод необходимо вызывать при привязке ключей к виджетам, а не к объекту root Tk.

import tkinter as tk


class Bullet:
    '''A black rectangular object drawn to the canvas. It can move left and right.'''

    def __init__(self, canvas, coords):
        self.canvas = canvas
        self.figure = canvas.create_rectangle(*coords,fill="black")
        self.canvas.bind("<Left>", self.move_left)
        self.canvas.bind("<Right>", self.move_right)

    def move_left(self, event):
        self.canvas.move(self.figure, -5, 0)

    def move_right(self, event):
        self.canvas.move(self.figure, 5, 0)


class Level(tk.Frame):
    '''An inherited tk.Frame that acts like a scene which can be created and destroyed for multiple levels.'''

    #Pass the root Tk into the frame and call super() to inherit all tk.Frame properties
    def __init__(self, root):
        super().__init__(master=root)
        self.pack()
        self.canvas = tk.Canvas(self, width=400, height=400)
        self.canvas.pack()
        #this focus_force is probably what you were missing as it's needed for widget specific key binds.
        self.canvas.focus_force()

    def create_bullet(self, coords):
        #create an instance of the Bullet class inside of the level's canvas widget
        b = Bullet(self.canvas, coords)

#don't forget to pack your widgets or else you can't use them

root = tk.Tk()
#create the level
level1 = Level(root)
#create a bullet instance inside the canvas
level1.create_bullet((100,125,125,100))

root.mainloop()
...