每当海龟撞击边界时生成随机颜色时,我想在 turtle.Screen()
处写一条提示消息,生成石灰绿色 (50, 205, 50)
。
import random
import turtle
import math
turtle.colormode(255)
# random color generator
r = random.randint(0, 255)
g = random.randint(0, 255)
b - random.randint(0, 255)
rand_color = turtle.color(r, g, b)
# it will update the rgb values set above everytime a condition is satisfied
def rand_c():
return rand_color
# for the prompt message inside turtle.Screen()
sm = turtle.Turtle()
sm.color("White")
sm.hideturtle()
sm.goto(0, 0)
# game loop
while True:
player.forward(speed)
# boundary checking/ putting effects on the border/ player
if player.xcor() > 275 or player.xcor() < -275:
player.setposition(x=0, y=0) # player positioned to (0, 0) when it hits L and R border
winsound.PlaySound("KABOOM", winsound.SND_ASYNC) # plays sound when border is hit
score *= 0 # multiplies the score to zero if the player hits border
rand_c() # change the player color every time it hits the left and right border
# What should be the code here? (condition statement for when turtle generates a lime green color)
if rand_color == (50, 205, 50):
sm.write("Stealth Mode", align="center", font=("Courirer new", 10, "bold"))
sleep(2)
sm.clear()
else:
pass
问题是它每次碰到边界时都会写提示信息,而不是只在海龟随机生成石灰绿色时才写提示信息 (50, 205, 50)
回答1
如果您想要生成新颜色,那么您必须这样做。
# random color generator
def rand_c():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
turtle.color( (r,g,b) )
return r, g, b
rand_color = rand_c()
在你的循环中:
rand_color = rand_c()
if rand_color == (50, 205, 50):
回答2
您可以 store 在全局中使用 @TimRoberts 中的随机颜色,或者您可以询问海龟的当前颜色,即 pencolor()
。但是还有一系列其他问题使您的代码无法正常工作。
首先,一个减号,你的意思是一个等号:
g = random.randint(0, 255)
b - random.randint(0, 255)
接下来,您将从不返回任何内容的方法中分配结果:
rand_color = turtle.color(r, g, b)
或者,可以是:
turtle.color(r, g, b)
rand_color = turtle.pencolor()
或者:
rand_color = (r, g, b)
turtle.color(rand_color)
对解决这些问题和其他问题的代码进行返工:
from turtle import Screen, Turtle
from random import randrange
from time import sleep
# random color generator
# it will update the rgb values set above every time a condition is satisfied
def rand_c():
r = randrange(256)
g = randrange(256)
b = randrange(256)
rand_color = (r, g, b)
player.color(rand_color)
screen = Screen()
screen.colormode(255)
player = Turtle()
# for the prompt message inside turtle.Screen()
prompt = Turtle()
prompt.hideturtle()
while True:
player.forward(player.speed())
# boundary checking/ putting effects on the border/ player
if not -275 <= player.xcor() <= 275:
player.home() # player positioned to (0, 0) when it hits L and R border
# winsound.PlaySound("KABOOM", winsound.SND_ASYNC) # plays sound when border is hit
score = 0 # sets the score to zero if the player hits border
rand_c() # change the player color every time it hits the left and right border
if player.pencolor() == (50, 205, 50):
prompt.write("Stealth Mode", align='center', font=('Courirer new', 10, 'bold'))
sleep(2)
prompt.clear()
screen.mainloop() # never reached