【问题标题】:snake head is not moving蛇头不动
【发布时间】:2021-06-24 03:05:05
【问题描述】:

这个蛇游戏代码是用 python-turtle 编写的。我想移动使用turtle模块绘制的蛇头,但不幸的是它不起作用。另外我使用for循环为蛇添加了多种食物,可能它们在碰撞中有问题,但我不知道如何摆脱这个......?????

导入模块

import turtle
from turtle import *
import random
import time


delay = 0.1
level = 1
lives = 3

#score
score = 0
high_score = 0

#setting the screen
wn = turtle.Screen()
wn.title('Snake Game')
wn.bgcolor('black')
wn.bgpic('pic55.png')
#wn.addshape('snake head6.png')
wn.setup(width= 600, height= 600)
wn.tracer(0) #turns off the screen update

使用海龟绘制的蛇头

#snake head
head = turtle.Turtle()
def draw_circle(color, radius, x, y):
    #head(turtle.Turtle())
    head.penup()
    head.fillcolor(color)
    head.goto(x, y)
    head.begin_fill()
    head.circle(radius)
    head.end_fill()
    head.hideturtle()
draw_circle("#FF4500", 30, 0, -40)  #face OrangeRed #FF4500 green #2CD717
draw_circle("#ffffff", 10, -10, -5)      #left eye 9659BD purple
draw_circle("#ffffff", 10, 10, -5)      #right eye  B4BCE2 light blue

draw_circle("#4a70e3", 7, -8, -4)      #5e7ede 9eb1eb  4a70e3 royalblue light colors
draw_circle("#4a70e3", 7, 8, -4)


draw_circle("#17202A", 5, -10, -5)      ##17202A black
draw_circle("#17202A", 5, 10, -5)





#colors = random.choice(['green','black'])
#shapes = random.choice(['square'])

#head.shape(shapes)
#head.color(colors)
head.goto(0,0)
head.penup()
head.speed(0) #animation speed
head.direction = 'stop'

#segment = []

多种食物

#max food
maxfoods =10
foods = []

#snake food
for count in range(maxfoods):
    foods.append(turtle.Turtle())
    foods[count].color('red')
    foods[count].shape('square')
    #food[count].shape(shapes)
    #food[count].color(colors)
    foods[count].penup()
    foods[count].speed() 
    foods[count].speed(0)#animation speed
    foods[count].setposition(random.randint(-300, 300) ,random.randint(-300, 300))

    
segment = []  

#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 Level: 1 Lives: 3",align = "center", font=("courier", 16, "normal"))



#functions
def go_up():
    if head.direction != 'down':
        head.direction = 'up'
def go_down():
    if head.direction != 'up':
        head.direction = 'down'
def go_left():
    if head.direction != 'right':
        head.direction = 'left'
def go_right():
    if head.direction != 'left':
        head.direction = 'right'
    
def move():
    if head.direction == 'up':
        y = head.ycor()
        head.sety(y + 20)
    if head.direction == 'down':
        y = head.ycor()
        head.sety(y - 20)
    if head.direction == 'left':
        x = head.xcor()
        head.setx(x - 20)
    if head.direction == 'right':
        x = head.xcor()
        head.setx(x + 20)


#keyboard binding
wn.listen()
wn.onkeypress(go_up, 'Up')
wn.onkeypress(go_down, 'Down')
wn.onkeypress(go_left, 'Left')
wn.onkeypress(go_right, 'Right')

while 循环

while True:
    wn.update()
    #check the border collision
    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
        time.sleep(1)
        head.goto(0, 0)
        head.direction = 'stop'
        for segments in segment:
            segment.goto(1000, 1000)
        segment.clear()
        
        #reset the score
        score = 0

        #reset the delay
        delay = 0.1

        #reset level
        level = 1
        
        pen.clear()
        pen.write("Score: {} High Score: {} Level: {} Lives: {}".format(score, high_score, level, lives),align = "center", font=("courier", 16, "normal"))

       
    
    #check for head collision with the food

    for count in range(maxfoods):
        #maxfood.forward(3)
        if head.distance(foods) < 20:
            #MOve the head random
            x = random.randint(-290, 290)
            y = random.randint(-290, 290)
            foods.goto(x, y)

            #add body to snake
            new_segment = turtle.Turtle()
            new_segment.speed(0)
            new_segment.shape('square')
            new_segment.color('green')
            new_segment.penup()
            segment.append(new_segment)

        
        #shorten the delay
        delay -= 0.001

        

        #increase the score
        score +=10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score: {} High Score: {} Level: {} Lives: {}".format(score, high_score, level, lives),align = "center", font=("courier", 16, "normal"))

        

    #Move the end body in reverse order
    for index in range(len(segment)-1, 0, -1):
        x = segment[index-1].xcor()
        y = segment[index-1].ycor()
        segment[index].goto(x, y)

    #move the body 0 t where the head is
    if len(segment) > 0:
        x = head.xcor()
        y = head.ycor()
        segment[0].goto(x, y)
        
    
    move()
    #check for head collision with body/segment
    for segments in segment:
        if segments.distance(head) < 20:
            time.sleep(1)
            head.goto(0, 0)
            head.direction = 'stop'
            
            #hide the segment
            for segments in segment:
                segments.goto(1000, 1000)

            #clear the segment list
            segment.clear()

            #reset the score
            score = 0

            #reset the level
            level = 1

            #update the score display
            pen.clear()
            pen.write("Score: {} High Score: {} Level: {} Lives: {}".format(score, high_score, level, lives),align = "center", font=("courier", 16, "normal"))


           
            
                        
    #levels
    if level == 1 and score == 50:
        level += 1
        delay *= 0.9
    if level == 2 and score == 100:
        level += 1
        delay *= 0.9
    if level == 3 and score == 250:
        level += 1
        delay *= 0.9
    if level == 4 and score == 350:
        level += 1
        delay *= 0.9
    if level == 5 and score == 450:
        level += 5
        delay *= 0.9
        

    time.sleep(delay)


wn.maingameloop()
 

【问题讨论】:

  • 我没试过,但我怀疑是因为你设置了wn.tracer(0)##注释掉那一行,或者在每个循环之后运行wn.update()
  • 实际上@Doyousketch2,我认为tracer()update() 是唯一正确的代码!再深入一点,一团糟。

标签: python turtle-graphics python-turtle


【解决方案1】:

您的代码是一场灾难。您是如何编写如此详细的代码而不测试基础知识是否有效的?明显问题的例子:

if head.distance(foods) < 20:

foods 变量是 list,您应该正在测试:

if head.distance(foods[count]) < 20:

还有这段代码:

#shorten the delay
delay -= 0.001

最终驱动 delay 为负,time.sleep() 失败。再次在这里:

foods.goto(x, y)

foods 变量是list,它不响应goto()。另外,无论蛇在哪里,你总是在同一个地方画蛇头!

下面是对您的程序的精简版本的完整修改,它试图使基础工作正常。蛇头动了;它可以吃食物来增加它的分数;检测到边界碰撞并重置分数和蛇位置:

from turtle import Screen, Turtle
from random import randint

FONT = ("courier", 16, "normal")

# score
score = 0
high_score = 0

# functions

def draw_circle(color, radius, x, y):
    head.fillcolor(color)
    head.goto(x, y)
    head.begin_fill()
    head.circle(radius)
    head.end_fill()

def go_up():
    if head.direction != 'down':
        head.direction = 'up'

def go_down():
    if head.direction != 'up':
        head.direction = 'down'

def go_left():
    if head.direction != 'right':
        head.direction = 'left'

def go_right():
    if head.direction != 'left':
        head.direction = 'right'

def move():
    x, y = head.position()

    if head.direction == 'up':
        head.sety(y + 20)
    elif head.direction == 'down':
        head.sety(y - 20)
    elif head.direction == 'left':
        head.setx(x - 20)
    elif head.direction == 'right':
        head.setx(x + 20)

    head.clear()
    x, y = head.position()

    draw_circle("#FF4500", 30, x + 0, y - 40)  # face OrangeRed #FF4500 green #2CD717
    draw_circle("#ffffff", 10, x - 10, y - 5)  # left eye 9659BD purple
    draw_circle("#ffffff", 10, x + 10, y - 5)  # right eye B4BCE2 light blue

    draw_circle("#4a70e3", 7, x - 8, y - 4)  # royalblue
    draw_circle("#4a70e3", 7, x + 8, y - 4)

    draw_circle("#17202A", 5, x - 10, y - 5)  # black
    draw_circle("#17202A", 5, x + 10, y - 5)

    head.setposition(x, y)

# setting the screen
screen = Screen()
screen.title('Snake Game')
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.tracer(False)  # turns off screen update

# snake head
head = Turtle()
head.hideturtle()
head.penup()
head.direction = 'stop'  # user defined property

move()

# max food
maxfoods = 10
foods = []

# snake food
for count in range(maxfoods):
    food = Turtle()
    food.color('red')
    food.shape('square')
    food.penup()
    food.setposition(randint(-300, 300), randint(-300, 300))
    foods.append(food)

# pen
pen = Turtle()
pen.hideturtle()
pen.shape('square')
pen.color('white')
pen.penup()
pen.sety(260)
pen.write("Score: 0 High Score: 0", align="center", font=FONT)

# keyboard binding
screen.onkeypress(go_up, 'Up')
screen.onkeypress(go_down, 'Down')
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()

def motion():
    global score, high_score

    # check the border collision
    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
        head.goto(0, 0)
        head.direction = 'stop'

        # reset the score
        score = 0

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

    # check for head collision with the food
    for food in foods:
        if head.distance(food) < 30:
            # Move the food randomly
            food.goto(randint(-290, 290), randint(-290, 290))

            # increase the score
            score += 10
            if score > high_score:
                high_score = score

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

            break

    move()

    screen.update()
    screen.ontimer(motion, 100)

motion()

screen.mainloop()

现在您应该能够一次添加一个功能并对其进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-30
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多