我需要用鼠标垂直移动我的桨图像,我该怎么做?这是我的代码。我想移动鼠标并将运动与乒乓球游戏中的桨联系起来。
import pygame
pygame.init()
width = 900
height = 600
black = (0,0,0)
white = (255, 255, 255)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Pong')
clock = pygame.time.Clock()
paddle1Img = pygame.image.load('paddle.png')
paddle1Img = pygame.transform.scale(paddle1Img,(600, 300))
paddle2Img = pygame.image.load('paddle.png')
paddle2Img = pygame.transform.scale(paddle2Img,(600, 300))
def paddle1(paddle1X, paddle1Y):
screen.blit(paddle1Img,(paddle1X, paddle1Y))
def paddle2(paddle2X, paddle2Y):
screen.blit(paddle2Img, (paddle2X, paddle2Y))
def gameloop():
paddle1X = -90
paddle1Y = 0
paddle2X = width - 125
paddle2Y = 0
gameOver = False
while not gameOver:
for event in pygame.event.get():
if(event.type == pygame.QUIT):
gameOver = True
if(event.type == pygame.MOUSEMOVE):
# i want to add here something that i cant understand that is how to associate paddleImg with mouse movement
screen.fill(white)
paddle1(paddle1X, paddle1Y)
paddle2(paddle2X, paddle2Y)
pygame.display.update()
clock.tick(60)
gameloop()
pygame.quit()
quit()
您有事件pygame.MOUSEMOTION
来获取鼠标移动。
它具有鼠标位置event.pos
可用于设置桨位置。
或者您可以event.rel
查看自上一次MOUSEMOTION
以来移动了多少鼠标。
我使用 Surface 生成桨,这样每个人都可以在没有图像的情况下运行它。
我使用 Rect 来保持位置,因为它不仅具有x
和y
,还有center
、left
、right
、top
、bottom
等。 所以我可以检查与边框的"碰撞"。
import pygame
# --- constants --- (UPPER_NAMES)
WIDTH = 900
HEIGHT = 600
BLACK = (0 , 0, 0)
WHITE = (255, 255, 255)
# --- classes --- (CamelNames)
# empty
# --- functions --- (lower_names)
# empty
# --- main --- (lower_names)
# - init -
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# - objects -
paddle1_image = pygame.surface.Surface((100,25))
paddle1_rect = paddle1_image.get_rect(x=90, y=10)
# - mainloop -
clock = pygame.time.Clock()
game_over = False
while not game_over:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.MOUSEMOTION:
# move padle with mouse
mouse_x, mouse_y = event.pos
paddle1_rect.centerx = mouse_x
# - updates (detect collision)-
# keep padle inside window
if paddle1_rect.left < 0:
paddle1_rect.left = 0
elif paddle1_rect.right > WIDTH:
paddle1_rect.right = WIDTH
# - draws -
screen.fill(WHITE)
screen.blit(paddle1_image, paddle1_rect)
pygame.display.update()
# - FPS -
clock.tick(30) # 30 FPS is enough for human eye to see animation
# - end -
pygame.quit()