简体   繁体   English

如何为每次出现的每个球选择随机颜色?

[英]How to choose a random color for each ball that will show up every time?

This is a simple python "flappy bird" game.这是一款简单的 python“飞鸟”游戏。 I am struggling with choosing a random color for each ball that will show up every time — how can I do it?我正在努力为每次出现的每个球选择一种随机颜色——我该怎么做?

from random import *
from turtle import *
from freegames import vector

bird = vector(0,0)
balls=[]

def tap (x, y):
    """Move bird up in response to screen tap"""
    up=vector(0,30)
    bird.move(up)
def inside(point):
     """Return true if point on screen """
     return -200 < point.x< 200 and -200 < point.y < 200

def draw(alive):
    """Draw screen objects."""
    clear()

    goto(bird.x, bird.y)
    if alive:
      dot(10,'green')
    else:
      dot(10,'red')

    for ball in balls:
      goto(ball.x, ball.y)
      dot(20,'black')

    update()

def move():
        """Update object positions."""
        bird.y -= 5

    for ball in balls:
      ball.x -= 3

    if randrange(10)==0:
      y=randrange(-199,199)
      ball=vector(199,y)
      balls.append(ball)

    while len(balls) >0 and not inside(balls[0]):
      balls.pop(0)

    draw (True)
    ontimer (move,50)

    if not inside(bird):
      draw(False)
      return

    for ball in balls:
      if abs(ball-bird)< 15:
      draw(False)
      return


setup(420,420,370,0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()

According to the turtle docs dot will accept either a colorstring or an rgb value.根据turtle docs dot 将接受颜色字符串或 rgb 值。 To supply an rgb value to dot you must use the syntax dot(size, r, g, b) to specify the color.要为 dot 提供 rgb 值,您必须使用语法dot(size, r, g, b)来指定颜色。 To generate a random color with random to fill these values we should create a function.要生成随机颜色来填充这些值,我们应该创建一个 function。

# Create a random color tuple
import random
import turtle
turtle.colormode(255)
def randomColor():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

# Now we can use this with dot like so
# Note we are using * to unpack the random color for dot()
turtle.dot(10, *randomColor())

There are at least three ways you can generate random color values in Python turtle:至少有三种方法可以在 Python turtle 中生成随机颜色值:

>>> import turtle
>>> from random import random
>>> turtle.colormode()  # confirm the default
>>> 1.0
>>> turtle.dot(20, (random(), random(), random()))

Another way, as @Alec Soronow points out is to change the default color mode and work with integer color values:正如@Alec Soronow 指出的那样,另一种方法是更改默认颜色模式并使用 integer 颜色值:

>>> from random import randint
>>> turtle.colormode(255)
>>> turtle.dot(20, (randint(0, 255), randint(0, 255), randint(0, 255)))

Since dot() can also accept hex color strings, eg '#a5b8af' , we can also do:由于dot()也可以接受十六进制颜色字符串,例如'#a5b8af' ,我们也可以这样做:

>>> hex_color = '#' + hex(randint(0, 256**3 - 1)).replace('0x', '').zfill(6)
>>> turtle.dot(20, hex_color)

That gets your random color, but doesn't solve your problem of having the ball remember its color.这会得到你的随机颜色,但不能解决让球记住它的颜色的问题。 You could approach this by storing in balls tuples of the vector and color, and then when you acces it, you do something like:您可以通过将向量颜色的balls元组存储在球中来解决此问题,然后当您访问它时,您可以执行以下操作:

for ball, color in balls:
    # whatever

but I'm going to suggest a different approach, which is to make your bird and balls all be turtles instead of vectors.但我将建议一种不同的方法,即让你的鸟和球都成为海龟而不是向量。 Something like:就像是:

from random import random, randrange
from turtle import Screen, Turtle

def tap(x, y):
    """ Move bird up in response to screen tap """

    bird.forward(30)

def inside(entity):
    """ Return true if point on screen """

    x, y = entity.position()

    return -200 < x < 200 and -200 < y < 200

balls = []
spare_balls = []

def move():
    """ Update object positions """

    global balls

    if inside(bird):
        for ball in balls:
            if ball.distance(bird) < 15:
                bird.color('red')
                screen.update()
                return
    else:
        bird.color('red')
        screen.update()
        return

    bird.backward(5)

    for ball in balls:
        ball.forward(3)

    inside_balls = []

    for ball in balls:
        if inside(ball):
            inside_balls.append(ball)
        else:
            ball.hideturtle()
            spare_balls.append(ball)

    balls = inside_balls

    if randrange(10) == 0:
        if spare_balls:
            ball = spare_balls.pop()
        else:
            ball = Turtle(shape='circle', visible=False)
            ball.penup()
            ball.setheading(180)

        ball.setposition(199, randrange(-199, 199))
        ball.color(random(), random(), random())
        balls.append(ball)
        ball.showturtle()

    screen.update()
    screen.ontimer(move, 50)

screen = Screen()
screen.setup(420, 420, 370, 0)
screen.tracer(False)

bird = Turtle()
bird.shape('turtle')
bird.color('green')
bird.penup()
bird.setheading(90)

screen.onclick(tap)

move()

screen.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM