如何在python龟中使用随机模块?

时间:2017-12-18 15:24:46

标签: python-3.x turtle-graphics

我试图制作像原始蛇一样的游戏,我想要"食物"去随机的地方,但我不确定如何让它在课堂上使用它。代码中还有一些其他错误,但现在想要专注于播放器和食物。

import turtle
import random
"""-------"""
t=turtle.Turtle()
s=turtle.Screen()
cube=turtle.Turtle
"""------------"""
WIDTH, HEIGHT=300, 300
DISTANCE=5
"""--------------"""
s.setup(WIDTH,HEIGHT)
"""------------"""
t.width(1)
s.bgcolor("dark green")
"""-----------------"""
class Border():
    def check():
        x, y = t.position()
        if not -WIDTH / 2 < x < WIDTH / 2 or not -HEIGHT / 2 < y < HEIGHT / 2:
            t.undo() # undo error
            t.speed(0)
            t.left(180) # turn around
            t.forward(10) # redo movement but in new direction
            t.speed(3)
"""-------------"""
randint=random.randint
x=random.randint(cube.xcor, 0)
y=random.randint(0,cube.ycor)
"""---------------"""
class Food():
    def block():
        cube.color("red")
        for i in range(4):
            cube.goto(x, -x, y, -y)
            cube.begin_fill()
            cube.forward(20)
            cube.right(90)
            cube.end_fill()
"""---------------"""
class Player():
    def move_up():
        player=False
        while player==False:
            for i in range(1):
                t.forward(DISTANCE)
                t.clear()
    def move_left():
        t.speed(0)
        t.left(90)
        t.speed(3)
    def move_right():
        t.speed(0)
        t.right(90)
        t.speed(3)
"""------------"""
collistion_check=Border()
player1=Player()
s.onkey(Player.move_up,"up")
s.onkey(Player.move_left,"left")
s.onkey(Player.move_right,"right")
s.listen()

1 个答案:

答案 0 :(得分:0)

一般来说,您的计划是一场灾难。至于您对随机数的直接问题,此代码存在一个问题:

randint=random.randint
x=random.randint(cube.xcor, 0)
y=random.randint(0,cube.ycor)

语法方面,这应该更像是:

from random import randint
...
x = randint(cube.xcor(), 0)
y = randint(0, cube.ycor())

即。它不清楚为什么你设置变量randint,因为你不使用它,而xcor()ycor()是方法并需要括号。

如果您的目标是在屏幕上随机找到食物,我会选择:

x = randint(cube.xcor()/2 - WIDTH/2, WIDTH/2 - cube.xcor()/2)
y = randint(cube.ycor()/2 - HEIGHT/2, HEIGHT/2 - cube.ycor()/2)

根据需要添加变量以减少冗余。我在代码的其余部分看到的最大问题是这种方法:

def move_up():
        player=False
        while player==False:
            for i in range(1):
                t.forward(DISTANCE)
                t.clear()

不清楚player True如何成为 import { Directive, TemplateRef, ViewContainerRef, NgZone } from "@angular/core"; @Directive({ selector: '[oneTime]', }) export class OneTimeDirective { constructor(template: TemplateRef<any>, container: ViewContainerRef, zone: NgZone) { zone.runOutsideAngular(() => { const view = container.createEmbeddedView(template); setTimeout(() => view.detach()); }) } } 所以一旦你点击向上箭头,你就会进入无限循环。但是,一旦你解决了食物问题,我认为你会专注于此。

相关问题