Question

In: Computer Science

import random import turtle def isInScreen(win,turt): leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2...

import random
import turtle

def isInScreen(win,turt):
leftBound = -win.window_width() / 2
rightBound = win.window_width() / 2
topBound = win.window_height() / 2
bottomBound = -win.window_height() / 2

turtleX = turt.xcor()
turtleY = turt.ycor()

stillIn = True
if turtleX > rightBound or turtleX < leftBound:
stillIn = False
if turtleY > topBound or turtleY < bottomBound:
stillIn = False

return stillIn

def main():
wn = turtle.Screen()
# Define your turtles here
june = turtle.Turtle()


june.shape('turtle')
while isInScreen(wn,june):
coin = random.randrange(0, 2)
if coin == 0:
june.left(90)
else:
june.right(90)

june.forward(50)

wn.exitonclick()

main()

  1. Following the process in the previous unit’s assignment, write a function to randomly move a turtle. The function should have at least one parameter, the turtle to move. Call this function in your main program instead of the code that is already there. If you do this correctly, your program will behave the same.
  2. Create a second turtle, make it a different color, and start it at a different location than the current one. The location should be 100 units away, either horizontally or vertically.
  3. The second turtle should move randomly 5 times for every time the first turtle does. It should also move 1/5 the distance as the original turtle each time. This is where having a function with proper parameters comes in handy.
  4. After the loop, write a message, in the center of the window, indicating which turtle was higher up. Use the turtle that is higher (more toward the top of the screen) to do the writing. Be sure your message specifies the turtle. See the write() function in the turtle module for writing text messages in the window.
  5. Once your program works the way you want, rewrite the if statement in the function isInScreen, so it still implements the same logic, but does it a different way. For example, maybe you can use an elif, or maybe you can write several statements and eliminate the use of or. You should probably do this step last, or else if you make a mistake, you'll never be able to debug the rest of your code.

Solutions

Expert Solution

Hi. I have answered a similar question before. Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code

'''
File: <filename>
Author: <your name>
Description: This program creates two turtles, move them randomly until one of them goes out of window
'''
import random
import turtle


def isInScreen(win, turt):
    '''
    this method checks if turt is inside bounds of win
    :param win: turtle screen
    :param turt: turtle object
    :return: True if inside, False if not
    '''
    leftBound = -win.window_width() / 2
    rightBound = win.window_width() / 2
    topBound = win.window_height() / 2
    bottomBound = -win.window_height() / 2
    turtleX = turt.xcor()
    turtleY = turt.ycor()
    stillIn = True
    # modified the if statement to use a different approach. (does the required task in a single step)
    if turtleX > rightBound or turtleX < leftBound or turtleY > topBound or turtleY < bottomBound:
        stillIn = False
    return stillIn


def move(turt, distance):
    '''
    This method moves turtle turt in distance spaces randomly
    :param turt: turtle object
    :param distance: distance to be moved
    :return: nothing
    '''
    # randomly turning left or right 90 degrees and moving forward distance spaces
    coin = random.randrange(0, 2)
    if coin == 0:
        turt.left(90)
    else:
        turt.right(90)
    turt.forward(distance)


def main():
    '''
    this is where execution starts. the method creates two turtles, move them continiously until
    one of them goes outside the window. first turtle moves greater distance, but slowly,
    second turtle moves quickly, but using 1/5th of the speed of first
    :return: nothing
    '''
    wn = turtle.Screen()
    june = turtle.Turtle()  # first turtle
    june.shape('turtle')
    june.speed(0)  # maximum speed
    tim = turtle.Turtle()  # creating second turtle
    tim.shape('turtle')
    tim.color('red')  # red color
    tim.up()  # pen up
    tim.goto(100, 0)  # placing 100 spaces right to june
    tim.down()  # pen down
    tim.speed(0)  # max speed
    # looping until june or tim goes out of bounds
    while isInScreen(wn, june) and isInScreen(wn, tim):
        move(june, 50)  # moving june 50 spaces
        for i in range(5):  # looping for 5 times
            move(tim, 10)  # moving tim 10 spaces (1/5th of june's distance)
    # after while loop, checking which turtle is up high
    if june.pos()[1] > tim.pos()[1]:
        june.up()  # pen up
        june.goto(0, 0)  # moving to center
        # writing a message saying that the first turtle was up high
        june.write("First turtle was higher up!", align='center', font=("Arial", 16, "bold"))
    else:
        # doing the same with tim (second turtle)
        tim.up()
        tim.goto(0, 0)
        tim.write("Second turtle was higher up!", align='center', font=("Arial", 16, "bold"))
    wn.exitonclick()


main()

#output screenshots


Related Solutions

import random # define functions def rollDice(): # function returns a random number between 1 and...
import random # define functions def rollDice(): # function returns a random number between 1 and 6 def userWon(t1, t2): # function accepts player total and computer total # function returns true if player wins # function returns false if computer wins def main(): # each player rolls two Dice player = rollDice() + rollDice() computer = rollDice() + rollDice() # ask the player if they want to roll again again = int(input("Please enter 1 to roll again. Enter 2...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a,...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a, b):        self.a = a        self.b = b    def add(self):        return self.a + self.b    def mul(self):        return self.a * self.b    def div(self):        return self.a / self.b    def sub(self):        return self.a - self.b def playQuiz():    print("0. Exit")    print("1. Add")    print("2. Subtraction")    print("3. Multiplication")    print("4. Division")...
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits.
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits = '0b' + bits     value = int(bits, 2)     return value.to_bytes((value.bit_length() + 7) // 8, 'big').decode() def writeMessageToRedChannel(file, message):     image = Image.open(file)     width, height = image.size     messageBits = stringToBits(message)     messageBitCounter = 0     y = 0     while y < height:         x = 0         while x < width:             r, g, b, a = image.getpixel((x, y))             print("writeMessageToRedChannel: Reading pixel %d, %d - Original values (%d, %d, %d, %d)"...
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(")...
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(") " + entry) return int(input(question)) plz explain this code
I need to write these three functions in Python using turtle module. def line(t, coord1, coord2)...
I need to write these three functions in Python using turtle module. def line(t, coord1, coord2) t is a turtle object passed in coord1 and coord2 are 2-element lists that represent x, y coordinates draws a line from coord1 to cord2 def poly(t, *coords) t is a turtle object passed in *coords is any number of x, y coordinates each as a 2-element list draws a polygon based on coords (will close off polygon by drawing a line from last...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path):...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path): """ Retrieve list of students and their expected grade from file, generate a sampled test grade for each student drawn from a Gaussian distribution defined by the student expected grade as mean, and the given standard deviation. If the sample is higher than 100, re-sample. If the sample is lower than 0 or 5 standard deviations below mean, re-sample Write the list of student...
Can somebody describe what this following code does step by step. import turtle turtle.penup() x =...
Can somebody describe what this following code does step by step. import turtle turtle.penup() x = int(input("Enter x coordinate of top-left corner: ")) y = int(input("Enter y coordinate of top-left corner: ")) side = int(input("Enter side of the largest square: ")) if side >= 100: gap = int(input("Enter gap between squares: ")) if gap < side: turtle.goto(x,y) turtle.pendown() while True: for i in range(4): turtle.forward(side) turtle.right(90) side -=gap turtle.penup() x += gap y -= gap turtle.goto(x,y) turtle.pendown() if side<0: exit(1)
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()     return(d) print(a["Date"]) print("3/14/2012".get()) How to write the "get" function (without any imput), to convery the format ""3/14/2012" to the format "2012-03-14", by simply using "3/14/2012".get() ?
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def take_e(n, gen):     return [elem for (i, elem) in enumerate(gen) if i < n] def take_zc(n, gen):     return [elem for (i, elem) in zip(count(), gen) if i < n] FIBONACCI UNBOUNDED: def fibonacci_unbounded():     """     Unbounded Fibonacci numbers generator     """     (a, b) = (0, 1)     while True:         # return a         yield a         (a, b) = (b, a + b) SUPPOSED TO RUN THIS TO ASSIST WITH...
Please fix all the errors in this Python program. import math def solve(a, b, c): """...
Please fix all the errors in this Python program. import math def solve(a, b, c): """ Calculate solution to quadratic equation and return @param coefficients a,b,class @return either 2 roots, 1 root, or None """ #@TODO - Fix this code to handle special cases d = b ** 2 - 4 * a * c disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b - disc) / (2 * a) return root1, root2 if...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT