我正在尝试将“P”作为文本传输到棋盘上。即使按照之前有关如何位 block 传输方 block 的帮助,我也无法使用文本来完成此操作。
这种国际象棋游戏的变体由长枪兵、弓箭手和骑士进行。 “P”代表长枪兵。
将来,我将显示一个 Sprite ,但目前我想显示字母(另外,因为它可能对 GUI 有帮助)
class Unit:
def __init__(self):
self.surface = pygame.Surface((100, 100))
self.my_font = pygame.font.SysFont('Time New Roman', 18)
self.img = self.my_font.render('P', 1, (255, 0, 0))
self.surface.blit(self.img, (100, 100))
基本上我想做的是创建一个表面,设置字体,渲染它,并将其位图传输到创建的表面上。
以下是完整的显示代码:
import pygame
import sys
from coordinator import coordinator
# Sets up the display
pygame.init()
window_size = (800, 800)
game_window = pygame.display.set_mode(size=window_size)
pygame.display.set_caption('My Game')
class WhiteSquare:
def __init__(self):
self.height = int(window_size[0] / 8)
self.width = int(window_size[1] / 8)
self.white_square = pygame.Surface((self.height, self.width))
self.white_square.fill((255, 255, 255))
class BlackSquare:
def __init__(self):
self.height = int(window_size[0] / 8)
self.width = int(window_size[1] / 8)
self.black_square = pygame.Surface((self.height, self.width))
self.black_square.fill((0, 0, 0))
class ChessBoard:
def __init__(self):
self.ws = ws
self.bs = bs
self.white_columns = white_columns
self.black_columns = black_columns
def draw(self):
for columns in self.white_columns:
game_window.blit(self.ws.white_square, columns)
for columns in self.black_columns:
for destination in columns:
game_window.blit(self.bs.black_square, destination)
class Unit:
def __init__(self):
self.surface = pygame.Surface((100, 100))
self.my_font = pygame.font.SysFont('Time New Roman', 18)
self.img = self.my_font.render('P', 1, (255, 0, 0))
self.surface.blit(self.img, (100, 100))
coordinator = coordinator()
black_columns = coordinator[2], coordinator[3]
white_columns = coordinator[0] + coordinator[1]
#print('coordinator' + str(coordinator))
#print('w_columns' + str(w_columns))
ws = WhiteSquare()
bs = BlackSquare()
cb = ChessBoard()
u = Unit()
# Event loop (outer)
while 1:
# Event loop (inner)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
cb.draw()
pygame.display.update()
希望这是有道理的。
谢谢
最佳答案
在Unit
的构造函数中创建self.imag
。但在 draw
方法中对其进行了blit
。实例方法draw
有一个参数,它是Surface,其中的文本必须blit
:
class Unit:
def __init__(self):
self.surface = pygame.Surface((100, 100))
self.my_font = pygame.font.SysFont('Time New Roman', 18)
self.img = self.my_font.render('P', 1, (255, 0, 0))
def draw(self, surface):
surface.blit(self.img, (100, 100))
创建 Unit
类的实例(例如 u
)。在主循环中调用u.draw
。 draw
方法的参数是与显示器 (game_window
) 关联的 Surface,因此文本将绘制在显示器上。例如:
u = Unit()
while 1:
# Event loop (inner)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# draw the scene
cb.draw()
u.draw(game_window)
# update the display
pygame.display.update()
关于python - 如何从类内部显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58413084/