[英]Collision Detection Python curses
以下代码作为玩具代码编写,用于在MacBook Pro上测试curses模块(我使用的是Terminal App中随附的默认python安装)。 该测试将创建一个L符号表示的“敌人”(跟随一个移动周期),而播放器则以“ @”表示。 无论我如何处理边界问题(请参见宽度和高度处理),我唯一关心的问题是碰撞检测不起作用。 我不知道这是由于if块或时序的错误移位引起的。
代码粘贴:
import curses
import random
from time import sleep
screen = curses.initscr()
screen.keypad(True)
curses.noecho()
screen.nodelay(True)
xpos=1
ypos=1
i=0
h,w = screen.getmaxyx()
w=w-22
h=h-5
e1startxpos=random.randint(5,80)
e1startypos=random.randint(2,15)
e1xpos=[0,0,0,1,1,1,0,0,0,-1,-1,-1]
e1ypos=[1,1,1,0,0,0,-1,-1,-1,0,0,0]
tempe1x = e1startypos+e1ypos[i]
tempe1y = e1startxpos+e1xpos[i]
while True:
screen.clear()
screen.border(0)
screen.addstr(ypos,xpos,"@")
screen.addstr(0,w,"xpos:{0}ypos:{1}h:{2}w:{3}".format(xpos,ypos,h,w))
if (xpos == tempe1x and ypos == tempe1y):#The detector, which should run before another cycle
screen.addstr(1,1,"Collision Detected: Exiting")
screen.refresh()
sleep(1.5) #timing redundant to see the detection of collision
break
else:
tempe1x = tempe1x+e1ypos[i]
tempe1y = tempe1y+e1xpos[i]
screen.addstr(tempe1x,tempe1y,"L")
if(i == len(e1xpos)-1):
i=0
else:
i+=1
screen.refresh()
c = screen.getch()
if c == ord('a'):
if xpos>0:
xpos = xpos-1
elif c == ord('d'):
if xpos<w:
xpos = xpos+1
elif c == ord('w'):
if ypos>0:
ypos = ypos-1
elif c == ord('s'):
if ypos<h:
ypos = ypos+1
elif c == ord('q'):
break
sleep(0.1)
screen.clear()
screen.addstr(0,0,"Gioco Finito")
screen.refresh()
sleep(2)
curses.echo()
curses.endwin()`
PS:我没有在该平台上编辑帖子的经验,因此此代码副本可能导致缩进不正确
首先,您在此处混合了tempe1x
和tempe1y
的初始化:
tempe1x = e1startypos+e1ypos[i]
tempe1y = e1startxpos+e1xpos[i]
您需要切换x和y:
tempe1x = e1startxpos+e1xpos[i]
tempe1y = e1startypos+e1ypos[i]
接下来, addstr
方法首先使用y位置,然后是x位置。 使用播放器可以实现正确的操作: screen.addstr(ypos,xpos,"@")
但是您可以通过将x位置放在第一位来将其与敌人角色screen.addstr(tempe1x, tempe1y,"L")
: screen.addstr(tempe1x, tempe1y,"L")
。 它应该是:
screen.addstr(tempe1y,tempe1x,"L")
根据我的经验,这是可行的。 我没有使用curses
库的经验,所以如果您仍然遇到任何问题,请告诉我。
-Jason
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.