在我的任务要求中, 1.在100和200之间绘制一个随机的正方形。 2.正方形的宽度和高度必须为10。 3.让用户输入发射速度和发射角度。 4.从原点到正方形开火。但炮弹必须画出抛物线。 5.如果贝壳碰到一个正方形,则结束程序,否则返回数字3。
但是问题是5号。我尝试将5号具体化,但是没有用。 请看一下我的代码。
import turtle as t
import math
import random
import sys
def square(): //function that make the square
for i in range(4):
t.forward(10)
t.left(90)
t.forward(500)
t.goto(0,0)
d1 = random.randint(100,200) //choose the random distance between 100 to 200
t.up()
t.forward(d1)
t.down()
square() //satisfy condition 1
t.up()
t.goto(0,0)
t.down()
def fire(): //function that fire a shell to a square direction.
x = 0
y = 0
gameover = False
speed = int(input("speed:")) //satisfy condition 3
angle = int(input("angle:")) //satisfy condition 3
vx = speed * math.cos(angle * 3.14/180.0)
vy = speed * math.sin(angle * 3.14/180.0)
while t.ycor()>=0: // until y becomes negative. and satisfy condition 4
vx = vx
vy = vy - 10
x = x + vx
y = y + vy
t.goto(x,y)
x_pos = t.xcor() // save x-coordinate to x_pos
y_pos = t.ycor() // save y-coordinate to y_pos
if d1<=x_pos<=d1+10 and 0 <= y_pos <= 10: // if x_pos and y_pos are within range, save gameover to True and break
gameover = True
break
if gameover == True: // trying to satisfy number 5
exit()
else: // if a shell not hit a square repeat the fire.
t.up()
t.home()
t.down()
fire()
fire()
请告诉我如何体现5号,或者告诉我我做错了什么。
答案 0 :(得分:0)
与其在后续尝试中递归调用fire()
,不如在while not gameover:
中使用fire()
循环并相应地调整其余代码,效果更好。在下面的代码重写中,我使用了这样的循环,还使用了乌龟自己的图形numinput()
函数而不是控制台:
from turtle import Screen, Turtle
from math import radians, sin, cos
from random import randint
def square(t):
''' function that make the square '''
for _ in range(4):
t.forward(10)
t.left(90)
def fire(t):
''' function that fire a shell to a square direction '''
gameover = False
speed = None
angle = None
while not gameover:
t.up()
t.home()
t.down()
speed = screen.numinput("Angry Turtle", "Speed:", default=speed, minval=1, maxval=1000) # satisfy condition 3
if speed is None:
continue
angle = screen.numinput("Angry Turtle", "Angle (in degrees):", default=angle, minval=1, maxval=89) # satisfy condition 3
if angle is None:
continue
vx = speed * cos(radians(angle))
vy = speed * sin(radians(angle))
x = 0
y = 0
while t.ycor() >= 0: # until y becomes negative; satisfy condition 4
vy -= 10
x += vx
y += vy
t.goto(x, y)
x_pos, y_pos = t.position()
# if x_pos and y_pos are within range, set gameover to True and break loop
if d1 <= x_pos <= d1 + 10 and 0 <= y_pos <= 10:
gameover = True
break
screen = Screen()
screen.title("Angry Turtle")
turtle = Turtle()
turtle.shape("turtle")
turtle.forward(screen.window_width() // 2)
turtle.home()
d1 = randint(100, 200) # choose the random distance between 100 to 200
turtle.up()
turtle.forward(d1)
turtle.down()
square(turtle) # satisfy condition 1
fire(turtle)
但是,以上设计将用户困在“如果您想退出,赢得游戏”的情况下,您可能想给他们提供更好的退出程序的方法。