Форум программистов, компьютерный форум, киберфорум
Python: GUI, графика
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.81/68: Рейтинг темы: голосов - 68, средняя оценка - 4.81
 Аватар для YaTagan
4 / 3 / 2
Регистрация: 25.11.2018
Сообщений: 86

Обработать столкновение объектов

08.07.2019, 15:20. Показов 13220. Ответов 23
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Tkinter, два класса, шевелятся, надо обработать столкновение объектов этого класса. Как вычислить их координаты и удалить только столкнувшиеся?
Заранее спасибо.
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
08.07.2019, 15:20
Ответы с готовыми решениями:

Столкновение объектов
мне нужно чтобы при столкновении ( наезда ) одного прямоугольника - Man, на другой прямоугольник - Vec, прямоугольник Vec исчезал (т.е....

Столкновение двух объектов БЕЗ PYGAME
Здравствуйте! Никак не могу додуматься, надеюсь вы поможете. Можете пожалуйста написать if который будет просчитывать столкновения? ...

Как обработать столкновение?
Программисты, нужна ваша помощь, уже третий день ничего не получается. Собственно проблема - КАК СДЕЛАТЬ ЧТОБЫ ПРИ СТОЛКНОВЕНИИ ДВУХ...

23
 Аватар для YaTagan
4 / 3 / 2
Регистрация: 25.11.2018
Сообщений: 86
27.08.2019, 09:07  [ТС]
Студворк — интернет-сервис помощи студентам
Снова прошу вашей помощи: приделываю к игрушке меню, но игрок исчезает при активации игры. Не могу допереть как создать его снова?

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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
from tkinter import*
from random import*
import time
 
#Main menu
def fregat(x,y):
    fgb=t.create_polygon(x,y, x+20,y+20, x+20,y+30, x+50,y+70, x+30,y+70,
                         x+20,y+60, x+20,y+90, x-20,y+140, x-60,y+90, x-60,y+60,
                         x-70,y+70, x-90,y+70, x-60,y+30, x-60,y+20, x-40,y, fill='yellow')
    fgo=t.create_polygon(x+10,y+10, x+10,y+70, x-20,y+120, x-50,y+70, x-50,y+10,
                         x-60,y+20, x-60,y+90, x-20,y+140, x+20,y+90, x+20,y+20,
                         fill='green')
    fgb=t.create_polygon(x-10,y+10, x-10,y+30, x,y+40, x,y+60, x-10,y+70,
                         x-30,y+70, x-40,y+60, x-40,y+40, x-30,y+30, x-30,y+10,
                         fill='green')
 
def player(x,y):
    pw1=t.create_polygon(x+10,y+10, x+20,y+20, x+20,y+30, x+10,y+30, fill='red')
    pw2=t.create_polygon(x,y+10, x-10,y+20, x-10,y+30, x,y+30, fill='red')
    pt1=t.create_rectangle(x+20,y+10, x+30,y+40, fill='white', outline='white')
    pt2=t.create_rectangle(x-10,y+10, x-20,y+40, fill='white', outline='white')
    pb=t.create_rectangle(x,y, x+10,y+50, fill='white', outline='white')
 
def fighter(x,y):
    fb1=t.create_rectangle(x,y, x-10,y+30, fill='yellow', outline='yellow')
    fb2=t.create_rectangle(x+10,y, x+20,y+30, fill='green', outline='green')
    fb3=t.create_rectangle(x,y+20, x+10,y+40, fill='green', outline='green')
    fw1=t.create_polygon(x+20,y+30, x+30,y+40, x+30,y+60, x+20,y+60,
                         x+10,y+50, x+10,y+20, fill='green')
    fw2=t.create_polygon(x-10,y+30, x-20,y+40, x-20,y+60, x-10,y+60,
                         x,y+50, x,y+20, fill='green')
 
def mainMenu():
    global start, tut, bes
    fregat(150, 260)
    t.create_text(400,60, anchor='center', font='segoePrint 60',  text='Галлага',
                  fill='white')
    
    start=Button(t, width=10, height=2, font='segoe 15', text='Начать игру',
                command=begin)
    tut=Button(t, width=10, height=2, font='segoe 15', text='Как играть?',
               command=tutorial)
    bes=Button(t, width=10, height=2, font='segoe 15', text='Бестиарий')
    
    start.place(x=350, y=180)
    tut.place(x=350, y=260)
    bes.place(x=350, y=340)
 
def begin():
    global l1,l2,l3,l4,l5,b1
    
    tut.destroy()
    start.destroy()
    bes.destroy()
 
    l1=Button(t, width=15, height=2, font='segoe 15', text='Фрегат \n"Атлас"', command=game)
    l2=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    l3=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    l4=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    l5=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    b1=Button(t, width=15, height=2, font='sd 15', text='Назад', command=back1)
    
    l1.place(x=340, y=120)
    l2.place(x=340, y=200)
    l3.place(x=340, y=280)
    l4.place(x=340, y=360)
    l5.place(x=340, y=440)
    b1.place(x=340, y=520)
 
def tutorial():
    global b2
    tut.destroy()
    start.destroy()
    bes.destroy()
    t.delete('all')
 
    t.create_text(400,60, anchor='center', font='segoePrint 60',  text='Обучение',
                  fill='white')
    t.create_text(120,140, font='ggg 15', text='Вы будете играть за ', fill='white')
    t.create_text(190,200, font='ggg 15', text='Управление движением на стрелках ',
                  fill='white')
    t.create_text(170,240, font='ggg 15', text='Выстрел на левую кнопку мыши ',
                  fill='white')
    t.create_text(232,280, font='ggg 15', text='Прорвитесь к слабому месту крупного кораля',
                 fill='white')
    t.create_text(250,320, font='ggg 15', text='Не забывайте про рой меньших кораблей на пути',
                 fill='white')
    t.create_text(259,360, font='ggg 15', text='Но помните, главное - повредить крупный корабль',
                 fill='white')
    player(240, 120)
    b2=Button(t, width=67, height=2, font='sd 15', text='Назад', command=back2)
    b2.place(x=25, y=520)
 
def bestiarii():
    pass
 
def back1():
    l1.destroy()
    l2.destroy()
    l3.destroy()
    l4.destroy()
    l5.destroy()
    b1.destroy()
 
    mainMenu()
 
def back2():
    t.delete('all')
    b2.destroy()
 
    mainMenu()
    
def game():
    global t
    gamer = player()
    l1.destroy()
    l2.destroy()
    l3.destroy()
    l4.destroy()
    l5.destroy()
    b1.destroy()
    t.delete('all')
    players.append(gamer)
    gamer.draw()
    peremennie()
    game_loop()
    wave()
    t.configure(bg='white')
    players.append(gamer)
    
t=Canvas(width=800, height=600, bg='navy')
 
#player
def contact(rect, point):
    if point[0] > rect[0] and point[0] < (rect[0] + rect[2]) and point[1] > rect[1] and point[1] < (rect[1] + rect[3]):
        return True
    return False
 
def Gover(ply, over):
    if over[0] > ply[0] and over[0] < (ply[0] + ply[2]) and over[1] > ply[1] and over[1] < (ply[1] + ply[3]):
        return True
    return False
 
class player:
    def __init__ (self):
        global gun, boss
        self._x=350
        self._y=550
        self._avatar=t.create_rectangle(self._x, self._y, self._x+30, self._y+30)
 
        gun=367
 
        self._v=7
 
        self._active = True
 
    def ml(self):
        global gun
        if self._x<780:
            self._x+=self._v
            gun+=self._v
 
    def mp(self):
        global gun
        if self._y>20:
            self._x-=self._v
            gun-=self._v
 
    def ply(self):
        return self._x, self._y, 30, 30
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x+30, self._y+30)
 
    def set_dead(self):
        global game, boss
        t.delete('all')
        bullets.clear()
        Ebullets.clear()
        players.clear()
        enemies.clear()
        game=False
        boss=False
 
    def is_alive(self):
        return self._active
 
class bullet:
    def __init__ (self):
        self._x=gun
        self._avatar=t.create_line(gun,790, gun,785, width=3)
        self._y=550
        self._v=20
        self._active = True
 
    def update(self):
        self._y-=self._v
        if self._y < -10:
            self._active = False
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x, self._y+8)
 
    def point(self):
        return self._x, self._y
 
    def set_dead(self):
        self._active = False
        self._x = -100
        self._y = -100
        self._vx=0
        self._vy=0
 
    def is_alive(self):
        return self._active
 
bullets = []
 
def fire(e):
    global heal, boss
    bullets.append(bullet())
    if boss==True:
        heal-=5
        print(heal)
    if heal<0:
        t.after(300, bossDed)
 
#enemy
class fighter:
    def __init__ (self):
        global egx, egy
        self._x=300
        self._y=0
        self._avatar=t.create_rectangle(self._x, self._y, self._x+30, self._y+30)
 
        self._vx=randint(-8,8)
        self._vy=randint(1,5)
        
        egx=0
        egy=0
 
        self.counter = 0
 
        self._active = True
 
    def update(self):
        self._x+=self._vx
        self._y+=self._vy
        egx=self._x
        egy=self._y
        if self._x>780 or self._x<20:
           self._vx=-self._vx
 
        self.counter += 1
        if self.counter > 50:
            self.attack()
            self.counter = 0
 
    def rect(self):
        return self._x, self._y, 30, 30
 
    def co(self):
        global cx, cy
        if game==True:
           cx=self._x
           cy=self._y
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x+30, self._y+30)
 
    def set_dead(self):
        self._x = -100
        self._y = -100
        self._vx=0
        self._vy=0
        self._active = False
 
    def is_alive(self):
        return self._active
 
    def attack(self):
        pass
        #Ebullets.append(Ebullet(self._x, self._y))
            
 
class Ebullet:
    def __init__ (self, egx, egy):
        self._x=egx
        self._avatar=t.create_line(egx,egy, egx,egy, width=3)
        self._y=egy
        self._v=-20
        self._active = True
 
    def update(self):
        self._y-=self._v
        if self._y > 610:
            self._active = False
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x, self._y+8)
 
    def over(self):
        return self._x, self._y
 
    def set_dead(self):
        self._active = False
        self._x = -100
        self._y = -100
        self._vx=0
        self._vy=0
 
    def is_alive(self):
        return self._active
 
Ebullets=[]
 
root=Tk()
root.geometry('800x600')
root.resizable(False, False)
 
enemy = fighter()
gamer = player()
  
players = []
enemies = []
 
def wave():
    global z, bs
    if game==True:
        enemies.extend([fighter() for i in range(z)])
        z+=1
    if z<11:
        t.after(50, wave)
    else:
        bs=t.create_polygon(0,-200, 400,0, 800,-200)
        bossMov()
 
def bossMov():
    global bs, b, boss
    t.move(bs, 0, 1)
    b+=1
    if b<200:
        t.after(25, bossMov)
    else:
        boss=True
        bossAtt()
        print('profit')
 
def bossAtt():
    global boss
    bbb=randint(3, 7)
    for i in range (bbb):
        bx=randint(10, 590)
        Ebullets.append(Ebullet(bx, 0))
    if boss==True:
        t.after(100, bossAtt)
 
def bossDed():
    boss=False
    t.delete('all')
    bullets.clear()
    Ebullets.clear()
    players.clear()
    enemies.clear()
    game=False
    
def update():
    for enemy in enemies:
        enemy.update()
 
    for bullet in bullets[::-1]:
        bullet.update()
 
    for Ebullet in Ebullets[::-1]:
        Ebullet.update()
 
    for bullet in bullets:
        for enemy in enemies:
            if contact(enemy.rect(), bullet.point()):
                bullet.set_dead()
                enemy.set_dead()
 
    for Ebullet in Ebullets:
        for gamer in players:
            if Gover(gamer.ply(), Ebullet.over()):
                Ebullet.set_dead()
                gamer.set_dead()
            
def draw():
    for enemy in enemies:
        enemy.draw()
 
    for gamer in players:
        gamer.draw()
 
    for bullet in bullets:
        bullet.draw()
 
    for Ebullet in Ebullets:
        Ebullet.draw()
 
def game_loop():
    update()
    draw()
    enemy.co()
    t.after(25, game_loop)
 
def MoveRight(e):
    gamer.mp()
 
def MoveLeft(e):
    gamer.ml()
 
def peremennie():
    global boss, heal, game, gun, b, z
    heal=100
    b=1
    z=1
    gun=400
    game=True
    boss=False
 
t.bind('<Left>', MoveRight)
t.bind('<Right>', MoveLeft)
t.bind('<Up>', fire)
 
t.focus_set()
t.pack()
 
mainMenu()
 
root.mainloop()
0
1293 / 677 / 367
Регистрация: 07.01.2019
Сообщений: 2,300
27.08.2019, 09:56
Цитата Сообщение от YaTagan Посмотреть сообщение
игрок исчезает при активации игры
В функции game вы сначала создаете игрока, а затем вызываете
Python
1
 t.delete('all')
и очищаете весь канвас и еще у вас переменная gamer локальная, сделайте ее глобальной
0
 Аватар для YaTagan
4 / 3 / 2
Регистрация: 25.11.2018
Сообщений: 86
27.08.2019, 11:43  [ТС]
Снова прошу вашей помощи: приделываю к игрушке меню, но игрок исчезает при активации игры. Не могу допереть как создать его снова?

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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
from tkinter import*
from random import*
import time
 
#Main menu
def fregat(x,y):
    fgb=t.create_polygon(x,y, x+20,y+20, x+20,y+30, x+50,y+70, x+30,y+70,
                         x+20,y+60, x+20,y+90, x-20,y+140, x-60,y+90, x-60,y+60,
                         x-70,y+70, x-90,y+70, x-60,y+30, x-60,y+20, x-40,y, fill='yellow')
    fgo=t.create_polygon(x+10,y+10, x+10,y+70, x-20,y+120, x-50,y+70, x-50,y+10,
                         x-60,y+20, x-60,y+90, x-20,y+140, x+20,y+90, x+20,y+20,
                         fill='green')
    fgb=t.create_polygon(x-10,y+10, x-10,y+30, x,y+40, x,y+60, x-10,y+70,
                         x-30,y+70, x-40,y+60, x-40,y+40, x-30,y+30, x-30,y+10,
                         fill='green')
 
def player(x,y):
    pw1=t.create_polygon(x+10,y+10, x+20,y+20, x+20,y+30, x+10,y+30, fill='red')
    pw2=t.create_polygon(x,y+10, x-10,y+20, x-10,y+30, x,y+30, fill='red')
    pt1=t.create_rectangle(x+20,y+10, x+30,y+40, fill='white', outline='white')
    pt2=t.create_rectangle(x-10,y+10, x-20,y+40, fill='white', outline='white')
    pb=t.create_rectangle(x,y, x+10,y+50, fill='white', outline='white')
 
def fighter(x,y):
    fb1=t.create_rectangle(x,y, x-10,y+30, fill='yellow', outline='yellow')
    fb2=t.create_rectangle(x+10,y, x+20,y+30, fill='green', outline='green')
    fb3=t.create_rectangle(x,y+20, x+10,y+40, fill='green', outline='green')
    fw1=t.create_polygon(x+20,y+30, x+30,y+40, x+30,y+60, x+20,y+60,
                         x+10,y+50, x+10,y+20, fill='green')
    fw2=t.create_polygon(x-10,y+30, x-20,y+40, x-20,y+60, x-10,y+60,
                         x,y+50, x,y+20, fill='green')
 
def mainMenu():
    global start, tut, bes
    fregat(150, 260)
    t.create_text(400,60, anchor='center', font='segoePrint 60',  text='Галлага',
                  fill='white')
    
    start=Button(t, width=10, height=2, font='segoe 15', text='Начать игру',
                command=begin)
    tut=Button(t, width=10, height=2, font='segoe 15', text='Как играть?',
               command=tutorial)
    bes=Button(t, width=10, height=2, font='segoe 15', text='Бестиарий')
    
    start.place(x=350, y=180)
    tut.place(x=350, y=260)
    bes.place(x=350, y=340)
 
def begin():
    global l1,l2,l3,l4,l5,b1
    
    tut.destroy()
    start.destroy()
    bes.destroy()
 
    l1=Button(t, width=15, height=2, font='segoe 15', text='Фрегат \n"Атлас"', command=game)
    l2=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    l3=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    l4=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    l5=Button(t, width=15, height=2, font='segoe 15', text='Скоро')
    b1=Button(t, width=15, height=2, font='sd 15', text='Назад', command=back1)
    
    l1.place(x=340, y=120)
    l2.place(x=340, y=200)
    l3.place(x=340, y=280)
    l4.place(x=340, y=360)
    l5.place(x=340, y=440)
    b1.place(x=340, y=520)
 
def tutorial():
    global b2
    tut.destroy()
    start.destroy()
    bes.destroy()
    t.delete('all')
 
    t.create_text(400,60, anchor='center', font='segoePrint 60',  text='Обучение',
                  fill='white')
    t.create_text(120,140, font='ggg 15', text='Вы будете играть за ', fill='white')
    t.create_text(190,200, font='ggg 15', text='Управление движением на стрелках ',
                  fill='white')
    t.create_text(170,240, font='ggg 15', text='Выстрел на левую кнопку мыши ',
                  fill='white')
    t.create_text(232,280, font='ggg 15', text='Прорвитесь к слабому месту крупного кораля',
                 fill='white')
    t.create_text(250,320, font='ggg 15', text='Не забывайте про рой меньших кораблей на пути',
                 fill='white')
    t.create_text(259,360, font='ggg 15', text='Но помните, главное - повредить крупный корабль',
                 fill='white')
    player(240, 120)
    b2=Button(t, width=67, height=2, font='sd 15', text='Назад', command=back2)
    b2.place(x=25, y=520)
 
def bestiarii():
    pass
 
def back1():
    l1.destroy()
    l2.destroy()
    l3.destroy()
    l4.destroy()
    l5.destroy()
    b1.destroy()
 
    mainMenu()
 
def back2():
    t.delete('all')
    b2.destroy()
 
    mainMenu()
    
def game():
    global t
    gamer = player()
    l1.destroy()
    l2.destroy()
    l3.destroy()
    l4.destroy()
    l5.destroy()
    b1.destroy()
    t.delete('all')
    players.append(gamer)
    gamer.draw()
    peremennie()
    game_loop()
    wave()
    t.configure(bg='white')
    players.append(gamer)
    
t=Canvas(width=800, height=600, bg='navy')
 
#player
def contact(rect, point):
    if point[0] > rect[0] and point[0] < (rect[0] + rect[2]) and point[1] > rect[1] and point[1] < (rect[1] + rect[3]):
        return True
    return False
 
def Gover(ply, over):
    if over[0] > ply[0] and over[0] < (ply[0] + ply[2]) and over[1] > ply[1] and over[1] < (ply[1] + ply[3]):
        return True
    return False
 
class player:
    def __init__ (self):
        global gun, boss
        self._x=350
        self._y=550
        self._avatar=t.create_rectangle(self._x, self._y, self._x+30, self._y+30)
 
        gun=367
 
        self._v=7
 
        self._active = True
 
    def ml(self):
        global gun
        if self._x<780:
            self._x+=self._v
            gun+=self._v
 
    def mp(self):
        global gun
        if self._y>20:
            self._x-=self._v
            gun-=self._v
 
    def ply(self):
        return self._x, self._y, 30, 30
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x+30, self._y+30)
 
    def set_dead(self):
        global game, boss
        t.delete('all')
        bullets.clear()
        Ebullets.clear()
        players.clear()
        enemies.clear()
        game=False
        boss=False
 
    def is_alive(self):
        return self._active
 
class bullet:
    def __init__ (self):
        self._x=gun
        self._avatar=t.create_line(gun,790, gun,785, width=3)
        self._y=550
        self._v=20
        self._active = True
 
    def update(self):
        self._y-=self._v
        if self._y < -10:
            self._active = False
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x, self._y+8)
 
    def point(self):
        return self._x, self._y
 
    def set_dead(self):
        self._active = False
        self._x = -100
        self._y = -100
        self._vx=0
        self._vy=0
 
    def is_alive(self):
        return self._active
 
bullets = []
 
def fire(e):
    global heal, boss
    bullets.append(bullet())
    if boss==True:
        heal-=5
        print(heal)
    if heal<0:
        t.after(300, bossDed)
 
#enemy
class fighter:
    def __init__ (self):
        global egx, egy
        self._x=300
        self._y=0
        self._avatar=t.create_rectangle(self._x, self._y, self._x+30, self._y+30)
 
        self._vx=randint(-8,8)
        self._vy=randint(1,5)
        
        egx=0
        egy=0
 
        self.counter = 0
 
        self._active = True
 
    def update(self):
        self._x+=self._vx
        self._y+=self._vy
        egx=self._x
        egy=self._y
        if self._x>780 or self._x<20:
           self._vx=-self._vx
 
        self.counter += 1
        if self.counter > 50:
            self.attack()
            self.counter = 0
 
    def rect(self):
        return self._x, self._y, 30, 30
 
    def co(self):
        global cx, cy
        if game==True:
           cx=self._x
           cy=self._y
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x+30, self._y+30)
 
    def set_dead(self):
        self._x = -100
        self._y = -100
        self._vx=0
        self._vy=0
        self._active = False
 
    def is_alive(self):
        return self._active
 
    def attack(self):
        pass
        #Ebullets.append(Ebullet(self._x, self._y))
            
 
class Ebullet:
    def __init__ (self, egx, egy):
        self._x=egx
        self._avatar=t.create_line(egx,egy, egx,egy, width=3)
        self._y=egy
        self._v=-20
        self._active = True
 
    def update(self):
        self._y-=self._v
        if self._y > 610:
            self._active = False
 
    def draw(self):
        t.coords(self._avatar, self._x, self._y, self._x, self._y+8)
 
    def over(self):
        return self._x, self._y
 
    def set_dead(self):
        self._active = False
        self._x = -100
        self._y = -100
        self._vx=0
        self._vy=0
 
    def is_alive(self):
        return self._active
 
Ebullets=[]
 
root=Tk()
root.geometry('800x600')
root.resizable(False, False)
 
enemy = fighter()
gamer = player()
  
players = []
enemies = []
 
def wave():
    global z, bs
    if game==True:
        enemies.extend([fighter() for i in range(z)])
        z+=1
    if z<11:
        t.after(50, wave)
    else:
        bs=t.create_polygon(0,-200, 400,0, 800,-200)
        bossMov()
 
def bossMov():
    global bs, b, boss
    t.move(bs, 0, 1)
    b+=1
    if b<200:
        t.after(25, bossMov)
    else:
        boss=True
        bossAtt()
        print('profit')
 
def bossAtt():
    global boss
    bbb=randint(3, 7)
    for i in range (bbb):
        bx=randint(10, 590)
        Ebullets.append(Ebullet(bx, 0))
    if boss==True:
        t.after(100, bossAtt)
 
def bossDed():
    boss=False
    t.delete('all')
    bullets.clear()
    Ebullets.clear()
    players.clear()
    enemies.clear()
    game=False
    
def update():
    for enemy in enemies:
        enemy.update()
 
    for bullet in bullets[::-1]:
        bullet.update()
 
    for Ebullet in Ebullets[::-1]:
        Ebullet.update()
 
    for bullet in bullets:
        for enemy in enemies:
            if contact(enemy.rect(), bullet.point()):
                bullet.set_dead()
                enemy.set_dead()
 
    for Ebullet in Ebullets:
        for gamer in players:
            if Gover(gamer.ply(), Ebullet.over()):
                Ebullet.set_dead()
                gamer.set_dead()
            
def draw():
    for enemy in enemies:
        enemy.draw()
 
    for gamer in players:
        gamer.draw()
 
    for bullet in bullets:
        bullet.draw()
 
    for Ebullet in Ebullets:
        Ebullet.draw()
 
def game_loop():
    update()
    draw()
    enemy.co()
    t.after(25, game_loop)
 
def MoveRight(e):
    gamer.mp()
 
def MoveLeft(e):
    gamer.ml()
 
def peremennie():
    global boss, heal, game, gun, b, z
    heal=100
    b=1
    z=1
    gun=400
    game=True
    boss=False
 
t.bind('<Left>', MoveRight)
t.bind('<Right>', MoveLeft)
t.bind('<Up>', fire)
 
t.focus_set()
t.pack()
 
mainMenu()
 
root.mainloop()
0
1293 / 677 / 367
Регистрация: 07.01.2019
Сообщений: 2,300
27.08.2019, 13:02
Лучший ответ Сообщение было отмечено YaTagan как решение

Решение

Python
1
2
3
4
5
6
7
8
9
    global t, gamer
    l1.destroy()
    l2.destroy()
    l3.destroy()
    l4.destroy()
    l5.destroy()
    b1.destroy()
    t.delete('all')
    gamer = player()
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
27.08.2019, 13:02
Помогаю со студенческими работами здесь

Арканоид в консоли.Не получается обработать столкновение с блоком
Доброго времени суток.Каким образом можно обработать столкновение с блоком? Код : #include &quot;stdafx.h&quot; #include...

Столкновение 2D объектов
Делаю игру -арканоид, и сталкнулся с такой проблемой, когда шарик сталкивается с правой или левой стороной ракетки(пратформы), он(шарик)...

Столкновение объектов
Нужна помощь по столкновению. Нашол код столкновения в инете, и вставил в свой код. Столкновение работает как бы, но если два препядствия...

Столкновение объектов в AS 3.0
Здравствуйте! Вопрос, конечно уже не новый, но хотелось бы получить совет в каком направлении двигаться дальше:) Я хочу настроить объект...

Столкновение объектов
Здравствуйте. Подскажите, пожалуйста, как сделать столкновение объектов. У меня на сцене генерируется много объектов. Главный герой должен...


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

Или воспользуйтесь поиском по форуму:
24
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru