这种情况最近才发生在我身上,而且我没有对代码进行任何更改,所以我不知道从哪里开始寻找解决方案。
对于这个例子,我要求 chat-gpt 编写一个简单的 pygame 代码(粘贴在下面),但在我最近使用 pygame 编写的任何代码中都会发生这种情况:
import pygame
import numpy as np
import sys
# Initialize Pygame
pygame.init()
# Set up the window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Pygame with Circle")
# Set up the colors
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# Set up the player's properties using NumPy arrays
player_radius = 25
player_pos = np.array([WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2])
player_speed = 5
# Main game loop
running = True
while running:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_pos[0] -= player_speed
if keys[pygame.K_RIGHT]:
player_pos[0] += player_speed
if keys[pygame.K_UP]:
player_pos[1] -= player_speed
if keys[pygame.K_DOWN]:
player_pos[1] += player_speed
# Fill the background with white
window.fill(WHITE)
# Draw the player as a circle
pygame.draw.circle(window, RED, player_pos, player_radius)
# Update the display
pygame.display.flip()
# Cap the frame rate
pygame.time.Clock().tick(60)
# Quit Pygame
pygame.quit()
sys.exit()
如果在示例代码中,我使用箭头将圆圈向右移动,它最终会离开屏幕。
但是,如果我将它向左移动,它不会只是移动,而是留下一个覆盖屏幕整个宽度的红色条,与圆的直径一样,并且位于与高度相同的位置圆的中心。当圆心的 x 坐标小于零时,红色条就会显示。
游戏不会崩溃。如果我上下移动圆圈,红色条也会移动。如果我将圆圈进一步向左移动,栏将保持不变。如果我将圆圈向右移动,只要其中心的 x 坐标高于零,它就会重新出现并正常显示。
这只发生在圆圈上。红色方块通常会移动到屏幕的左边框。
如何解决这个问题?
import pygame
import numpy as np
import sys
# Initialize Pygame
pygame.init()
# Set up the window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Pygame with Circle")
# Set up the colors
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# Set up the player's properties using pygame.Rect()
player_radius = 25
height = 5 #You can edit this later
player = pygame.Rect(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2, player_radius, height)
player_speed = 5
# Main game loop
running = True
while running:
# Cap the frame rate
pygame.time.Clock().tick(60)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= player_speed
if keys[pygame.K_RIGHT]:
player.x += player_speed
if keys[pygame.K_UP]:
player.y -= player_speed
if keys[pygame.K_DOWN]:
player.y += player_speed
# Fill the background with white
window.fill(WHITE)
# Draw the player as a circle
pygame.draw.circle(window, RED, (player.x, player.y), player.width)
# Update the display
pygame.display.update()
# Quit Pygame
pygame.quit()
sys.exit()