Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Скриптовые языки программирования > Python
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 07.07.2016, 20:58   #1
Новичок Эл
Новичок
Джуниор
 
Регистрация: 07.07.2016
Сообщений: 1
Восклицание Ошибка: TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType' Как исправить?

Я изучаю Python месяц и ещё новичок.
Решил создать простую игру. Название: Охотник за пузырями.
Но при запуске выдаёт ошибку:

Traceback (most recent call last):
File "C:\Python33\Охотник за пузырями. py", line 97, in
score += collision()
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'

Что не так?
Вот код:


Код:
from tkinter import *
HEIGHT = 500
WIDTH = 800
window = Tk()
window.title('Bubble Blaster')
c = Canvas(window, width=WIDTH, height=HEIGHT, bg='darkblue')
c.pack()
ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill='red')
ship_id2 = c.create_oval(0, 0, 30, 30, outline='red')
SHIP_R = 15
MID_X = WIDTH / 2
MID_Y = HEIGHT / 2
c.move(ship_id, MID_X, MID_Y)
c.move(ship_id2, MID_X, MID_Y)
SHIP_SPD = 10
def move_ship(event):
    if event.keysym == 'Up':
        c.move(ship_id, 0, -SHIP_SPD)
        c.move(ship_id2, 0, -SHIP_SPD)
    elif event.keysym == 'Down':
        c.move(ship_id, 0, SHIP_SPD)
        c.move(ship_id2, 0, SHIP_SPD)
    elif event.keysym == 'Left':
        c.move(ship_id, -SHIP_SPD, 0)
        c.move(ship_id2, -SHIP_SPD, 0)
    elif event.keysym == 'Right':
        c.move(ship_id, SHIP_SPD, 0)
        c.move(ship_id2, SHIP_SPD, 0)
c.bind_all('<Key>', move_ship)
from random import randint
bub_id = list()
bub_r = list()
bub_speed = list()
MIN_BUB_R = 10
MAX_BUB_R = 30
MAX_BUB_SPD = 10
GAP = 100
def create_bubble():
    x = WIDTH + GAP
    y = randint(0, HEIGHT)
    r = randint(MIN_BUB_R, MAX_BUB_R)
    id1 = c.create_oval(x - r, y - r, x + r, y + r, outline='white')
    bub_id.append(id1)
    bub_r.append(r)
    bub_speed.append(randint(1, MAX_BUB_SPD))
def move_bubbles():
    for i in range(len(bub_id)):
        c.move(bub_id[i], -bub_speed[i], 0)
def get_coords(id_num):
    pos = c.coords(id_num)
    x = (pos[0] + pos[2])/2
    y = (pos[1] + pos[3])/2
    return x, y
def del_bubble(i):
    del bub_r[i]
    del bub_speed[i]
    c.delete(bub_id[i])
    del bub_id[i]
def clean_up_bubs():
    for i in range(len(bub_id)-1, -1, -1):
        x, y = get_coords(bub_id[i])
        if x < -GAP:
            del_bubble(i)
from math import sqrt
def distance(id1, id2):
    x1, y1 = get_coords(id1)
    x2, y2 = get_coords(id2)
    return sqrt((x2 - x1)**2 + (y2 - y1)**2)
def collision():
    points = 0
    for bub in range(len(bub_id)-1, -1, -1):
        if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]):
            points += (bub_r[bub] + bub_speed[bub])
            del_bubble(bub)
        return points
c.create_text(50, 30, text='TIME', fill='white' )
c.create_text(150, 30, text='SCORE', fill='white' )
time_text = c.create_text(50, 50, fill='white' )
score_text = c.create_text(150, 50, fill='white' )
def show_score(score):
    c.itemconfig(score_text, text=str(score))
def show_time(time_left):
    c.itemconfig(time_text, text=str(time_left))
from time import sleep, time
BUB_CHANCE = 10
TIME_LIMIT = 30
BONUS_SCORE = 1000
score = 0
bonus = 0
end = time() + TIME_LIMIT
#MAIN GAME LOOP
while time() < end:
    if randint(1, BUB_CHANCE) == 1:
        create_bubble()
    move_bubbles()
    clean_up_bubs()
    score += collision()
    if (int(score / BONUS_SCORE)) > bonus:
        bonus += 1
        end += TIME_LIMIT
    show_score(score)
    show_time(int(end - time()))
    window.update()
    sleep(0.01)
c.create_text(MID_X, MID_Y, \
              text='GAME OVER', fill='white', font=('Helvetica',30))
c.create_text(MID_X, MID_Y + 30, \
              text='Score: '+ str(score), fill='white')
c.create_text(MID_X, MID_Y + 45, \
              text='Bonus time: '+ str(bonus*TIME_LIMIT), fill='white')

Последний раз редактировалось Alex11223; 07.07.2016 в 21:10.
Новичок Эл вне форума Ответить с цитированием
Старый 07.07.2016, 21:13   #2
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Код collision странный, может быть return points должно было быть после цикла? (1 отступ вместо 2).
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Старый 07.07.2016, 21:25   #3
pompiduskus
юзер как все
Участник клуба
 
Аватар для pompiduskus
 
Регистрация: 10.01.2012
Сообщений: 1,586
По умолчанию

Alex11223 правильно подметил.
return должен быть по любому. даже если небыло нужных совпадений

А у вас получается перебор, и если нет совпадений то ничего (None) "возвращается"

А None + Integer неможет быть, вот они говорит что

for +=: 'int' and 'NoneType'

Вот так попробуйте

PHP код:
# -*- coding: utf-8 -*-

from tkinter import *
from time import sleeptime
from random import randint
from math import sqrt

# =====================================================================
HEIGHT 500
WIDTH 
800
window 
Tk()
window.title('Bubble Blaster')
Canvas(windowwidth=WIDTHheight=HEIGHTbg='darkblue')
c.pack()
ship_id c.create_polygon(555253015fill='red')
ship_id2 c.create_oval(003030outline='red')
SHIP_R 15
MID_X 
WIDTH 2
MID_Y 
HEIGHT 2
c
.move(ship_idMID_XMID_Y)
c.move(ship_id2MID_XMID_Y)
SHIP_SPD 10

def move_ship
(event):
    if 
event.keysym == 'Up':
        
c.move(ship_id0, -SHIP_SPD)
        
c.move(ship_id20, -SHIP_SPD)
    
elif event.keysym == 'Down':
        
c.move(ship_id0SHIP_SPD)
        
c.move(ship_id20SHIP_SPD)
    
elif event.keysym == 'Left':
        
c.move(ship_id, -SHIP_SPD0)
        
c.move(ship_id2, -SHIP_SPD0)
    
elif event.keysym == 'Right':
        
c.move(ship_idSHIP_SPD0)
        
c.move(ship_id2SHIP_SPD0)

c.bind_all('<Key>'move_ship)
bub_id = list()
bub_r = list()
bub_speed = list()
MIN_BUB_R 10
MAX_BUB_R 
30
MAX_BUB_SPD 
10
GAP 
100

def create_bubble
():
    
WIDTH GAP
    y 
randint(0HEIGHT)
    
randint(MIN_BUB_RMAX_BUB_R)
    
id1 c.create_oval(rrrroutline='white')
    
bub_id.append(id1)
    
bub_r.append(r)
    
bub_speed.append(randint(1MAX_BUB_SPD))

def move_bubbles():
    for 
i in range(len(bub_id)):
        
c.move(bub_id[i], -bub_speed[i], 0)

def get_coords(id_num):
    
pos c.coords(id_num)
    
= (pos[0] + pos[2])/2
    y 
= (pos[1] + pos[3])/2
    
return xy

def del_bubble
(i):
    
del bub_r[i]
    
del bub_speed[i]
    
c.delete(bub_id[i])
    
del bub_id[i]

def clean_up_bubs():
    for 
i in range(len(bub_id)-1, -1, -1):
        
xget_coords(bub_id[i])
        if 
< -GAP:
            
del_bubble(i)

def distance(id1id2):
    
x1y1 get_coords(id1)
    
x2y2 get_coords(id2)
    return 
sqrt((x2 x1)**+ (y2 y1)**2)

def collision():
    
points 0
    
for bub in range(len(bub_id)-1, -1, -1):
        if 
distance(ship_id2bub_id[bub]) < (SHIP_R bub_r[bub]):
            
points += (bub_r[bub] + bub_speed[bub])
            
del_bubble(bub)

        return 
points
    
return points;

c.create_text(5030text='TIME'fill='white' )
c.create_text(15030text='SCORE'fill='white' )
time_text c.create_text(5050fill='white' )
score_text c.create_text(15050fill='white' )

def show_score(score):
    
c.itemconfig(score_texttext=str(score))

def show_time(time_left):
    
c.itemconfig(time_texttext=str(time_left))

BUB_CHANCE 10
TIME_LIMIT 
30
BONUS_SCORE 
1000
score 
0
bonus 
0
end 
time() + TIME_LIMIT

#MAIN GAME LOOP
while time() < end:

    if 
randint(1BUB_CHANCE) == 1:
        
create_bubble()
    
move_bubbles()
    
clean_up_bubs()
    
score += collision()

    if (
int(score BONUS_SCORE)) > bonus:
        
bonus += 1
        end 
+= TIME_LIMIT
    show_score
(score)
    
show_time(int(end time()))
    
window.update()
    
sleep(0.01)

c.create_text(MID_XMID_Ytext='GAME OVER'fill='white'font=('Helvetica',30))
c.create_text(MID_XMID_Y 30text='Score: 'str(score), fill='white')
c.create_text(MID_XMID_Y 45text='Bonus time: 'str(bonus*TIME_LIMIT), fill='white'
<Дзен - Вся вселенная в тебе > | Резюме: https://ch3ll0v3k.github.io/CV/

Последний раз редактировалось pompiduskus; 07.07.2016 в 21:28.
pompiduskus вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Operator not applicable to this operand type NewLamer&Programer Общие вопросы Delphi 5 11.05.2013 13:27
С++ not implemented in type 'istream' for arguments of type 'float *'из-за чего эта ошибка и как исправить? Mitax-47 Помощь студентам 1 10.05.2013 15:48
Operator not applicable to this operand type Makaralex Помощь студентам 2 07.09.2012 11:52
Operator not applicable to this operand type welcomeTo Помощь студентам 9 06.06.2011 21:01
ошибка - [Error] Unit1.pas(325): Operator not applicable to this operand type blackstersl Общие вопросы Delphi 6 27.08.2008 13:17