所以我有一个项目,我必须创建一个TURTLE图形的游戏,而不使用任何其他模块,除了龟和随机模块。我正在创造传统的蛇游戏,除非蛇“吃掉”它不会变大的物体。我的游戏的问题是,当“蛇”到达物体时,物体不会消失,我希望它消失并重新出现在另一个位置。请帮忙。这是代码:
from turtle import *
import random
setup(700, 700)
title("Snake Game!")
bgcolor("blue")
# Boundary
bPen = Pen()
bPen.color("Orange")
bPen.up()
bPen.goto(-300, -300)
bPen.down()
for i in range(4):
bPen.ht()
bPen.fd(600)
bPen.lt(90)
# Player
playerPen = Pen()
playerPen.color("Orange")
playerPen.up()
playerPen.width(4)
# Create Circle
circle = Pen()
circle.shape("circle")
circle.color("Red")
circle.up()
circle.speed(0)
circle.goto(-100, 100)
# Speed
speed = 2
# Movement functions
def left():
playerPen.lt(90)
def right():
playerPen.rt(90)
def speedBoost():
global speed
speed += 1
# Key Prompts
onkey(left, "Left")
onkey(right, "Right")
onkey(speedBoost, "Up")
listen()
# Infinity loop and player knockback
while True:
playerPen.fd(speed)
if playerPen.xcor() < -300 or playerPen.xcor() > 300:
playerPen.rt(180)
elif playerPen.ycor() < - 300 or playerPen.ycor() > 300:
playerPen.rt(180)
# Collision with circle
if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():
circle.goto(random.randint(-300, 300), random.randint(-300, 300))
done()
答案 0 :(得分:0)
代码可以正常工作,但是很难将蛇完全击中圆圈的中心。要解决此问题,请在代码顶部添加一个常量:
RADIUS = 10
这大致是圆的半径。然后,更改此行:
if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():
代替:
if abs(playerPen.xcor() - circle.xcor()) < RADIUS and abs(playerPen.ycor() - circle.ycor()) < RADIUS:
享受游戏吧!
或者如果你因为无法使用abs()
而无法享受游戏,那么这是另一种在没有它的情况下写同一行的方法:
if -RADIUS < playerPen.xcor() - circle.xcor() < RADIUS and -RADIUS < playerPen.ycor() - circle.ycor() < RADIUS: