首页 > > 详细

data留学生辅导、Java,c++程序设计调试、Python语言讲解解析Java程序|解析C/C++编程

Lab 4: Unique turtles
In this week's lab, you will create a collage of "turtle tracks" that are left as multiple turtles with
unique shapes and colors move from top-to-bottom across the canvas (like footprints left in the
snow). The animation of the turtles drawing the collage resembles a colorful version of code rain
from The Matrix.
The goals this week are to:
● Learn how to use objects using the familiar turtle module.
● Practice using return values and multiple assignment.
● Practice conditionals.
● Practice reading code documentation to discover new functions that are needed to
complete a task.
● Lab 4: Unique turtles
○ Tasks
■ L1. The setup
■ L2. Make Screen and Turtle objects
■ L2a: Create a Screen object
■ L2b: Make the screen appear
■ L2c: Create one Turtle object
■ L2d: Make a few Turtle objects
■ L3: Reset the position of each turtle
■ L3a: Write the reset_turtle function
■ L3b: In main, place your turtles on the starting line
■ L4: Turtle tracks
■ L5: Make your collage
■ L6: Scorekeeper: A turtle with a different job
■ L6a: Keeping count of strides
■ L6b: Make a function to write text to the screen
■ L6c: Have a new Turtle write the stride count on-screen
○ Get started with the project
- © 2020 Oliver Layton
Tasks
L1. The setup
Create a Lab04 folder on your computer where you store CS151 projects and labs, hopefully
somewhere that is backed up (e.g. in Dropbox, Google Drive, Microsoft One Drive, etc.)
Open VS Code. Create a new Python source code file calledlab4.py. Import the random and
turtle modules.
Open up a Terminal (e.g. Control+` in VS Code) and change the directory (cd) to the Lab04
folder.
L2. Make Screen and Turtle objects
This week, we will use objects to divide up the labor of creating a canvas and drawing shapes
with turtle. The division of labor occurs among 2 types of objects:
1. Screen: You will create a Screen object that represents the canvas (pop-up window in
which each the turtle draws stuff). This object will allow you to store and change
information relating to the canvas window ("screen") (i.e. its height and width, whether it
stays up waiting for you to click, its background color, etc.)
2. Turtle: You can now create more than one turtle that draws on the screen at once! Each
turtle is a different object that you create. You will control each independently and
customize each one with unique properties: each can have different pen widths, colors,
shapes, and locations.
In this task, you will create an object for the screen and several different turtles.
L2a: Create a Screen object
Write a function in lab4.py that has the following docstring:
It may be helpful to have class notes and the turtle documentation open as you work. Your
function should accomplish the following:
● Create a Screen object.
● Set the height and width of the screen.
● Set the background color.
● Set the title
● Return the screen object that you created.
Reminder: With objects, you call functions ON THEM, not on the turtle module (e.g.
screen.setup(width, height), not:
turtle.setup(width, height), assuming your Screen object is called screen).
L2b: Make the screen appear
Make a main function in lab4.py. In it, call your make_screen function and remember to assign a
variable to the Screen object that make_screen returns. For example,
screen = make_screen( ). You can pass in whatever
parameter values that you like when you call make_screen. Here are some suggestions:
● A good starting point for the screen size is 500 pixels (width) x 400 pixels (height). You
may change this later based on your preferences.
● Give the window a title string. Again, you can change this later.
● You can leave the background color its default value (black) or change it.
Call the exitonclick method on your Screen object at the end of your main function.
Create the usual conditional statement for main code at the bottom of lab4.py (i.e.
if __name__ == '__main__':). Call main in it.
Running lab4.py should give you a blank window like this, with your custom size and title (my
background color is black and I used the Screen title "Turtle Tracks"):
Spend a moment to play with your title, window size, and background color to get a sense of
how each property controls how the screen looks.
L2c: Create one Turtle object
Write a function that creates a single Turtle object that will appear on the canvas (represented
by your Screen object) with the following docstring:
Your function should do the following (again, it probably will be helpful to look at lecture notes
and the turtle documentation):
● Create one Turtle object (calling your make_turtle function multiple times later on will
allow you to create multiple, uniquely customized turtles).
● Set the shape of the turtle object based on the parameter that you pass in.
● Set the pen color of the turtle object based on the parameter that you pass in.
● Set the turtle object's pen in the ‘up’ mode. We want each turtle to leave their "tracks" as
they move, not a connected line.
● Return the Turtle object that you created.
Reminder: You should NOT be typing turtle. except for the first line where you create the
Turtle object! Instead, call methods on your turtle object.
L2d: Make a few Turtle objects
After creating your Screen object in main, but before you call exitonclick, call make_turtle 3
times. This will create 3 turtles that show up on your canvas. Like you did with make_screen,
remember to assign the returned object from each make_turtle call to a distinct variable so that
you can control each one later (e.g. turt1, turt2, turt3).
Move your first turtle to (x, y) = (-200, 0) by calling the goto method on it, the second turtle to
(-50, -50), and the third turtle to (100, 100) (by calling the goto method on each of them).
Running your code should give you something that looks like:
Take a moment to have some fun playing with shapes and colors of each turtle. What do each
of the built-in turtle shapes look like?
L3: Reset the position of each turtle
Let's start to create a colorful collage of the "tracks" left behind by each turtle as they move from
top-to-bottom across the screen. First, you need to place each turtle in their starting position at
the top of the screen.
L3a: Write the reset_turtle function
Write your function with the following signature:
def reset_turtle(turt, screen_width, screen_height):
Your function should do the following with the Turtle object passed in as a parameter (turt):
● Place the turtle at a random position along the top edge of the screen (see hint below).
● Reset the turtle's heading so that it is facing south (Hint: if you forget the heading angle
convention, check out the documentation for setheading).
● Set the turtle's pen color to a random RGB tuple, each component ranging between 0 to
1 (Remember the parentheses).
Hint: The center of the screen is position (0, 0).
The x-coordinate of the left edge of the screen is -screen_width/2 and that of the right edge of
the screen is screen_width/2.
The y-coordinate of the bottom edge of the screen is -screen_height/2 and that of the top edge
of the screen is screen_height/2.
L3b: In main, place your turtles on the starting line
Call your reset_turtle function 3 times in main, once on each of the 3 turtles. You should get
something that looks like this (your positions will be different due to randomness):
Tip: If one or more of your turtles are not showing up, try placing them 10 pixels or so below the
top of the screen (e.g. screen_height/2 - 10). It is possible that they are up there, but just are not
visible because they are slightly off-screen.
L4: Turtle tracks
Write a function with the following signature that should move the turtle turt forward by distance
and then stamp to leave a track.
def move_and_stamp(turt, distance):
In main, call move_and_stamp once on each turtle. Have your 3 turtles move different
distances: 40, 30, 20, respectively. You should see something that looks like:
L5: Make your collage
In main, repeat the process of moving all 3 turtles forward and having them leave a stamp 1000
times. If any of the turtles moves off the bottom of the screen (the y coordinate is too small), call
your reset_turtle function on that turtle.
If everything is working when you run your code, you should see a collage like the one at the top
of this page being created!
Once you get the collage working, have some fun and try:
● Speeding up the animations. Call the speed method on your Turtle object when you
make it.
● Add some variety to the distance traveled by each Turtle during each movement:
randomly move each turtle between 0 and 10 units farther than the default distance.
L6: Scorekeeper: A turtle with a different job
In this last task, you will make another Turtle object — but it will have the unique job of writing
text on the screen (rather than leaving tracks or drawing shapes).
L6a: Keeping count of strides
In main, define a counter variable that starts at 0 and gets incremented by 1 whenever any one
of your turtles completes a stride from top-to-bottom of the screen and gets reset. In other
words, this variable should keep track of how many times you call reset_turtle.
I suggest printing out the variable when you update it (i.e. add one to it) to help you debug / help
convince yourself that your code is working.
L6b: Make a function to write text to the screen
This function will have a Turtle object write your current stride count on the screen.
Make a function with the following signature:
def writeNumStrides(turt, numStrides):
It should do three things:
● Call the clear method on the turt Turtle object. This will have the turtle erase the previous
number to prepare to write the current one. For example, if numStrides was previously 1
(and 1 is shown on the screen), clear will erase that so that a new number (e.g. 2) can
be written.
● Copy and paste the line:
turt.write(numStrides, font=('Arial', 30, 'normal')).
This will have the turtle write the number on the screen in a nice, large font.
● Call the hideturtle method on the Turtle object. This will make the turtle shape go
invisible so that it does not block the number it just wrote!
L6c: Have a new Turtle write the stride count on-screen
In main, create one new Turtle object — the shape does not matter, but I suggest using a white
pen color if you are keeping the default screen background color of black (you want to be able
to see the text on your background color!).
Place the new Turtle object somewhere on the screen (not the top). For example, I placed mine
in the middle, 10 pixels higher than the bottom of the screen.
Whenever you call reset_turtle and increment your stride counter (i.e. assign it to one more than
its current value), call the writeNumStrides function to have the latest stride count always
appear on the screen.
Test out your collage with the new counter. You should see the stride count on screen and it
should increase by 1 whenever a turtle reaches the bottom of the screen.
Get started with the project
Once you are done with each of the lab tasks, you may start on the project.
© 2020 Oliver Layton
Project 4: Turtle race
In this project, you will practice creating objects that have unique roles and properties. You will
be making a scene where two turtles are racing each other in a race course that you design.
Aside from the Screen object, you will create different Turtle objects, each of whom perform
different roles:
● Race on the track.
● Draw the background scene (showing the race track, the audience, etc.).
● Show the score — how many laps each turtle completes (there are two Turtle "score
keepers", one per racer).
Extension points are awarded for complex scenes, especially those that show me that you can
integrate concepts from lecture into making your scenes and take things to the next level!
Tasks
● Project 4: Turtle race
○ Tasks
■ 0. Design your race course
■ 1. Create object_shapelib.py
■ 1a. goto function
■ 1b. Create functions that you need to draw your race track scene
■ 1c. draw_race_scene
■ 1d. Test your race track scene
■ 2. Create race.py
■ 2a. Copy over make_turtle from lab into race.py
■ 2b. Make a main function
■ 2c. Create the move_turtle function
■ 2d. Move your racing turtles around the track
■ 3. Race!
■ 3a. Randomly jitter each racing turtle's speed
■ 3b. Keep score
○ Check reproducibility
○ Extensions
○ Submission checklist
- © 2020 Oliver Layton
0. Design your race course
Decide on the shape of your race course. It doesn't need to be fancy. Keep in mind that your
turtles will need to be able to go around the race course multiple times (i.e. to complete "laps").
Some ideas are:
● circular (simplest and recommended)
● linear (e.g. back-and-forth either side of the screen)
● around a simple shape (e.g. square, diamond, etc.)
1. Create object_shapelib.py
Just like better_shapelib from last week, object_shapelib.py will contain all your
functions that draw shapes and the race scene. You're welcome to add as much
complexity as you would like, but minimally it should contain the following functions.
For full credit, all these functions should only use a Turtle object to do the
drawing. I should not see turtle. anywhere, except on the line where you create
your Turtle object!
1a. goto function
Copy-and-paste the goto function that you have from better_shapelib, and update it to
have the function signature:
def goto(turt, x, y, heading=0):
Do the following:
● Update the code so that it entirely consists of method calls done on the Turtle
object turt.
● If you previously did not have a parameter for heading, make sure that you set
turt's heading to the parameter heading.
1b. Create functions that you need to draw your race track scene
The ones you need depend on your race track design and your concept for your race
scene. For example, if you were using a circular track, you might use a circle function to
draw the racing lanes (e.g. their outlines, fill, inner and outer lane dividers, road
markers, etc.):
def circle(turt, x, y, radius, penWidth=3, fill=True, fillColor='brown'):
Keep it simple! You can always add complexity later. At minimum, each of your shape
functions should have:
● A parameter for the Turtle object that draws your shape (e.g. turt above).
● Position parameters (e.g. x and y).
● Keyword arguments to control the appearance (e.g. penWidth above).
Feel free to copy-and-paste and adapt code from previous projects!
1c. draw_race_scene
This is the function that should draw your race track scene. It does NOT need to have
(x, y, scale) parameters — I suggest only putting in the work to do this if you plan to
take advantage of repositioning and scaling your scene as part of a larger extension.
Here is an overview of what the draw_race_scene function should do:
● Create a Turtle object that will draw your scene.
● Call your functions from Task 1b to draw the lanes/course in which your two
turtles will race one another.
● Customize the rest of the scene as much as you'd like (e.g. add bleachers, a
crowd of fans, trees, etc.). You can skip this for now until you get the rest of the
project working.
1d. Test your race track scene
Copy-and-paste your make_screen function from lab into object_shapelib.py.
Add main code to if __name__ == '__main__': in object_shapelib.py to test out your race
scene. It should make a Screen object and draw your race scene.
Run object_shapelib.py to produce your race scene.
Take a screenshot —
This is Required Image 1 in your project report.
2. Create race.py
This file will place your turtles in their racing lanes and have them race. The following
subtasks walk you through the general setup.
2a. Copy over make_turtle from lab into race.py
Call this function when you need to create a Turtle object.
2b. Make a main function
Your function should:
● Make a Screen object
● Draw your race scene
● Create 4 Turtle objects: 2 racing turtles and 2 "score keepers" (they will show
how many laps racing Turtle 1 and Turtle 2 complete, respectively).
● Place the racing turtles at the "starting line" of your race track (where ever you
decide that to be). Make sure they are facing the right way to start racing on your
track!
● The placement of the two score keeper turtles is up to you.
Important notes:
● Make sure that the two racing turtles look distinct (e.g. different colors, shapes,
etc.).
● The score keeper turtles should have a color that will make their written scores
readable against your background color.
Add a if __name__ == '__main__': statement in race.py that calls your main function.
If you run your code now, you should see your racing scene drawn on the screen and
your two racing turtles should show up at the starting line in their respective lanes.
2c. Create the move_turtle function
Each racing turtle will move at a different speed, which means that you move them
speed units on each time step of your simulation (e.g. in a loop coming up later). The
move_turtle function should have one of your turtles (turt) take one "step" (the size of
step is speed) and should have a signature that looks like:
def move_turtle(turt, speed):
'''Moves the `Turtle` object `turt` `speed` units '''
Feel free to customize the parameters to suit your race course concept.
Hint (if using a circular course): The turtle circle method has a keyword argument that
allows you to specify how much of a circle (angle) that you want to move around.
2d. Move your racing turtles around the track
After the code that you have already written in main, move each of the racing turtles
1000 times. Give Turtle 1 a speed of 5 and Turtle 2 a speed of 4.9.
If you run your code, you should see each turtle move around the track (not deviating
from it). Turtle 1 should complete laps faster than Turtle 2.
Hint: If your race course requires the turtles or go back-and-forth or turn corners, you
will need to change their heading after they move a certain distance or reach the end of
the screen.
3. Race!
Make the race more interesting by adding the following elements.
3a. Randomly jitter each racing turtle's speed
Every time that you move one of the turtles, randomly shift its speed by at most
±1\pm1±1 unit.
3b. Keep score
Create variables to keep track of each turtle's "score": how many laps each turtle has
completed.
Detect when a turtle completes a lap, increment the appropriate turtle's score, and
display the updated score on the screen (somewhere in your scene). You may
repurpose any relevant code from lab.
Take a screenshot of your final race scene in action
(showing two turtles racing on your track with their
scores shown). This is Required Image 2 to be
included in your report.
Check reproducibility
In order to grade your project, we need to be able to run your code and get the same
results as you do! Here is a summary of the expected outputs from each of the source
code files that you created:
● python3 race.py: Draws your racing scene and has two turtles move along the
race course that you designed. The number of laps completed by each turtle
racer should be displayed and updated.
If you use command-line arguments in an extension,
explain what they are and provide an example way to
run your code in both code comments and your
report.
Extensions
Congratulations on completing the core tasks! If your code and report meet the above
expectations, you’ve already earned up to 26/30 points for this project.
The remaining 4/30 are a chance for you to earn credit for exploring parts of this project
and digging deeper to express your creativity! This is entirely optional; 26/30 is a B and
is a perfectly respectable place to stop. Extensions are open-ended and exist to
compliment the structured core project. Explore and learn something new that interests
you!
Concentrating your energy on 1-2 "deep" extensions that challenge
you will earn you more points than many small, "shallow" extensions.
You can pick your own topics that interest you. Here are a few examples:
1. Creative or complex scenes above and beyond the basic expectations count as
extensions.
2. Make the animation of your turtles making the collage from lab look more like
code rain. Some ideas are to draw letters and numbers rather than turtle shapes,
randomize which letters or numbers are drawn, have the "stamps" disappear
after each the turtle has moved a certain number of times.
3. Learn about lists and use them to improve the conciseness of your code.
4. Add additional racing turtles.
5. Design a more complex race track shape (e.g. a spiral, maze, etc.)
6. Designate a winning turtle: the first turtle to complete N laps. Analyze how
differences in the turtle speeds and the amount of randomness influences the
chance that they win.
7. Related to the previous extension, learn about the Gaussian distribution and use
it to generate the random variations in the turtle speed. Analyze how factors
related to how randomness is created influences the chance that either turtle
wins.
8. Make it so that you can position and scale your race scene. Do something
interesting that takes advantage of this.
9. Create a new scene and/or scenario that involves multiple Turtle objects in an
interesting way.
Submission checklist
To turn in your project, make sure you do all of the following:
● Check the rubric in Google Classroom and make sure your report and code
contain all the required parts.
● Move your lab folder inside your project folder (i.e. drag the Lab04 folder inside
Project04).
● Create a zip file of your project.
● Attach (drag) the zip file to the posted project assignment on Google Classroom.
● Click Turn In on your Google Doc report on Google Classroom.
© 2020 Oliver Layton

联系我们
  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-21:00
  • 微信:codinghelp
热点标签

联系我们 - QQ: 99515681 微信:codinghelp
程序辅导网!