碰撞检测Python诅咒

2024-05-01 21:34:26 发布

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

下面的代码是作为在macbookpro上测试curses模块的玩具代码编写的(我使用的是终端应用程序中的默认python安装)。 这个测试创建了一个“敌人”,用L符号表示,它遵循一个移动周期,玩家用“@”表示。 不管我如何糟糕地处理边界问题(请参见宽度和高度处理),我关心的唯一问题是无法工作的碰撞检测。我不明白这是否是由于错误的位移,如果块或时间。你知道吗

代码粘贴:

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:我没有在这个平台上编辑文章的经验,所以这个代码的副本可能会导致缩进不正确


Tags: 代码importifsleeprandomscreencurseselif
1条回答
网友
1楼 · 发布于 2024-05-01 21:34:26

首先,您在这里混淆了tempe1xtempe1y的初始化:

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(tempe1y,tempe1x,"L")

这是我的经验。我没有使用curses库的经验,所以如果您仍然遇到任何问题,请告诉我。你知道吗

-杰森

相关问题 更多 >