试图让pygame文档代码正常工作

2024-04-19 06:48:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在浏览pygame 1.9.6的文档,我已经到了第29页,老实说,我不明白为什么我不能让它做它所说的事情(制作一个绿色矩形,用红点和黑色文本定义4个角、4个中点和中心点)

文档代码见第29页: https://buildmedia.readthedocs.org/media/pdf/pygame/latest/pygame.pdf

我觉得他们提供的示例中遗漏了很多内容,所以我对它进行了一点尝试,但已经达到了我只想看看如何让它做它所说的应该做的事情的地步

我的变体:

import pygame
from pygame.locals import *
from pygame.rect import *
from pygame.font import *

def draw_point(text, pos):
    img = font.render(text, True, Black)
    pygame.draw.circle(screen, RED, pos, 3)
    screen.blit(img, pos)

SIZE = 500, 200
RED = (255, 0, 0)
GRAY = (150, 150, 150)
GREEN = (255, 0, 0)
BLACK = (255, 255, 255)

pygame.init()
screen = pygame.display.set_mode(SIZE)

rect = Rect(50, 40, 250, 80)
##print(f'x={rect.x}, y={rect.y}, w={rect.w}, h={rect.h}')
##print(f'left={rect.left}, top={rect.top}, right={rect.right}, bottom={rect.bottom}')
##print(f'center={rect.center}')

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    screen.fill(GRAY)
    pygame.draw.rect(screen, GREEN, rect, 4)

    for pt in pts:
        draw_point(pt, eval('rect.'+pt))
        
    pygame.display.flip()

pygame.quit()

感谢您的帮助


Tags: from文档posrectimporteventptpdf
1条回答
网友
1楼 · 发布于 2024-04-19 06:48:31

阅读完整的document

变量pts在第25页

pts = ('topleft', 'topright', 'bottomleft', 'bottomright', 
       'midtop', 'midright', 'midbottom', 'midleft', 'center')

变量font在第36页:

font = pygame.font.Font(None, 24)

完整示例:

import pygame
from pygame.locals import *
from pygame.rect import *
from pygame.font import *

def draw_point(text, pos):
    img = font.render(text, True, BLACK)
    pygame.draw.circle(screen, RED, pos, 3)
    screen.blit(img, pos)

SIZE = 500, 200
RED = (255, 0, 0)
GRAY = (150, 150, 150)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)

pygame.init()
screen = pygame.display.set_mode(SIZE)
font = pygame.font.Font(None, 24)
rect = Rect(50, 40, 250, 80)
pts = ('topleft', 'topright', 'bottomleft', 'bottomright', 
       'midtop', 'midright', 'midbottom', 'midleft', 'center')

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    screen.fill(GRAY)
    pygame.draw.rect(screen, GREEN, rect, 4)

    for pt in pts:
        draw_point(pt, eval('rect.'+pt))
        
    pygame.display.flip()

pygame.quit()

相关问题 更多 >