Форум программистов, компьютерный форум, киберфорум
Python: PyGame
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.54/13: Рейтинг темы: голосов - 13, средняя оценка - 4.54
0 / 0 / 0
Регистрация: 08.05.2021
Сообщений: 6

TypeError: 'NoneType' object is not subscriptable

08.05.2021, 18:51. Показов 2848. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте. Недавно начал программирование и уже натыкаюсь на казусы (в данном случае выдает TypeError: 'NoneType' object is not subscriptable). Где я допустил ошибку?
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import pygame as pg
from random import randint
 
pg.init()
 
screen = pg.display.set_mode((800, 600))
pg.display.set_caption("Relzzz")
 
icon = pg.image.load("icon.png")
pg.display.set_icon(icon)
 
grass = pg.image.load("grass.jpg")
 
horse = {
    "x": 350, "y": 250,
    "image_number": 0
}
horse_image_number = 0
 
horse_stand = pg.image.load(r"horse/horse_stand.png")
horse_left = [
    pg.image.load(r"horse/horse_left_0.png"),
    pg.image.load(r"horse/horse_left_1.png"),
    pg.image.load(r"horse/horse_left_2.png"),
    pg.image.load(r"horse/horse_left_3.png"),
]
 
horse_right = [
    pg.image.load(r"horse/horse_right_0.png"),
    pg.image.load(r"horse/horse_right_1.png"),
    pg.image.load(r"horse/horse_right_2.png"),
    pg.image.load(r"horse/horse_right_3.png"),
]
 
horse_up = [
    pg.image.load(r"horse/horse_up_0.png"),
    pg.image.load(r"horse/horse_up_1.png"),
    pg.image.load(r"horse/horse_up_2.png"),
    pg.image.load(r"horse/horse_up_3.png"),
]
 
horse_down = [
    pg.image.load(r"horse/horse_down_0.png"),
    pg.image.load(r"horse/horse_down_1.png"),
    pg.image.load(r"horse/horse_down_2.png"),
    pg.image.load(r"horse/horse_down_3.png"),
]
 
anhorse = {
    "x": randint(0, 700), "y": randint(0, 500)
}
 
bee = [
    pg.image.load(r"bee/bee_0.png"), (r"bee/bee_1.png"),
    pg.image.load(r"bee/bee_2.png"), (r"bee/bee_4.png"),
]
 
monster_x = randint(500, 800)
monster_y = 0
monster_y -= 100
monster_speed_x = randint(3, 8)
monster_speed_y = randint(4, 10)
monster_fly_image_number = 0
monster_hit_image_number = 0
monster_animation_type = "fly"
 
monster_fly = [
    pg.image.load(r"green_monster/monster_fly_0.png"),
    pg.image.load(r"green_monster/monster_fly_1.png"),
    pg.image.load(r"green_monster/monster_fly_2.png"),
    pg.image.load(r"green_monster/monster_fly_3.png"),
]
 
monster_hit = [
    pg.image.load(r"green_monster/monster_hit_0.png"),
    pg.image.load(r"green_monster/monster_hit_1.png"),
    pg.image.load(r"green_monster/monster_hit_0.png"),
    pg.image.load(r"green_monster/monster_hit_1.png"),
]
 
draw_another_horse = pg.image.load(r"horse/horse_stand.png")
clock = pg.time.Clock()
game_over = False
 
def create_another_monster():
    global screen
    global another_monster
 
    another_monster = {
        "x": randint(0, 700), "y": randint(0, 500),
        "image_number": 0,
        "images": [
            pg.image.load(r"green_monster/monster_fly_0.png"),
            pg.image.load(r"green_monster/monster_fly_1.png"),
            pg.image.load(r"green_monster/monster_fly_2.png"),
            pg.image.load(r"green_monster/monster_fly_3.png"),
            ]
        }
        
def draw_another_monster():
    global screen
    global another_monster
    
    screen.blit(monster_fly[another_monster["image_number"] // 5], (another_monster["x"], another_monster["y"]))
    another_monster["image_number"] += 1
    
    if another_monster["image_number"] > 19:
        another_monster["image_number"] = 0
 
 
def draw_monster():
    global screen
    global monster_fly, monster_hit, monster_x, monster_y
    global monster_speed_x, monster_speed_y
    global monster_fly_image_number, monster_hit_image_number
    global monster_animation_type
    global another_monster
    
    if monster_x <= 0 or monster_y >= 470:
        monster_animation_type = "hit"
        
    if monster_animation_type == "hit":
    
        screen.blit(monster_hit[monster_hit_image_number // 8], (monster_x, monster_y))
        monster_hit_image_number += 1
        if monster_hit_image_number > 31:
            monster_hit_image_number = 0
            monster_animation_type = "fly"
            
            monster_x = randint(500, 800)
            monster_y = 0
            monster_y -= 100
            monster_speed_x = randint(3, 8)
            monster_speed_y = randint(4, 10)
            
    elif monster_animation_type == "fly":
        monster_x -= monster_speed_x
        monster_y += monster_speed_y
        screen.blit(monster_fly[monster_fly_image_number // 5], (monster_x, monster_y))
        
        monster_fly_image_number += 1
        if monster_fly_image_number > 19:
            monster_fly_image_number = 0
    
 
def create_bee():
    bee_dict = {
        "x": 0, "y": randint(0, 500),
        "image_number": 0,
        "speed": randint(3, 10),
        "images": [
            pg.image.load(r"bee/bee_0.png"),
            pg.image.load(r"bee/bee_1.png"),
            pg.image.load(r"bee/bee_2.png"),
            pg.image.load(r"bee/bee_3.png"),
            pg.image.load(r"bee/bee_4.png"),
            pg.image.load(r"bee/bee_5.png"),
        ]
    }
    bee_dict["x"] -= 100
    return bee_dict
 
def draw_bee():
    global screen
    global bee
    
    bee["x"] += bee["speed"]
    if bee["x"] > 800:
        bee["x"] = 0
        bee["x"] -= 100
        bee["y"] = randint(0, 500)
        bee["speed"] = randint(3, 10)
 
    screen.blit(bee["images"][bee["image_number"] // 3], (bee["x"], bee["y"]))
 
    bee["image_number"] += 1
    if bee["image_number"] > 17:
        bee["image_number"] = 0
        
def draw_another_horse():
    global screen
    global horse_stand
    
    screen.blit(horse_stand, (anhorse["x"], anhorse["y"]))
    
def draw_horse():
    global screen
    global horse_stand, horse_left, horse_up, horse_down
    global horse_x, horse_y, horse_image_number
    
    keys = pg.key.get_pressed()
    if keys[pg.K_LEFT]:
        horse["x"] -= 3
        screen.blit(horse_left[horse["image_number"] // 5], (horse["x"], horse["y"]))
        horse["image_number"] += 1
    elif keys[pg.K_RIGHT]:
        horse["x"] += 3
        screen.blit(horse_right[horse["image_number"] // 5], (horse["x"], horse["y"]))
        horse["image_number"] += 1
    elif keys[pg.K_UP]:
        horse["y"] -= 3
        screen.blit(horse_up[horse["image_number"] // 5], (horse["x"], horse["y"]))
        horse["image_number"] += 1
    elif keys[pg.K_DOWN]:
        horse["y"] += 3
        screen.blit(horse_down[horse["image_number"] // 5], (horse["x"], horse["y"]))
        horse["image_number"] += 1
    else:
        screen.blit(horse_stand, (horse["x"], horse["y"]))
 
    if horse["image_number"] > 11:
        horse["image_number"] = 0
    
 
def start_game():
    global game_over, clock, screen
    global grass
    global bee, another_monster
    
    bee = create_bee()
    another_monster = create_another_monster()
 
    while not game_over:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                game_over = True
                pg.quit()
                return
        
        keys = pg.key.get_pressed()
        if keys[pg.K_ESCAPE]:
            game_over = True
            pg.quit()
            return
        
        screen.blit(grass, (0, 0))
        
        draw_another_monster()
        draw_another_horse()
        draw_horse()
        draw_bee()
        draw_monster()
        
        pg.display.update()
        clock.tick(60)
 
start_game()
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
08.05.2021, 18:51
Ответы с готовыми решениями:

Появляется ошибка "TypeError: 'NoneType' object is not subscriptable'
Проблема в том, что при вводе в &quot;UserName&quot;, не того ника как в базе данных появляется ошибка и программа вылетает.Если надо могу скинуть...

TypeError: 'NoneType' object is not iterable
Здравствуйте уважаемые программисты и знатоки. Есть сама программа &quot;Калькулятор валютных свопов&quot; в которой подключен модуль Mt5. При...

TypeError: 'NoneType' object is not subscriptable
Доброго времени суток! При выполнении : 1. | import cv2 2. | import face_recognition 3. | video_capture =...

4
Супер-модератор
Эксперт функциональных языков программированияЭксперт Python
 Аватар для Catstail
38171 / 21106 / 4307
Регистрация: 12.02.2012
Сообщений: 34,701
Записей в блоге: 14
08.05.2021, 19:09
Цитата Сообщение от hahahahahahah Посмотреть сообщение
Где я допустил ошибку?
- лучше скажи честно: сам писал этот код, или взял готовый?
0
 Аватар для Semen-Semenich
5224 / 3471 / 1173
Регистрация: 21.03.2016
Сообщений: 8,298
08.05.2021, 19:11
так выше ошибки должна быть и строка указана.
0
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7390 / 4817 / 1246
Регистрация: 30.03.2015
Сообщений: 13,667
Записей в блоге: 29
08.05.2021, 19:38
hahahahahahah, какие ж это казусы? Обычная ошибка, когда получил Нан вместо данных
0
0 / 0 / 0
Регистрация: 08.05.2021
Сообщений: 6
09.05.2021, 09:52  [ТС]
по уроку делал, это д/з

я уже решил проблему сам.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
09.05.2021, 09:52
Помогаю со студенческими работами здесь

TypeError: 'NoneType' object is not subscriptable
import sys import pygame import string import queue class game: def is_valid_value(self,char): if ( char ==...

TypeError: 'NoneType' object is not subscriptable в скрипте
Код у меня такой(писал не сам, хочется разобраться) import imaplib import email import os server = &quot;imap.gmail.com&quot; ...

Непонятные проблемы с TypeError: 'NoneType' object is not subscriptable
a = ,,,,,] def spawn(a): r=random.random() if r&lt;=0.2: a = 1 elif r&lt;=0.4: a = 1 elif r&lt;=0.6: ...

Python & REGEX: TypeError: 'NoneType' object is not subscriptable
TypeError: 'NoneType' object is not subscriptable Привет. У меня есть эта ошибка, но в строке с формулой регулярного выражения. Как я...

Ошибка "TypeError: 'NoneType' object is not subscriptable"
Добрый день всем, мусолю эту тему уже 2 день, но никак не могу разобраться. Подскажите молодому чайнику, в чем проблема Вот код: from...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Обработчик клика мыши в браузере ПК и касания экрана в браузере на мобильном устройстве
8Observer8 02.02.2026
Содержание блога Для начала пошагово создадим рабочий пример для подготовки к экспериментам в браузере ПК и в браузере мобильного устройства. Потом напишем обработчик клика мыши и обработчик. . .
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования. Часть библиотеки BedvitCOM Использованы. . .
SDL3 для Android: Загрузка PNG с альфа-каналом с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 28.01.2026
Содержание блога SDL3 имеет собственные средства для загрузки и отображения PNG-файлов с альфа-каналом и базовой работы с ними. В этой инструкции используется функция SDL_LoadPNG(), которая. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru