簡體   English   中英

鼠標坐標不變 - python

[英]Mouse coordinates not changing - python

我正在嘗試構建一個簡單的游戲,但是我遇到了鼠標問題,因為它沒有顯示它的坐標正在改變。

這是我的代碼:

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

這是單擊屏幕的多個不同部分后的結果:

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

另外,有沒有辦法讓一個矩形跟隨我的鼠標? 我嘗試做pygame.mouse.rect(game_screen, blue, [pos, character_length, character_width]) ,但這只是讓我的程序崩潰。

所以,問題是你沒有刷新鼠標position,因為不在循環中。 您需要做的就是將pos變量放入循環中。

這是您應該如何做的:

if event.type == pygame.MOUSEBUTTONDOWN:
        pos = pygame.mouse.get_pos()
        print(pos)
        game_screen.fill(black)
        pygame.display.update()

我希望我對你有幫助!

謝謝,我成功地為我的 x 和 y 坐標設置了一個變量,但是當我嘗試讓一些東西(如矩形)跟隨我的鼠標時,它不起作用甚至顯示出來。 該程序只是執行一個純黑屏。

這是我的代碼:

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

# 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:
                pos = pygame.mouse.get_pos()
                character_x = pos[0]
                character_y = pos[1]
                pygame.draw.rect(game_screen, blue, [character_x, character_y, character_length, character_width])
                game_screen.fill(black)
                pygame.display.update()

pygame.quit()
quit()

我使用調試行來查看變量是否存在問題,但這些似乎工作得很好,所以我不確定問題出在哪里。

這是您第二個問題的答案:

所以,問題是在你繪制矩形之后,你正在用黑色填充屏幕,所以,所有的矩形都被黑色覆蓋了。

您需要做的就是刪除game_screen.fill(black)並且它會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM