gpt4 book ai didi

python - 如何在pygame中用鼠标滚动图像?

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:59 25 4
gpt4 key购买 nike

我需要用鼠标垂直移动我的桨图像,我该怎么做?这是我的代码。我想移动鼠标并将运动与 Racket 关联起来,就像乒乓球游戏中一样。

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生成 paddle,以便每个人都可以在没有图像的情况下运行它。

我使用Rect保持位置,因为它不仅有 xy,还有 centerleftrighttopbottom 等,这样我就可以检查与边框的“碰撞”。

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()

关于python - 如何在pygame中用鼠标滚动图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47365518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com