我正在为我的基于文本的RPG改造我的战斗系统,其中一个核心内容正在丢失。我有这样的代码:
gamemap=[["player", "", "", "", "", ""],
["", "", "", "", "", ""],
["", "", "", "", "", ""],
["", "", "", "", "", ""],
["", "", "", "", "", ""],
["", "", "", "", "", "enemy"]]
while True:
print("╔▒▒▒▒▒▒▒▒▒▒▒╗")
for i in gamemap:
print("▒║", end=" ")
for o in i:
if o=="player":
print("⌂", end="")
if o=="enemy":
print("⦿", end="")
if o=="":
print(".", end="")
print(" ║▒ ")
print("╚▒▒▒▒▒▒▒▒▒▒▒╝")
#shows possible actions
print("")
print(" UP | ATTACK")
print("LEFT RIGHT | DEFEND SPELL")
print(" DOWN | QUICK")
#asks what player wants to do
act=str(input("Type here. "))
if act=="RIGHT":
...
如果您运行此程序,它将显示我的游戏的样子。那个像房子一样的角色是玩家,而宝珠则是敌人。这是我的问题:
A)我希望那个球员可以移动。因此,如果玩家输入RIGHT,它将向右移动一个点。我怎么可能那样做?
B)如果你能够/想要你可以回答的其他事情。我想检测玩家和敌人之间的距离到int变量“距离”。以后它会对战斗系统很方便。
答案 0 :(得分:0)
您的游戏地图是网格(或矩阵)。尝试将游戏逻辑和渲染逻辑相互分离。我的意思是;给你的玩家和敌人更多信息。一种简单的方法如下:
class Entity:
def __init__(self, x, y, char, name):
self.pos = (x, y)
self.char = char
self.name = name
def __str__(self):
return self.char
def up(self):
y = max(self.pos[1] - 1, 0)
self.pos = (self.pos[0], y)
def right(self, width):
# not as nice, as up, as the width has to be
# known for the boundaries.
x = (self.pos[0] + 1) % width
self.pos = (x, self.pos[1])
# make something like this for every direction. problem:
# needs size of matrix for outer-bounds
player = Entity(0, 0, "⌂", "player")
enemy = Entitiy(5, 5, "⦿", "enemy")
def render(entities, width, height):
# just basics, no borders etc. for now
matrix = [['.' for x in range(width)] for y in range(height)]
for entity in entities:
x, y = entity.pos
matrix[y][x] = str(entity) # or entity.char, if unclear
printable = '\n'.join(''.join(line) for line in matrix)
print(printable)
# call with
>>> render([player, enemy], 6, 6)
⌂.....
......
......
......
......
.....⦿
>>> player.down()
......
⌂.....
......
......
......
.....⦿
这不是最佳解决方案,因为实体是硬连线的。我建议使用Matrix
- 类,保留这些结构并管理打印矩阵。
对于您的第二个问题:与上述解决方案一样,您可以将实体放置在坐标系中,可以采用不同的方法来获得距离。
<强> Euklidian geometry 强>
import math
a = max(player.pos[0]-enemy.pos[0], enemy.pos[0]-player.pos[0]) # on x-axis (dunno, if abs would do the same)
b = max(player.pos[1]-enemy.pos[1], enemy.pos[1]-player.pos[1]) # on y-axis
distance = math.sqrt(a**2 + b**2)
<强> Manhattan-metric 强>
aX, aY = player.pos
bX, bY = enemy.pos
distance = abs(aX - bX) + abs(aY - bY)
如果我弄错了或者你有疑问:请继续告诉我:P
修改强>
Entity.right
来说明垂直移动和矩阵边界。