【问题标题】:Collision detection in PythonPython中的碰撞检测
【发布时间】:2015-01-22 17:11:30
【问题描述】:

我目前正在开发一个用 iPython notbook 编写的迷宫游戏。我无法访问 pygame,因此从头开始进行碰撞检测。

到目前为止,我得到的代码能够让玩家四处移动,并且已经有一个网格可以确定游戏场的大小。

from turtle import *

def line(x1, y1, x2, y2):
    pu()
    goto(x1,y1)
    pd()
    goto(x2,y2)
    pu()


setup(600,600)
setworldcoordinates(-1,-1,11,11)

class Network:

tracer(30)
ht()
for n in range(0,11):
    line(0,n,10,n)
    line(n,0,n,10)

tracer(1)

head= heading()

st()

class Figur:

register_shape("figur.gif")
shape("figur.gif")

head = heading()
pu()
setpos(9.5,9.5)

def turtle_up():
    if head != 90:
        seth(90)
        fd(1)

def turtle_down():
    if head != 270:
        seth(270)
        fd(1)

def turtle_left():
    if head != 180:
        seth(180)
        fd(1)

def turtle_right():
    if head != 360:
        seth(0)
        fd(1)

onkey(turtle_up, "Up")
onkey(turtle_down, "Down")
onkey(turtle_left, "Left")
onkey(turtle_right, "Right")

listen()

class Walls:

    def tortle():
        tracer(30)
        t1 = Turtle()
        t1.color("green")
        t1.left(180)
        t1.fd(1)
        t1.right(90)
        t1.fd(11)
    for i in range(1,4):
        t1.right(90)
        t1.fd(12)
    for i in range(1,3):
        t1.right(90)
        t1.fd(1)
    t1.left(90)
    for i in range(1,5):
        t1.fd(10)
        t1.right(90)

Walls.tortle() 
tracer(1)

update()
done()

目前,墙壁还没有完工。我刚刚开始使用它们,并试图在比赛场地周围创建一堵墙,导致球洞区域被绿色覆盖。乌龟的图片是我自己创建的,但我认为没有它应该也能工作,而只需使用普通的乌龟。

所以我的主要问题是:如何为我的乌龟创建碰撞检测,使其无法穿过墙壁?

【问题讨论】:

  • 好的,马上-1。有人可以解释一下我在这篇文章中做错了什么吗?

标签: python-3.x ipython-notebook


【解决方案1】:

我想对已经访问过的点进行set 的Vec2Ds,然后在每次移动时进行比较。这是一个简单的前进和后退函数:

def no_collision_forward(amount, walls):
    movement = 1 if abs(amount) == amount else -1 # If amount is negative, moving down
    for i in range(abs(amount)):
        cur_pos = pos()
        nex_pos = Vec2D(cur_pos[0], cur_pos[1] + movement)
        if nex_pos in walls:
            return  # Can return whatever
        else:
            forward(movement)

def no_collision_backward(amount, walls):
    return no_collision_forward(-amount, walls)

visited_locations 应该是一组Vec2Ds 或元组。

这可能不是最有效的解决方案,但确实有效!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-26
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2019-04-30
    相关资源
    最近更新 更多