def handle(self, event):
if event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:
self.on_mouse_over()
pos = [event.pos[0] - self.mainloop.game_board.layout.score_bar_pos[0], event.pos[1]]
for each in self.elements:
if each.rect.topleft[0] + each.rect.width >= pos[0] >= each.rect.topleft[0] and each.rect.topleft[
1] + each.rect.height >= pos[1] >= each.rect.topleft[1]:
each.handle(event)
else:
pass
python类MOUSEMOTION的实例源码
def toggle_select(self):
if not self.menu.ldrag:
if self.selected:
self.hide_icons()
self.play_sound(6)
pygame.event.post(
pygame.event.Event(pygame.MOUSEMOTION,
{"pos": pygame.mouse.get_pos(), "rel": None, "buttons": None}))
else:
self.show_icons()
self.play_sound(5)
self.menu.update_panel_height()
def touch_handler(self, event):
action = None
if event.type == pygame.MOUSEBUTTONDOWN:
action = "down"
elif event.type == pygame.MOUSEMOTION:
action = "move"
elif event.type == pygame.MOUSEBUTTONUP:
action = "up"
pos = pygame.mouse.get_pos()
pos = tingbot.graphics._xy_subtract(pos, self.surface.get_abs_offset())
self.on_touch(pos, action)
def dispatch(self, player, shutdown):
""" Dispatch events.
Runs the main event loop. Redirects events to corresponding handler.
Distinguishes four types of events:
- Quit event - when user closes window (Windows only)
- Keyboard events
- Mouse events
- User Events
:param player: reference to player object
"param shutdown: shutdown method to use when user exits
"""
self.player = player
self.shutdown = shutdown
mouse_events = [pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP, pygame.MOUSEMOTION]
pygame.event.clear()
clock = Clock()
while self.run_dispatcher:
for event in pygame.event.get():
s = str(event)
logging.debug("Received event: %s", s)
if event.type == pygame.QUIT:
self.shutdown(event)
elif (event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and not self.config[USAGE][USE_LIRC]:
self.handle_keyboard_event(event)
elif event.type in mouse_events or event.type == USER_EVENT_TYPE:
self.handle_event(event)
if self.lirc != None:
code = self.lirc.nextcode()
if code != None:
self.handle_lirc_event(code)
self.current_screen.refresh()
self.screensaver_dispatcher.refresh()
clock.tick(self.frame_rate)
def event_loop(self):
for event in pg.event.get():
self.keys = pg.key.get_pressed()
if event.type == pg.QUIT or self.keys[pg.K_ESCAPE]:
self.done = True
self.closed = True
elif event.type == pg.KEYDOWN and self.keys[pg.K_i]:
# import pdb
# pdb.set_trace()
print 'Player at: '
print self.player.rect
print self.player.rect.x
print self.player.rect.y
print 'Camera at: '
print self.camera.state
print 'Painting at: '
print [(self.mouse[0], self.mouse[1]), (self.player.rect.centerx + abs(self.camera.state.x), self.player.rect.centery + abs(self.camera.state.y))]
print 'Angle:'
print self.angle
elif event.type == pg.KEYDOWN:
self.player.add_direction(event.key)
elif event.type == pg.KEYUP:
self.player.pop_direction(event.key)
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
if self.player.bullets_left > 0 and self.player.weapon:
self.player_bullets.add(Bullet(self.player.rect.center, self.angle))
self.player.bullets_left -= 1
elif event.type == pg.MOUSEMOTION:
self.get_angle(event.pos)
def __init__(self):
self.callbacks = {
pygame.KEYDOWN : self.key_state_change,
pygame.KEYUP : self.key_state_change,
pygame.MOUSEMOTION : self.mouse_motion,
pygame.MOUSEBUTTONUP : self.mouse_button_state_change,
pygame.MOUSEBUTTONDOWN : self.mouse_button_state_change,
pygame.QUIT : self.quit,
STATE_CHANGED : self.state_change,
SOUND_EFFECT : self.sound_effect,
SETTINGS_UPDATED : self.settings_updated,
SET_GAME_STATE : self.set_game_state,
MUSIC_STOPPED : self.music_stopped
}
self.key_states = defaultdict(int)
self.mouse_button_states = defaultdict(int)
self.key_listeners = []
self.state_change_listeners = []
self.sound_effect_listeners = []
self.mouse_button_listeners = []
self.settings_listeners = []
self.set_game_state_listeners = []
self.quit_listeners = []
self.game_start_listeners = []
self.music_stopped_listeners = []
pygame tetris.py 文件源码
项目:15-112-Term-Project--Tetris-God
作者: davidlizhang98
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def run(self):
screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption(self.title)
clock = pygame.time.Clock()
self._keys = dict()
self.init()
runGame = True
while runGame:
time = clock.tick(self.fps)
self.timerFired(time)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.mousePressed(*(event.pos))
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.mouseReleased(*(event.pos))
elif (event.type == pygame.MOUSEMOTION and
event.buttons == (0, 0, 0)):
self.mouseMotion(*(event.pos))
elif (event.type == pygame.MOUSEMOTION and
event.buttons[0] == 1):
self.mouseDrag(*(event.pos))
elif event.type == pygame.KEYDOWN:
self._keys[event.key] = True
self.keyPressed(event.key, event.mod, screen)
elif event.type == pygame.QUIT:
runGame = False
screen.fill(self.bgColor)
self.redrawAll(screen)
pygame.display.flip()
if (self.isGameOver == True):
return self.score
runGame = False
if (self.score > self.lineCap):
return self.score
runGame = False
pygame.quit()
pygame tetris.py 文件源码
项目:15-112-Term-Project--Tetris-God
作者: davidlizhang98
项目源码
文件源码
阅读 38
收藏 0
点赞 0
评论 0
def run(width = 800, height = 600, fps = 60, title = "Tetris"):
class Struct(object): pass
data = Struct()
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption(title)
clock = pygame.time.Clock()
init(data)
backgroundColor = (255,255,255)
runGame = True
while (runGame == True):
time = clock.tick(fps)
timerFired(time, data)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mousePressed(data, *(event.pos))
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
mouseReleased(data, *(event.pos))
elif (event.type == pygame.MOUSEMOTION and
event.buttons == (0, 0, 0)):
mouseMotion(data, *(event.pos))
elif (event.type == pygame.MOUSEMOTION and
event.buttons[0] == 1):
mouseDrag(data, *(event.pos))
elif event.type == pygame.KEYDOWN:
keyPressed(event.key, event.mod, screen, data)
elif event.type == pygame.QUIT:
runGame = False
screen.fill(backgroundColor)
redrawAll(screen, data)
pygame.display.flip()
pygame.quit()
###########################################
# Mode Dispatcher
###########################################
def update(self, *args):
"""
Handles the clicking of the Button and calls the function given in the constructor.
parameters: tuple arguments for the update (first argument should be an instance pygame.event.Event)
return values: -
"""
if self._state:
if self._state >= 2:
self._state = 1
else:
self._state = 0
self.markDirty()
if len(args) > 0 and self.isActive():
event = args[0]
if event.type == pygame.MOUSEBUTTONUP:
if self.rect.collidepoint(event.pos):
if event.button == 1:
try:
self._callback()
except:
pass
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
if event.button == 1:
self._state = 2
else:
self._state = 1
self.markDirty()
elif event.type == pygame.MOUSEMOTION:
if self.rect.collidepoint(event.pos):
if event.buttons[0]:
self._state = 2
else:
self._state = 1
self.markDirty()
super(Button, self).update(*args)
def update(self, *args):
"""
Handles the selection and keyboard-input
parameters: tuple arguments for the update (first argument should be an instance pygame.event.Event)
return values: -
"""
if len(args) > 0 and self.isActive():
event = args[0]
if event.type == pygame.KEYDOWN and self.isFocused():
if event.key == pygame.K_LEFT:
self.moveCursor(-1)
elif event.key == pygame.K_RIGHT:
self.moveCursor(1)
elif event.key == pygame.K_BACKSPACE or event.key == pygame.K_DELETE:
if self._selection == self._cursor:
if event.key == pygame.K_DELETE:
self.delete(self._selection + 1, CURSOR)
else:
self.delete(self._selection - 1, CURSOR)
self.moveCursor(-1)
else:
self.delete(SELECTION, CURSOR)
self.setCursor(self._sort(SELECTION, CURSOR)[0])
else:
char = event.unicode.encode("ascii", "ignore")
if (char != "" and (char == " " or not char.isspace())
and self._validation(self._text + char, self._text, self)):
self.delete(SELECTION, CURSOR)
s = self._sort(SELECTION, CURSOR)[0]
self.insert(s, char)
self.setCursor(s + 1)
elif event.type == pygame.MOUSEMOTION:
if self.rect.collidepoint(event.pos) and event.buttons[0]:
self.setSelection(SELECTION, self._posToIndex(event.pos[0] - self.rect.x))
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.setCursor(self._posToIndex(event.pos[0] - self.rect.x))
super(Entry, self).update(*args)
def from_pygame_event(cls, event):
if event.type == pygame.MOUSEMOTION:
return MouseMotion(event.pos, event.rel)
def check(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
State.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
self.events.append(GUI.LongClickEvent(event))
if event.type == pygame.MOUSEMOTION and len(self.events) > 0 and isinstance(self.events[len(self.events)-1], GUI.LongClickEvent):
self.events[len(self.events)-1].intermediateUpdate(event)
if event.type == pygame.MOUSEBUTTONUP and len(self.events) > 0 and isinstance(self.events[len(self.events)-1], GUI.LongClickEvent):
self.events[len(self.events)-1].end(event)
if not self.events[len(self.events)-1].checkValidLongClick():
self.events[len(self.events)-1] = self.events[len(self.events)-1].mouseUp
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.exit()
if hasattr(event, "pos"):
ix, iy = event.pos
self.mouse_inmenu = ix <= self.size[1] * MENU_BORDER / 100.0
fx = min(max(0, (ix - self.proj[0]) / float(self.proj[2])), 1)
fy = min(max(0, (iy - self.proj[1]) / float(self.proj[3])), 1)
if self.rotation == 0:
x = fx
y = fy
if self.rotation == 90:
x = 1.0 - fy
y = fx
if self.rotation == 180:
x = 1.0 - fx
y = 1.0 - fy
if self.rotation == 270:
x = fy
y = 1.0 - fx
if hasattr(event, "button"):
if event.button is not 1:
continue
if event.type == pygame.MOUSEBUTTONDOWN:
if ix < self.menu_w and self.show_menu:
self.menu_action(iy / (self.size[1] / 3))
elif ix > self.size[0] - self.nav_w and self.show_nav:
self.nav_action(iy / (self.size[1] / 3))
else:
self.touch.write(["down", x, y])
self.mouse_down = True
self.mouse_time = time()
if event.type == pygame.MOUSEBUTTONUP:
self.touch.write(["up"])
self.mouse_down = False
if event.type == pygame.MOUSEMOTION:
if self.mouse_down:
self.touch.write(["move", x, y])
def big_bang(inic, tela,
quando_tick=lambda e: e, \
frequencia=28, \
desenhar=lambda e: pg.Surface((0,0)), \
quando_tecla=lambda e, k: e, \
quando_solta_tecla=lambda e, k: e, \
quando_mouse=lambda e, x, y, ev: e, \
parar_quando=lambda e: False,\
modo_debug=False,
fonte_debug = 15):
pg.init()
estado = inic
clock = pg.time.Clock()
while True:
pg.display.flip()
if parar_quando(estado):
print(estado)
sys.exit(0)
for event in pg.event.get():
if event.type == pg.QUIT:
print(estado)
sys.exit(0)
if event.type == pg.KEYDOWN:
estado = quando_tecla(estado, event.key)
elif event.type == pg.KEYUP:
estado = quando_solta_tecla(estado, event.key)
elif event.type in [pg.MOUSEBUTTONDOWN, pg.MOUSEBUTTONUP, pg.MOUSEMOTION]:
x, y = pg.mouse.get_pos()
estado = quando_mouse(estado, x, y, event.type)
estado = quando_tick(estado)
tela.fill(COR_BRANCO)
desenhar(estado)
if modo_debug:
escreve_estado(estado, tela, fonte_debug)
clock.tick(frequencia)
def big_bang(inic, tela,
quando_tick=lambda e: e, \
frequencia=28, \
desenhar=lambda e: pg.Surface((0,0)), \
quando_tecla=lambda e, k: e, \
quando_solta_tecla=lambda e, k: e, \
quando_mouse=lambda e, x, y, ev: e, \
parar_quando=lambda e: False,\
modo_debug=False,
fonte_debug = 15):
pg.init()
estado = inic
clock = pg.time.Clock()
while True:
pg.display.flip()
if parar_quando(estado):
print(estado)
sys.exit(0)
for event in pg.event.get():
if event.type == pg.QUIT:
print(estado)
sys.exit(0)
if event.type == pg.KEYDOWN:
estado = quando_tecla(estado, event.key)
elif event.type == pg.KEYUP:
estado = quando_solta_tecla(estado, event.key)
elif event.type in [pg.MOUSEBUTTONDOWN, pg.MOUSEBUTTONUP, pg.MOUSEMOTION]:
x, y = pg.mouse.get_pos()
estado = quando_mouse(estado, x, y, event.type)
estado = quando_tick(estado)
tela.fill(COR_BRANCO)
desenhar(estado)
if modo_debug:
escreve_estado(estado, tela, fonte_debug)
clock.tick(frequencia)
def big_bang(inic, tela,
quando_tick=lambda e: e, \
frequencia=28, \
desenhar=lambda e: pg.Surface((0,0)), \
quando_tecla=lambda e, k: e, \
quando_solta_tecla=lambda e, k: e, \
quando_mouse=lambda e, x, y, ev: e, \
parar_quando=lambda e: False,\
modo_debug=False,
fonte_debug = 15):
pg.init()
estado = inic
clock = pg.time.Clock()
while True:
pg.display.flip()
if parar_quando(estado):
print(estado)
sys.exit(0)
for event in pg.event.get():
if event.type == pg.QUIT:
print(estado)
sys.exit(0)
if event.type == pg.KEYDOWN:
estado = quando_tecla(estado, event.key)
elif event.type == pg.KEYUP:
estado = quando_solta_tecla(estado, event.key)
elif event.type in [pg.MOUSEBUTTONDOWN, pg.MOUSEBUTTONUP, pg.MOUSEMOTION]:
x, y = pg.mouse.get_pos()
estado = quando_mouse(estado, x, y, event.type)
estado = quando_tick(estado)
tela.fill(COR_BRANCO)
desenhar(estado)
if modo_debug:
escreve_estado(estado, tela, fonte_debug)
clock.tick(frequencia)
def big_bang(inic, tela,
quando_tick=lambda e: e, \
frequencia=28, \
desenhar=lambda e: pg.Surface((0,0)), \
quando_tecla=lambda e, k: e, \
quando_mouse=lambda e, x, y, ev: e, \
parar_quando=lambda e: False):
def desenha_tela():
tela.fill(COR_BRANCO)
desenhar(estado)
pg.init()
estado = inic
clock = pg.time.Clock()
while True:
pg.display.flip()
if parar_quando(estado):
print(estado)
sys.exit(0)
for event in pg.event.get():
if event.type == pg.QUIT:
print(estado)
sys.exit(0)
if event.type == pg.KEYDOWN:
estado = quando_tecla(estado, event.key)
desenha_tela()
elif event.type in [pg.MOUSEBUTTONDOWN, pg.MOUSEBUTTONUP, pg.MOUSEMOTION]:
x, y = pg.mouse.get_pos()
estado = quando_mouse(estado, x, y, event.type)
desenha_tela()
estado = quando_tick(estado)
desenha_tela()
clock.tick(frequencia)
def handle(self, event):
gd.BoardGame.handle(self, event) # send event handling up
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
column = (pos[0] - self.px_padding) // (self.layout.width)
row = (pos[1] - self.layout.top_margin) // (self.layout.height)
if event.button == 1 and column >= 0 and 2 <= row < self.data[1]:
if self.points_count == 0:
self.new_screen()
elif event.type == pygame.MOUSEBUTTONUP:
pos = event.pos
active = self.board.active_ship
column = (pos[0] - self.px_padding) // (self.layout.width)
row = (pos[1] - self.layout.top_margin) // (self.layout.height)
if active != self.canvas_block.unit_id:
if active == self.poli_btn.unit_id:
self.change_tool(4)
elif active == self.tria_btn.unit_id:
self.change_tool(3)
elif active == self.circle_btn.unit_id:
self.change_tool(2)
elif active == self.next_btn.unit_id and self.next_btn.keyable == True:
self.next_shape()
if event.button == 1 and column >= 0 and 2 <= row < self.data[1]:
if self.points_count < self.max_points:
canvas_pos = self.snap_to_guide(
[pos[0] - self.px_padding, pos[1] - self.layout.top_margin - self.board.scale * 2])
if canvas_pos not in self.points:
self.points.append(canvas_pos)
self.p_current = canvas_pos
self.paint_line(0)
self.paint_line(2)
self.points_count += 1
if self.points_count >= self.max_points:
self.check_drawing()
elif event.type == pygame.MOUSEMOTION and 0 < self.points_count < self.max_points:
active = self.board.active_ship
pos = event.pos
column = (pos[0] - self.px_padding) // (self.layout.width)
row = (pos[1] - self.layout.top_margin) // (self.layout.height)
if column >= 0 and 2 <= row < self.data[1]:
canvas_pos = self.snap_to_guide(
[pos[0] - self.px_padding, pos[1] - self.layout.top_margin - self.board.scale * 2])
self.p_current = canvas_pos[:]
if self.prev_snap is None:
self.prev_snap = canvas_pos[:]
if self.prev_snap != self.p_current:
self.prev_snap = canvas_pos[:]
self.paint_line(1)
def handle(self, event):
gd.BoardGame.handle(self, event) # send event handling up
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
active = self.board.active_ship
column = (pos[0] - self.px_padding) // (self.layout.width)
row = (pos[1] - self.layout.top_margin) // (self.layout.height)
if event.button == 1 and column >= 0 and 0 <= row < self.data[1]:
if self.points_count == 0:
pass # self.new_screen()
elif event.type == pygame.MOUSEBUTTONUP:
pos = event.pos
active = self.board.active_ship
column = (pos[0] - self.px_padding) // (self.layout.width)
row = (pos[1] - self.layout.top_margin) // (self.layout.height)
if active != self.canvas_block.unit_id:
if active == self.poli_btn.unit_id:
self.change_tool(4)
elif active == self.tria_btn.unit_id:
self.change_tool(3)
elif active == self.circle_btn.unit_id:
self.change_tool(2)
if event.button == 1 and column >= 0 and 0 <= row < self.data[1]:
if self.points_count < self.max_points:
canvas_pos = self.snap_to_guide([pos[0] - self.px_padding, pos[1] - self.layout.top_margin])
if canvas_pos not in self.points:
self.points.append(canvas_pos)
self.p_current = canvas_pos
self.paint_line(0)
self.paint_line(2)
self.points_count += 1
if self.points_count >= self.max_points:
self.check_drawing()
elif event.type == pygame.MOUSEMOTION and 0 < self.points_count < self.max_points:
active = self.board.active_ship
pos = event.pos
column = (pos[0] - self.px_padding) // (self.layout.width)
row = (pos[1] - self.layout.top_margin) // (self.layout.height)
if column >= 0 and 0 <= row < self.data[1]:
canvas_pos = self.snap_to_guide([pos[0] - self.px_padding, pos[1] - self.layout.top_margin])
self.p_current = canvas_pos[:]
if self.prev_snap is None:
self.prev_snap = canvas_pos[:]
if self.prev_snap != self.p_current:
self.prev_snap = canvas_pos[:]
self.paint_line(1)
def handle(self, event):
gd.BoardGame.handle(self, event) # send event handling up
self.tm = self.time[:]
if event.type == pygame.MOUSEMOTION and self.hand_id > 0:
pos = [event.pos[0] - self.layout.game_left, event.pos[1] - self.layout.top_margin]
r = self.vector_len([pos[0] - self.center[0], pos[1] - self.center[1]])
if r == 0: r = 0.1
if self.hand_id == 1:
h = (self.current_angle(pos, r)) / self.angle_step_12
if int(h) == 0:
self.tm[0] = 12
else:
self.tm[0] = int(h)
elif self.hand_id == 2:
m = (self.current_angle(pos, r)) / self.angle_step_60
self.tm[1] = int(m)
if 0 <= self.tm[1] < 5 and 55 <= self.time[1] <= 59:
if self.tm[0] == 12:
self.tm[0] = 1
else:
self.tm[0] += 1
elif 0 <= self.time[1] < 5 and 55 <= self.tm[1] <= 59:
if self.tm[0] == 1:
self.tm[0] = 12
else:
self.tm[0] -= 1
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
active = self.board.active_ship
pos = [event.pos[0] - self.layout.game_left, event.pos[1] - self.layout.top_margin]
if active == 0:
r = self.vector_len([pos[0] - self.center[0], pos[1] - self.center[1]])
if r == 0: r = 0.1
self.hand_id = 0
if self.is_contained(pos, coords_id=0):
self.hand_id = 1
elif self.is_contained(pos, coords_id=1):
self.hand_id = 2
elif self.rs[0] * 1.1 > r:
h = (self.current_angle(pos, r)) / self.angle_step_12
if int(h) == 0:
h = 12
self.tm[0] = int(h)
else:
m = (self.current_angle(pos, r)) / self.angle_step_60
self.tm[1] = int(m)
elif active == 1:
self.change_time_btn(1, 0)
elif active == 2:
self.change_time_btn(0, 1)
elif active == 3:
self.change_time_btn(-1, 0)
elif active == 4:
self.change_time_btn(0, -1)
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.hand_id = 0
if self.tm != self.time:
self.time = self.tm[:]
self.draw_hands()
self.clock_canvas.painting = self.canvas.copy()