Прикреплённый файл «2013-11-29-balls.py»
Загрузка 1 #!/usr/bin/env python
2 # coding: utf
3 '''
4 Прыгающие шарики. В прямоугольной комнате прыгают два шарика.
5
6 так же, как в базовом примере (просто ударяясь о стены)
7 с учётом силы тяжести
8 шарики можно ловить мышью (тогда пойманный шарик не движется)
9 …и перетаскивать
10 с учётом соударений друг о друга (вспоминаем физику)
11 '''
12
13 import sys, pygame
14 from math import *
15
16 def qlength(start, end): return (start[0]-end[0])**2+(start[1]-end[1])**2
17
18 pygame.init()
19
20 size = width, height = 1000,800
21 screen = pygame.display.set_mode(size)
22 back = pygame.Color("midnightblue")
23
24 ball_1 = pygame.image.load("ball.gif")
25 ball_2 = pygame.transform.rotozoom(ball_1, 90, 0.5)
26
27 ball_2_mask = pygame.mask.from_surface(ball_2)
28 ball_1_mask = pygame.mask.from_surface(ball_1)
29
30 ball_1_rect = ball_1.get_rect()
31 ball_2_rect = ball_2.get_rect()
32
33 ball_1_speed = [0.5, 0.]
34 ball_2_speed = [-1., 0.]
35
36 ball_1_pos = (screen.get_rect().centerx*0.5,screen.get_rect().centery*1.5)
37 ball_2_pos = (screen.get_rect().centerx*1.5,screen.get_rect().centery*0.5)
38
39 G=0.2
40
41 def Move(pos, speed, rect):
42 '''Подвинуть прямоугольник rect со скоростью speed
43 с учётом границ и силы тяжести'''
44 speed[1]+=G
45 x,y = pos[0]+speed[0], pos[1]+speed[1]
46 if not rect.width/2<x<width-rect.width/2: speed[0]=-speed[0]
47 if not rect.height/2<y<height-rect.height/2: speed[1]=-speed[1]
48 return x+speed[0], y+speed[1]
49
50 def Overlap(pos1, rect1, mask1, pos2, rect2, mask2):
51 r1, r2 = rect1.copy(), rect2.copy()
52 r1.center, r2.center = pos1, pos2
53 return r1.colliderect(r2) and mask1.overlap(mask2, (r2.left-r1.left, r2.top-r1.top))
54
55 def Interact(pos1, speed1, pos2, speed2):
56 print pos1, speed1, pos2, speed2
57 return pos1, pos2
58
59 def Recalc():
60 '''Пересчёт игрового пространства'''
61 global ball_1_pos, ball_2_pos
62 if moved != ball_1:
63 ball_1_pos=Move(ball_1_pos, ball_1_speed, ball_1_rect)
64 if moved != ball_2:
65 ball_2_pos=Move(ball_2_pos, ball_2_speed, ball_2_rect)
66 if Overlap(ball_1_pos, ball_1_rect, ball_1_mask, ball_2_pos, ball_2_rect, ball_2_mask):
67 ball_1_pos, ball_2_pos = Interact(ball_1_pos, ball_1_speed, ball_2_pos, ball_2_speed)
68
69 def Redraw():
70 '''Отображение игрового пространства'''
71 ball_1_rect.center=(int(ball_1_pos[0]),int(ball_1_pos[1]))
72 ball_2_rect.center=(int(ball_2_pos[0]),int(ball_2_pos[1]))
73 screen.fill(back)
74 screen.blit(ball_1, ball_1_rect)
75 screen.blit(ball_2, ball_2_rect)
76
77 debug,again,redraw,recalc=False,True,True,True
78 moved = None
79 pygame.time.set_timer(pygame.USEREVENT, 50)
80 while again:
81 # Какие события пришли (минимум одно)?
82 for event in [pygame.event.wait()]+pygame.event.get():
83 if event.type == pygame.QUIT:
84 again = False
85 # Смена игрового времени
86 elif event.type == pygame.USEREVENT:
87 recalc = True
88 elif event.type == pygame.MOUSEBUTTONDOWN:
89 if ball_1_rect.collidepoint(event.pos):
90 moved = ball_1
91 elif ball_2_rect.collidepoint(event.pos):
92 moved = ball_2
93 else:
94 moved = None
95 elif event.type == pygame.MOUSEMOTION:
96 if event.buttons[0]:
97 if moved == ball_1:
98 ball_1_pos = event.pos
99 elif moved == ball_2:
100 ball_2_pos = event.pos
101 redraw = True
102 else:
103 moved = None
104 elif event.type == pygame.MOUSEBUTTONUP:
105 moved = None
106
107 # Взаимодействие объектов
108 if recalc:
109 Recalc()
110 redraw, recalc = True, False
111 # Обновление картинки
112 if redraw:
113 Redraw()
114 redraw = False
115 pygame.display.flip()
116 pygame.quit()
Прикреплённые файлы
Для ссылки на прикреплённый файл в тексте страницы напишите attachment:имяфайла, как показано ниже в списке файлов. Не используйте URL из ссылки «[получить]», так как он чисто внутренний и может измениться.- [получить | показать] (2013-12-06 14:13:23, 4.0 KB) [[attachment:2013-11-29-balls.py]]
- [получить | показать] (2013-12-07 08:45:07, 4.8 KB) [[attachment:2013-11-29-polynom.py]]
- [получить | показать] (2013-12-04 21:12:18, 5.4 KB) [[attachment:2013-11-29-smartbowling.py]]
- [получить | показать] (2013-12-05 14:02:56, 11.3 KB) [[attachment:bowling.png]]
- [получить | показать] (2013-12-05 14:02:51, 1.0 KB) [[attachment:bowling.seg]]
Вам нельзя прикреплять файлы к этой странице.