【问题标题】:randomly positioned circle clicking game随机定位的圆圈点击游戏
【发布时间】:2018-05-27 03:41:08
【问题描述】:

所以我对 python 还是很陌生,并试图通过制作小项目来学习。 我正在制作的游戏旨在通过创建一堆随机圆圈来测试您的鼠标准确性,玩家要在给定的时间内单击这些圆圈。在游戏结束时,它应该告诉玩家他们的得分,以及他们有多少次点击错误。

我一直在使用乌龟来尝试这样做,但我被卡住了:

import turtle
import random
t = turtle.Pen()

win = turtle.Screen()
win.bgcolor("lightgreen")
win.title("clicky")


def mycircle(red, green, blue):
    t.color(red, green, blue)
    t.begin_fill()
    x = random.randint(10,50)
    t.circle(x)
    t.end_fill()
    t.up()
    y = random.randint(0,360)
    t.seth(y) 
    if t.xcor() < -300 or t.xcor() > 300:
        t.goto(0, 0)
    elif t.ycor() < -300 or t.ycor() > 300:
        t.goto(0, 0)
    z = random.randint(0,100)
    t.forward(z)
    t.down()

for i in range(0, 20):
    a = random.randint(0,100)/100.0
    b = random.randint(0,100)/100.0
    c = random.randint(0,100)/100.0
    mycircle(a, b, c)

我一直试图弄清楚的主要问题是:

  • 如何使生成的圆圈彼此远离?它们重叠 经常发生,我希望避免这种情况。

  • 如何让圆圈立即生成而不是必须 画了吗?

【问题讨论】:

    标签: python python-3.x turtle-graphics


    【解决方案1】:

    我怎样才能让圈子彼此离得更远?

    我们可以跟踪已经创建的圆,并确保它们的中心彼此之间至少相差一个直径。您当前的圆圈放置逻辑太复杂且有缺陷。让我们尝试简化它,并确保圆圈完全绘制在窗口内。

    我怎样才能让圆圈立即产生而不是必须 画了吗?

    我们可以标记它们而不是绘制它们。但是,由于您绘制的圆圈很少,我们可以将每个圆圈都设为乌龟。这样可以更简单地确定您是否单击了一个圆圈并删除该圆圈。我添加了代码,供您扩展,删除您点击的任何圆圈:

    from turtle import Turtle, Screen
    from random import random, randint
    
    CURSOR_SIZE = 20
    
    def my_circle(color):
        radius = randint(10, 50)
    
        circle = Turtle('circle', visible=False)
        circle.shapesize(radius / CURSOR_SIZE)
        circle.color(color)
        circle.penup()
    
        while True:
            nx = randint(2 * radius - width // 2, width // 2 - radius * 2)
            ny = randint(2 * radius - height // 2, height // 2 - radius * 2)
    
            circle.goto(nx, ny)
    
            for other_radius, other_circle in circles:
                if circle.distance(other_circle) < 2 * max(radius, other_radius):
                    break  # too close, try again
            else:  # no break
                break
    
        circle.showturtle()
    
        circle.onclick(lambda x, y, t=circle: t.hideturtle())  # expand this into a complete function
    
        return radius, circle
    
    screen = Screen()
    screen.bgcolor("lightgreen")
    screen.title("clicky")
    
    width, height = screen.window_width(), screen.window_height()
    
    circles = []
    
    for _ in range(0, 20):
        rgb = (random(), random(), random())
    
        circles.append(my_circle(rgb))
    
    screen.mainloop()
    

    您需要解决的一个问题是确保您的圆圈颜色与您的背景颜色不太相似(或相同),否则您将寻找一个不可见的圆圈。此外,如果需要,我们或许可以进一步加快绘制圆的过程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2019-01-17
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多