Уведомления

Группа в Telegram: @pythonsu

#1 Дек. 26, 2019 09:26:44

JohnMc
Зарегистрирован: 2019-12-26
Сообщения: 8
Репутация: +  0  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

Возникла ошибка:NameError: name ‘catcher’ is not defined
Код:

import random
from itertools import cycle
from tkinter import Tk,Canvas,messagebox,font
canvas_width = 800
canvas_height = 400
root = Tk()
root.title('Яйцелов')
c = Canvas(root,width = canvas_width,height = 400,background = ‘deep sky blue’)
c.create_rectangle(-5,canvas_height - 100,canvas_width + 5,canvas_height + 5,fill = ‘sea green’,width = 0)
c.create_oval(-80,-80,120,120,fill = ‘orange’,width = 0)
c.pack()
color_cycle = cycle()
egg_width = 45
egg_height = 55
egg_score = 10
egg_speed = 500
egg_interval = 4000
difficulty_factor = 0.95
catcher_color = ‘blue’
catcher_width = 100
catcher_height = 100
catcher_start_x = canvas_width / 2 - catcher_width / 2
catcher_start_y = canvas_height - catcher_height - 20
catcher_start_x2 = catcher_start_x + catcher_width
catcher_start_y2 = catcher_start_y + catcher_height
catсher = c.create_arc(catcher_start_x,catcher_start_y,catcher_start_x2,catcher_start_y2,\
start = 200,extent = 140,style = ‘arc’,outline = catcher_color,width = 3)
game_font = font.nametofont('TkFixedFont')
game_font.config(size = 18)
score = 0
score_text = c.create_text(10,10,anchor = ‘nw’,font = game_font,fill = ‘dark blue’,text = ‘Счёт: ’ + str(score))
lives_remaining = 3
lives_text = c.create_text(canvas_width - 10,10,anchor = ‘ne’,font = game_font,fill = ‘darkblue’,\
text = ‘Жизней: ’ + str(lives_remaining))
eggs =
def create_egg():
x = random.randrange(10,740)
y = 40
new_egg = c.create_oval(x,y,x + egg_width,y + egg_height,fill = next(color_cycle),width = 0)
eggs.append(new_egg)
root.after(egg_interval,create_egg)


def move_eggs():
for egg in eggs:
(egg_x,egg_y,egg_x2,egg_y2,) = c.coords(egg)
c.move(egg,0,5)
if egg_y2 > canvas_height:
egg_dropped(egg)
root.after(egg_speed,move_eggs)

def egg_dropped(egg):
eggs.remove(egg)
c.delete(egg)
lose_a_life()
if lives_remaining == 0:
messagebox.showinfo('Конец игры !','Итоговый счёт: ‘ + str(score))
root.destroy()


def lose_a_life():
global lives_remaining
lives_remaining -= 1
c.itemconfigure(lives_text,text = ’Жизней: ‘ + str(lives_remaining))

def check_catch():
(catcher_x,catcher_y,catcher_x2,catcher_y2) = c.coords(catcher)
return catcher
for egg in eggs:
(egg_x,egg_y,egg_x2,egg_y2,) = c.coords(egg)
if x < egg_x and egg_x2 < x2 and y2 - egg_y2 < 40:
eggs.remove(egg)
c.delete(egg)
increase_score(egg_score)
root.after(100,check_catch)

def increase_score(points):
global score,egg_speed,egg_interval
score += points
egg_speed = int(egg_speed * difficulty_factor)
egg_interval = int(egg_interval * difficulty_factor)
c.itemconfigure(score_text,text = ’Счёт: ‘ + str(score))



def move_left(event):
(x1,y1,x2,y2) = c.coords(catcher)
if catcher_x1 > 0:
c.move(catcher,-20,0)



def move_right(event):
(x1,y1,x2,y2) = c.coords(catcher)
if x2 < canvas_width:
c.move(catcher,20,0)

c.bind(’<Left>',move_left)
c.bind('<Right>',move_right)
c.focus_set()
root.after(1000,create_egg)
root.after(1000,move_eggs)
root.after(1000,check_catch)
root.mainloop()
Выдаёт ошибку:
Exception in Tkinter callback
Traceback (most recent call last):
File “Python\Python37\lib\tkinter\__init__.py”, line 1705, in __call__
return self.func(*args)
File “Python\Python37\lib\tkinter\__init__.py”, line 749, in callit
func(*args)
File “Проекты_Python\Other_programs\egg_cather.py”, line 67, in check_catch
(catcher_x,catcher_y,catcher_x2,catcher_y2) = c.coords(catcher)
NameError: name ‘catcher’ is not defined
Помогите пожалуйста , не могу разобраться в чём проблема.
Заранее спасибо.

Отредактировано JohnMc (Дек. 26, 2019 13:12:43)

Прикреплённый файлы:
attachment egg_cather.py (3,4 KБ)

Офлайн

#2 Дек. 26, 2019 09:42:47

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

ну наверное в том что итaпретатор не знает такой пременной как catcher в пространстве имен этой функции (check_catch)



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Дек. 26, 2019 10:33:33)

Офлайн

#3 Дек. 26, 2019 10:59:23

rami
Зарегистрирован: 2018-01-08
Сообщения: 281
Репутация: +  72  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

Потому что в 26 строке в слове cather отсутствует “c”.

Офлайн

#4 Дек. 26, 2019 12:37:36

JohnMc
Зарегистрирован: 2019-12-26
Сообщения: 8
Репутация: +  0  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

rami
Потому что в 26 строке в слове cather отсутствует “c”.
Спасибо исправил.
Но всё равно пишет ошибку.

Офлайн

#5 Дек. 26, 2019 12:42:27

JohnMc
Зарегистрирован: 2019-12-26
Сообщения: 8
Репутация: +  0  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

AD0DE412
ну наверное в том что итaпретатор не знает такой пременной как catcher в пространстве имен этой функции (check_catch)
А каким образом это исправить?

Офлайн

#6 Дек. 26, 2019 12:50:21

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

двайте так

 """
закаментируем все функции и связаное с ними конечно
"""
и сделаем print(catcher, type(catcher)) после обявления переменной
зы сделайте нормальным код в первом посте



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Дек. 26, 2019 12:59:50)

Офлайн

#7 Дек. 26, 2019 13:14:44

JohnMc
Зарегистрирован: 2019-12-26
Сообщения: 8
Репутация: +  0  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

AD0DE412
двайте так
Я не понял ,могли бы вы указать это место в коде или в частичке кода

Офлайн

#8 Дек. 26, 2019 13:19:54

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

ну вся идея в том что бы проверить переменную catcher избавившись на время проверки от ее исползования в коде уж не знаю что тут показывать



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Офлайн

#9 Дек. 26, 2019 13:32:32

JohnMc
Зарегистрирован: 2019-12-26
Сообщения: 8
Репутация: +  0  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

В любом случае пишет ошибку даже если так

Отредактировано JohnMc (Дек. 26, 2019 13:33:01)

Офлайн

#10 Дек. 26, 2019 14:06:35

AD0DE412
Зарегистрирован: 2019-05-12
Сообщения: 1130
Репутация: +  44  -
Профиль   Отправить e-mail  

Возникла ошибка:NameError: name 'catcher' is not defined

УМВР

 import random
from itertools import cycle
from tkinter import Tk,Canvas,messagebox,font
canvas_width = 800
canvas_height = 400
root = Tk()
root.title('Яйцелов')
c = Canvas(root,width = canvas_width,height = 400,background = 'deep sky blue')
c.create_rectangle(-5,canvas_height - 100,canvas_width + 5,canvas_height + 5,fill = 'sea green',width = 0)
c.create_oval(-80,-80,120,120,fill = 'orange',width = 0)
c.pack()
color_cycle = cycle(['light blue','light green','light yellow','light cyan','white'])
egg_width = 45
egg_height = 55
egg_score = 10
egg_speed = 500
egg_interval = 4000
difficulty_factor = 0.95
catcher_color = 'blue'
catcher_width = 100
catcher_height = 100
catcher_start_x = canvas_width / 2 - catcher_width / 2
catcher_start_y = canvas_height - catcher_height - 20
catcher_start_x2 = catcher_start_x + catcher_width
catcher_start_y2 = catcher_start_y + catcher_height
catcher = c.create_arc(catcher_start_x,catcher_start_y,catcher_start_x2,catcher_start_y2,\
                      start = 200,extent = 140,style = 'arc',outline = catcher_color,width = 3)
game_font = font.nametofont('TkFixedFont')
game_font.config(size = 18)
score = 0
score_text = c.create_text(10,10,anchor = 'nw',font = game_font,fill = 'dark blue',text = 'Счёт: ' + str(score))
lives_remaining = 3
lives_text = c.create_text(canvas_width - 10,10,anchor = 'ne',font = game_font,fill = 'darkblue',\
                           text = 'Жизней: ' + str(lives_remaining))
eggs = []
def create_egg():
    x = random.randrange(10,740)
    y = 40
    new_egg = c.create_oval(x,y,x + egg_width,y + egg_height,fill = next(color_cycle),width = 0)
    eggs.append(new_egg)
    root.after(egg_interval,create_egg)
def move_eggs():
    for egg in eggs:
        (egg_x,egg_y,egg_x2,egg_y2,) = c.coords(egg)
        c.move(egg,0,5)
        if egg_y2 > canvas_height:
            egg_dropped(egg)
        root.after(egg_speed,move_eggs)
def egg_dropped(egg):
    eggs.remove(egg)
    c.delete(egg)
    lose_a_life()
    if lives_remaining == 0:
        messagebox.showinfo('Конец игры !','Итоговый счёт: ' + str(score))
        root.destroy()
def lose_a_life():
    global lives_remaining
    lives_remaining -= 1
    c.itemconfigure(lives_text,text = 'Жизней: ' + str(lives_remaining))
def check_catch():
    (catcher_x,catcher_y,catcher_x2,catcher_y2) = c.coords(catcher)
    return catcher
    for egg in eggs:
        (egg_x,egg_y,egg_x2,egg_y2,) = c.coords(egg)
        if x < egg_x and egg_x2 < x2 and y2 - egg_y2  < 40:
            eggs.remove(egg)
            c.delete(egg)
            increase_score(egg_score)
        root.after(100,check_catch)
def increase_score(points):
    global score,egg_speed,egg_interval
    score += points
    egg_speed = int(egg_speed * difficulty_factor)
    egg_interval = int(egg_interval * difficulty_factor)
    c.itemconfigure(score_text,text = 'Счёт: ' + str(score))
def move_left(event):
    (x1,y1,x2,y2) = c.coords(catcher)
    if catcher_x1 > 0:
        c.move(catcher,-20,0)
def move_right(event):
    (x1,y1,x2,y2) = c.coords(catcher)
    if x2 < canvas_width:
        c.move(catcher,20,0)
c.bind('<Left>',move_left)
c.bind('<Right>',move_right)
c.focus_set()
root.after(1000,create_egg)
root.after(1000,move_eggs)
root.after(1000,check_catch)
root.mainloop()

ps хорошоя попытка совладать с форумным движком кхм кхм нужн выделить текст который вы собираетесь обозначить как код и нжать значек



1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например), нажмите и вставьте ссылку на его url

есчщо

Отредактировано AD0DE412 (Дек. 26, 2019 14:22:04)

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version