1

当我点击播放时,我的光标似乎位于矩形的左上角,我对使用 thonny/pygames 非常陌生,但不知道如何让我的鼠标光标位于矩形的中心。

任何帮助将不胜感激,谢谢!:)

import pygame  # accesses pygame files
import sys  # to communicate with windows

# game setup ################ only runs once
pygame.init()  # starts the game engine
clock = pygame.time.Clock()  # creates clock to limit frames per second
FPS = 60  # sets max speed of main loop
SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1000, 800  # sets size of screen/window
screen = pygame.display.set_mode(SCREENSIZE)  # creates window and game screen

# set variables for colors RGB (0-255)
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
yellow = (255, 255, 0)
green = (0, 255, 0)

gameState = "running"  # controls which state the games is in
# game loop #################### runs 60 times a second!
while gameState != "exit":  # game loop - note:  everything in the mainloop is indented one tab

    for event in pygame.event.get():  # get user interaction events
        print (event)
        if event.type == pygame.QUIT:  # tests if window's X (close) has been clicked
            gameState = "exit"  # causes exit of game loop


    # your code starts here ##############################

        screen.fill(black)

        mouse_position = pygame.mouse.get_pos()
        player1X = mouse_position[0]
        player1Y = mouse_position[1]


        player1 = pygame.draw.rect(screen, red, (player1X, player1Y, 50, 50))

        pygame.display.flip()  # transfers build screen to human visable screen
        clock.tick(FPS)  # limits game to frame per second, FPS value





    # your code ends here ###############################
    pygame.display.flip()  # transfers build screen to human visable screen
    clock.tick(FPS)  # limits game to frame per second, FPS value

# out of game loop ###############
print("The game has closed")  # notifies user the game has ended
pygame.quit()   # stops the game engine
sys.exit()  # close operating system window
4

1 回答 1

0

创建一个pygame.Rect与播放器大小相同的对象,并center通过鼠标光标位置设置矩形的位置:

player1 = pygame.Rect(0, 0, 50, 50)
player1.center = mouse_position
pygame.draw.rect(screen, red, player1)

注意,apygame.Rect有一堆虚拟属性,可以用来获取一个集合的大小和位置。

于 2020-05-12T14:21:49.110 回答