【发布时间】:2021-02-14 04:36:33
【问题描述】:
我正在尝试将字符串转换为类似的函数
A_rect = "pygame.Rect(50, 50, 100, 100)"
然后在主循环下我想像pygame.draw.rect(win, (200, 0, 0), a_rect)一样显示它
但它不会带一个字符串。有什么办法可以隐藏它。
我实际上使用的是json文件,所以我的python文件如下:
import pygame
from pygame.locals import *
import sys
import json
pygame.init()
wind_h, wind_w = 800, 600
wind = pygame.display.set_mode((wind_h, wind_w))
pygame.display.set_caption("No Touch")
spsh = pygame.image.load("Carpets 4.png")
jsonv = open("JSONV.json", "r")
imgs = open("imgs.json", "r")
img_data = json.load(imgs)
data = json.load(jsonv)
def get_image(posx, posy, width, height, sprite_sheet):
"""Extracts image from sprite sheet"""
image = pygame.Surface([width, height])
image.blit(sprite_sheet, (0, 0), (posx, posy, width, height))
image.set_colorkey((0, 0, 0))
return image
def terminate():
pygame.quit()
sys.exit()
def draw():
wind.fill((100, 100, 100))
for i in data['Room-1']:
#print(data['Room-1'][str(i)]['w'])
#pygame.draw.rect(wind, (255, 0, 0), pygame.Rect(data['Room-1'][str(i)]['x'], data['Room-1'][str(i)]['y'], data['Room-1'][str(i)]['w'], data['Room-1'][str(i)]['h']))
wind.blit(get_image(0, 0, img_data['water']['w'], img_data['water']['h'], spsh), pygame.Rect(data['Room-1'][str(i)]['x'], data['Room-1'][str(i)]['y'], data['Room-1'][str(i)]['w'], data['Room-1'][str(i)]['h']))
#wind.blit(spsh, pygame.Rect(2, 2, 4, 4))
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
draw()
pygame.display.flip()
这是我的主要 jsonv.json 文件:
{
"Room-1" : {
"rect0" : {
"w": 500,
"h": 500,
"x": 4,
"y": 4
},
"rect1" : {
"w": 500,
"h": 500,
"x": 24,
"y": 4
},
"rect2" : {
"w": 500,
"h": 500,
"x": 44,
"y": 4
},
"rect3" : {
"w": 500,
"h": 500,
"x": 64,
"y": 4
},
"rect4" : {
"w": 500,
"h": 500,
"x": 4,
"y": 24
},
"rect5" : {
"w": 500,
"h": 500,
"x": 24,
"y": 24
},
"rect6" : {
"w": 500,
"h": 500,
"x": 44,
"y": 24
},
"rect7" : {
"w": 500,
"h": 500,
"x": 64,
"y": 24
},
"rect8" : {
"w": 500,
"h": 500,
"x": 4,
"y": 44
},
"rect9" : {
"w": 500,
"h": 500,
"x": 24,
"y": 44
},
"rect10" : {
"w": 500,
"h": 500,
"x": 44,
"y": 44
},
"rect11" : {
"w": 500,
"h": 500,
"x": 64,
"y": 44
}
}
}
这里我想用"rect1": "pygame.Rect(500, 500, 4, 4)"替换rect
那么有没有办法将字符串转换为函数呢?
任何帮助将不胜感激。
【问题讨论】:
-
尝试用
eval()转换它。 -
好的,试试@HenryTjhia,谢谢