随机定位圆点击游戏

2024-03-29 15:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我对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)

我一直在想的主要问题是:

  • 我怎样才能使这些圆彼此离得更远?它们重叠 很多时候,我想避免这种情况。

  • 我怎样才能让这些圆立即产生而不是必须要 绘制?


Tags: orimport游戏玩家randomgreenbluered
1条回答
网友
1楼 · 发布于 2024-03-29 15:45:14

How can I make the circles spawn further from each other?

我们可以跟踪已经创建的圆,并确保它们的中心彼此之间至少有一个直径的距离。你现在的圆形布局逻辑太复杂了,而且有问题。让我们试着简化它,确保在窗口内完全画出圆。在

How can I make the circles spawn instantly rather than having to be drawn?

我们可以给它们盖章,而不是画画。不过,既然你画的圆太少了,我们可以把每个圆都画成乌龟。这使得确定是否单击了一个圆并删除该圆变得更简单。我添加了代码,供您展开,它可以删除您单击的任何圆:

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()

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

enter image description here

相关问题 更多 >