Python基础:第018课——鼠标拖动小球移动(2)

视频

观看视频

用鼠标拖动小球移动

pygame事件完整解析

如何让小球移动

MOUSEBUTTONDOWN
+int event.button
+tuple event.pos
+ballStopMove()
MOUSEMOTION
+tuple event.pos
+ballMove(pos) : rect
MOUSEBUTTONUP
+tuple event.pos
+ballMove(pos) : rect
+ballStartMove()

边界处理

在这里插入图片描述
关键是:

  1. 水平方向,只要小球超过右边的边界,就需要保证让小球向左运动,即运动方向向左。
  2. 纵向,只要小球超出下边界,就需要保证小球向上运动,即运动方向向上。

本次课代码

import pygame, sys

pygame.init()

screen_width , screen_height = 600,480
screen = pygame.display.set_mode((screen_width,screen_height))

pygame.display.set_caption("小小工坊")

ball = pygame.image.load('pygame/images/ball.gif')
ball_rect = ball.get_rect()

fclock = pygame.time.Clock()

speed = [1,1]
orientation = [1,1]

still = False
while True:

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif e.type == pygame.KEYDOWN:
            if e.key == pygame.K_UP:
                speed[1] = speed[1] - 1 if speed[1] > 0 else 0
            elif e.key == pygame.K_DOWN:
                speed[1] = speed[1] + 1
            elif e.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1
            elif e.key == pygame.K_LEFT:
                speed[0] = speed[0] - 1 if speed[0] >0 else 0
        elif e.type == pygame.MOUSEBUTTONDOWN:
            if e.button == 1:
                still = True
        elif e.type == pygame.MOUSEBUTTONUP:
            still = False
            ball_rect.left,ball_rect.top = e.pos
        elif e.type == pygame.MOUSEMOTION:
            if e.buttons[0] == 1:
                ball_rect.left, ball_rect.top = e.pos
    
    if ball_rect.bottom >= screen_height or ball_rect.top < 0:
        orientation[1] = -orientation[1]
        if ball_rect.bottom >= screen_height and ball_rect.bottom + orientation[1]*speed[1] > ball_rect.bottom:
            orientation[1] = -orientation[1]
    if ball_rect.right >= screen_width or ball_rect.left < 0:
        orientation[0] = -orientation[0]
        if ball_rect.right >= screen_width and ball_rect.right + orientation[0]*speed[0] > ball_rect.right:
            orientation[0] = -orientation[0]
    if not still:
        ball_rect = ball_rect.move(speed[0]*orientation[0],speed[1]*orientation[1])

    # if ball_rect.bottom >= screen_height:
    #     speed[1] = -1
    #     # ball_rect.bottom = screen_height
    # if ball_rect.top <= 0:
    #     speed[1] = 1
    #     # ball_rect.top = 0
    # if ball_rect.right >= screen_width:
    #     speed[0] = -1
    #     # ball_rect.right = screen_width
    # if ball_rect.left <= 0:
    #     speed[0] = 1
    #     # ball_rect.left = 0

    screen.fill((0,0,255))
    screen.blit(ball,ball_rect)

    pygame.display.update()
    fclock.tick(200)

猜你喜欢

转载自blog.csdn.net/acktomas/article/details/125828686