如何在python中检测两个对象之间的冲突?

如何在python中检测两个对象之间的冲突?,python,python-turtle,Python,Python Turtle,所以我正在为chrome的恐龙游戏python turtle制作一个克隆。我已经为仙人掌做了随机化(这是非常粗糙的,是的,如果有什么比我的方法更好,请帮助!),跳跃是有效的。但是正如标题所说,我无法正确地检测碰撞。我已经尝试了很多: import turtle import time import random print("dino game in turtle") wn = turtle.Screen() wn.bgcolor("white") wn

所以我正在为chrome的恐龙游戏python turtle制作一个克隆。我已经为仙人掌做了随机化(这是非常粗糙的,是的,如果有什么比我的方法更好,请帮助!),跳跃是有效的。但是正如标题所说,我无法正确地检测碰撞。我已经尝试了很多:

import turtle
import time
import random
print("dino game in turtle")

wn = turtle.Screen()
wn.bgcolor("white")
wn.setup(width=650, height=400)
wn.tracer(0)
delay = 0.1
#scoring system
score = 0
w = 1
h = 1
#dino
dino = turtle.Turtle()
dino.shape("square")
dino.shapesize(w, h)
dino.color("black")
dino.penup()
dino.goto(-200, -50)

#ground
g = turtle.Turtle()
g.penup()
g.goto(0, -60)
g.pendown()
g.lt(180)
g.fd(500)
g.rt(180)
g.fd(1000)
g.hideturtle()

#cactus
#y = random.randint(2, 4)
cactus = turtle.Turtle()
cactus.penup()
cactus.shape("square")
cactus.color("green")
cactus.shapesize(3, 0.5)
cactus.goto(-50, -30)

cactus2 = turtle.Turtle()
cactus2.penup()
cactus2.shape("square")
cactus2.color("green")
cactus2.shapesize(3, 0.5)
cactus2.goto(600, -30)

cactus3 = turtle.Turtle()
cactus3.penup()
cactus3.shape("square")
cactus3.color("green")
cactus3.shapesize(3, 0.5)
cactus3.goto(600, -30)

#score_pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0  High Score: 0", align="center", font=("Courier", 24, "normal"))





max_height = 150



def steady():
    y = dino.ycor() 
    if y == -50:
        return True
        
    else:
        return False
def jump():
    y = dino.ycor()
    if y != -50:
        return True
    else:
        return False
def jumping():
    y = dino.ycor()
    y += 200
    dino.sety(y)

def cactus_move():
    x = cactus.xcor()
    x -= 20
    cactus.setx(x)

def cactus_move2():
    x = cactus2.xcor()
    x -= 20
    cactus2.setx(x)

def cactus_move3():
    x = cactus3.xcor()
    x -= 20
    cactus3.setx(x)
x = dino.xcor()
y = dino.ycor()

def check_rect_collision(dino, x, y, w, h): 
    
    if p.x >= x and p.x <= x+w and p.y >= y and p.y <= y+h:
        # collision between p and rectangle
        return True
    return False







wn.listen()
wn.onkeypress(jumping, "space")

while True:
    score += 1
    check_rect_collision()
    #print(score)
    #pen.clear()
    #pen.clear()
    #pen.write("Score: {} ".format(score), align="center", font=("Courier", 24, "normal")) 
    x = random.randint(200, 300)
    xm = random.randint(300, 500)
    xms = random.randint(500, 550)
    
    cactus_move()
    cactus_move2()
    cactus_move3()
    y = dino.ycor()

    if steady() == True and dino.distance(cactus) < 25:
        print("Hello")
        break
    if steady() == True and dino.distance(cactus2) < 25:
        print("Hello")
        break
    if steady() == True and dino.distance(cactus3) < 25:
        print("Hello")
        break
    if jump() == True and dino.ycor() <= cactus.ycor():
        print("Ycor")
        break 
    if jump() == True and dino.ycor() <= cactus2.ycor():
        print("Ycor")
        break 
    if jump() == True and dino.ycor() <= cactus3.ycor():
        print("Ycor")
        break 

    if steady() == False:
        y -= 25
        dino.sety(y)
        
    if y >= max_height:
        y -= 200
        dino.sety(y) 

    if cactus.xcor() < -400:
        cactus.goto(x, -30)

    if cactus2.xcor() < -400:
        cactus2.goto(xm, -30)

    if cactus3.xcor() < -400:
        cactus3.goto(xms, -30)

    
    
        

    time.sleep(delay)
    wn.update()
wn.mainloop()
导入海龟
导入时间
随机输入
打印(“海龟中的恐龙游戏”)
wn=tutle.Screen()
wn.bgcolor(“白色”)
wn.设置(宽度=650,高度=400)
wn.tracer(0)
延迟=0.1
#评分系统
分数=0
w=1
h=1
#恐龙
恐龙=乌龟。乌龟()
恐龙形状(“方形”)
恐龙形状(w,h)
恐龙颜色(“黑色”)
恐龙
恐龙后藤(-200,-50)
#地面
g=海龟。海龟()
g、 彭普()
g、 后藤(0,-60)
g、 彭敦()
g、 lt(180)
g、 fd(500)
g、 rt(180)
g、 fd(1000)
g、 希德图尔()
#仙人掌
#y=random.randint(2,4)
仙人掌=乌龟
仙人掌
仙人掌形状(“方形”)
仙人掌。颜色(“绿色”)
仙人掌形状(3,0.5)
仙人掌后藤(-50,-30)
仙人掌2=海龟。海龟()
仙人掌
仙人掌2.形状(“方形”)
仙人掌2.颜色(“绿色”)
仙人掌2.形状大小(3,0.5)
仙人掌2.后藤(600,-30)
仙人掌3=海龟。海龟()
仙人掌
仙人掌3.形状(“方形”)
仙人掌3.颜色(“绿色”)
仙人掌3.形状大小(3,0.5)
仙人掌3。后藤(600,-30)
#记分笔
pen=海龟。海龟()
笔速(0)
笔形(“方形”)
钢笔颜色(“白色”)
pen.penup()
pen.hideturtle()
后藤(0260)
书写(“分数:0高分:0”,align=“center”,font=(“Courier”,24,“normal”))
最大高度=150
def staid():
y=dino.ycor()
如果y==-50:
返回真值
其他:
返回错误
def jump():
y=dino.ycor()
如果y!=-50:
返回真值
其他:
返回错误
定义跳转():
y=dino.ycor()
y+=200
迪诺·塞蒂(y)
def cactus_move():
x=cactus.xcor()
x-=20
仙人掌
def cactus_move2():
x=cactus2.xcor()
x-=20
仙人掌2.setx(x)
def cactus_move3():
x=cactus3.xcor()
x-=20
仙人掌3.setx(x)
x=dino.xcor()
y=dino.ycor()
def检查直接碰撞(恐龙、x、y、w、h):

如果p.x>=x且p.x=y且p.y正常,我建议使用
turtle.distance()
函数。但是由于你的两只海龟的形状不同,你需要一个自定义的碰撞函数来考虑它们的形状。我在下面重新编写了您的代码,包括,以及修复它以使用turtle计时器事件,而不是
while True
sleep()
和其他更改:

from turtle import Screen, Turtle
from random import randint

WIDTH, HEIGHT = 650, 400
MAX_HEIGHT = 180
BASELINE = -60

NUMBER_CACTI = 3

FONT = ('Courier', 24, 'normal')

CURSOR_SIZE = 20
CACTUS_WIDTH, CACTUS_HEIGHT = 10, 60

def steady():
    return dino.ycor() == BASELINE + CURSOR_SIZE/2

def jump():
    y = dino.ycor()

    if steady():
        dino.sety(y + 7 * CURSOR_SIZE)
    elif y < MAX_HEIGHT:
        dino.sety(y + 2 * CURSOR_SIZE)

def cactus_move(cactus):
    cactus.setx(cactus.xcor() - CACTUS_WIDTH)

def check_rect_collision(a, b):
    return abs(a.xcor() - b.xcor()) < CURSOR_SIZE/2 + CACTUS_WIDTH/2 and abs(a.ycor() - b.ycor()) < CURSOR_SIZE/2 + CACTUS_HEIGHT/2

def place_cactus(cactus):
    cactus.setx(randint(WIDTH//2, WIDTH))

    while True:
        for other in cacti:
            if other is cactus:
                continue

            if other.distance(cactus) < 5 * CACTUS_WIDTH:
                cactus.setx(randint(0, WIDTH//2))
                break  # for
        else:  # no break
            break  # while

# scoring system
score = 0

def run():
    global score

    score += 1

    pen.clear()
    pen.write("Score: {} ".format(score), align='center', font=FONT)

    for cactus in cacti:
        cactus_move(cactus)

        if check_rect_collision(dino, cactus):
            screen.onkeypress(None, 'space')  # Game Over
            screen.tracer(True)
            return

        if cactus.xcor() < -WIDTH/2:
            place_cactus(cactus)

    if not steady():
        dino.sety(dino.ycor() - CURSOR_SIZE)

    screen.update()
    screen.ontimer(run, 50)  # repeat in 50 milliseconds

screen = Screen()
screen.title("Dino game in turtle")
screen.bgcolor('white')
screen.setup(width=WIDTH, height=HEIGHT)
screen.tracer(False)

# ground
ground = Turtle()
ground.hideturtle()

ground.penup()
ground.sety(BASELINE)
ground.pendown()

ground.forward(WIDTH/2)
ground.backward(WIDTH)

# dino

dino = Turtle()
dino.shape('square')
dino.penup()
dino.goto(-WIDTH/3, BASELINE + CURSOR_SIZE/2)

# cacti

cacti = []

for _ in range(NUMBER_CACTI):

    cactus = Turtle()
    cactus.shape('square')
    cactus.shapesize(CACTUS_HEIGHT / CURSOR_SIZE, CACTUS_WIDTH / CURSOR_SIZE)
    cactus.color('green')

    cactus.penup()
    cactus.sety(BASELINE + CACTUS_HEIGHT/2)
    place_cactus(cactus)

    cacti.append(cactus)

# score pen
pen = Turtle()
pen.hideturtle()
pen.penup()
pen.sety(175)

pen.write("Score: 0  High Score: 0", align='center', font=FONT)

screen.onkeypress(jump, 'space')
screen.listen()

run()

screen.mainloop()
从海龟导入屏幕,海龟
从随机导入randint
宽度,高度=650400
最大高度=180
基线=-60
仙人掌数量=3
字体=('Courier',24,'normal')
光标大小=20
仙人掌宽度,仙人掌高度=10,60
def staid():
返回dino.ycor()==基线+光标大小/2
def jump():
y=dino.ycor()
如果稳定():
恐龙尾巴(y+7*光标大小)
elif y<最大高度:
恐龙设置(y+2*光标大小)
def仙人掌移动(仙人掌):
cactus.setx(cactus.xcor()-cactus_宽度)
def检查直接碰撞(a、b):
返回abs(a.xcor()-b.xcor())

我相信它现在基本上是可以玩的,但是你可能想调整一些常数来适应你的口味。

你可以像游戏引擎一样,把形状放在物体上,应用碰撞检测算法,有一些算法非常简单,例如球体对球体,这就是它的工作原理

  • 在想要检测colision的对象上画一个圆圈,这可以通过创建一个类CircleCollider来实现,例如,将它作为海龟的属性。这个对撞机有一个ID、半径和位置,和海龟一样

  • 创建另一个类来管理碰撞器和碰撞,将碰撞保存在数组或列表中

  • 每次迭代(我假设您的游戏代码在一个循环中),应用sphere vs sphere算法来检测冲突。您必须在所有对象之间执行此操作。(也不要忘记更新碰撞器位置)

  • 球面与球面alg