I am trying to build a simple game, but I'm having trouble with the mouse as it's doesn't show that it's coordinates are changing.
Here's my code:
import pygame
pygame.init()
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
# Game Screen Dimensions
game_layout_length = 500
game_layout_width = 500
# Mouse Positions
pos = pygame.mouse.get_pos()
# Character Attributes
character_length = 10
character_width = 10
game_screen = pygame.display.set_mode((game_layout_width, game_layout_length))
game_close = False
game_lost = False
while not game_close:
while not game_lost:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_close = True
game_lost = True
if event.type == pygame.MOUSEBUTTONDOWN:
print(pos)
game_screen.fill(black)
pygame.display.update()
pygame.quit()
quit()
This is the result after clicking on multiple different parts of the screen:
pygame 2.1.2 (SDL 2.0.18, Python 3.8.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
Process finished with exit code 0
Also, is there a way to get a rectangle to follow my mouse? I tried doing pygame.mouse.rect(game_screen, blue, [pos, character_length, character_width])
, but that just crashed my program.
So, the problem is that you are not refreshing the mouse position, because is not in the loop. All you need to do is to put the pos
variable inside the loop.
Here is how should you do it:
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
print(pos)
game_screen.fill(black)
pygame.display.update()