好吧,我的目标是创建一个游戏。
虽然用户的分数小于10(最初设置为0),但我希望在圆圈周围的内接正方形中单击时,在分数中添加一个0到5之间的随机数。
现在,当我出于某种原因点击时,正在绘制新的圆圈。如果在圆中单击它,我希望该圆不被绘制,并在随机位置绘制一个和一个新的圆。
from graphics import *
import random
def main():
win= GraphWin("lab12",500,500)
score=0
while score < 10:
x=random.randint(0,450)
y=random.randint(0,450)
centa=Point(x,y)
c=Circle(centa,50)
c.setFill(color_rgb(200,0,0))
c.draw(win)
mouseClick2=win.getMouse()
if mouseClick2.y >= y-50 and mouseClick2.y <= y +50 and mouseClick2.x >= x-50 and mouseClick2.x <= x+50:
score=score + random.randint(0,5)
c.undraw()
x=random.randint(0,450)
y=random.randint(0,450)
centa=Point(x,y)
c=Circle(centa,50)
c.setFill(color_rgb(200,0,0))
c.draw(win)
else:
score=score+0
print "you won"
print "your final score is, "
main()
与其试图清除圆,不如简单地平移和移动坐标?
我用以下做到了
def draw_circle(win, c=None):
x=random.randint(0,450)
y=random.randint(0,450)
if c is None:
centa=Point(x,y)
c = Circle(centa,50)
c.setFill(color_rgb(200,0,0))
c.draw(win)
else:
p1 = c.p1
x_dif = (p1.x - x) * -1
y_dif = (p1.y - y) * -1
c.move(x_dif, y_dif)
return (c, x, y)
基本的翻译算法是newX = (x1-x2) * -1
和newY = (y1-y2) * -1
。我们交换符号是因为负值表示新的x坐标大于旧坐标,而应该向右移动(而不是向左移动,这是由移动指示的)。
这会将您的主循环更改为以下内容:
def main():
win= GraphWin("lab12",500,500)
score=0
c,x,y = draw_circle(win)
while score < 10:
mouseClick2=win.getMouse()
if mouseClick2.y >= y-50 and mouseClick2.y <= y +50 and mouseClick2.x >= x-50 and mouseClick2.x <= x+50:
score=score + random.randint(0,5)
c,x,y = draw_circle(win, c)
print "you won"
print "your final score is, {0}".format(score)
请记住,在python中,您可以unpack
将元组/数组/生成器添加到一组变量上,前提是您的变量数量与所述元组/阵列/生成器的大小相匹配。
例如
x,y,z = 5,10,20 # works
x,y = 5,10,20 # does not work
x,y,z = 5,10 # does not work
哦,我把你的分数加到了打印声明中!