Instantly share code, notes, and snippets.

@NatashaTheRobot

NatashaTheRobot / YahtzeeSolution

  • Download ZIP
  • Star ( 3 ) 3 You must be signed in to star a gist
  • Fork ( 1 ) 1 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save NatashaTheRobot/1389923 to your computer and use it in GitHub Desktop.
/*
* File: Yahtzee.java
* ------------------
* This program will eventually play the Yahtzee game.
*/
import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
public class Yahtzee extends GraphicsProgram implements YahtzeeConstants {
/* Private instance variables */
private int nPlayers; //number of players
private String[] playerNames; //an array of Player names
private YahtzeeDisplay display;
private RandomGenerator rgen = new RandomGenerator(); //random number generator
private int[] dieResults = new int [N_DICE]; //stores the most recently rolled dice numbers
private int[][] categoryScores; //stores the score for each category for each player
private int category; //selected category
private int[][] selectedCategories; //stores the already selected categories
public static void main(String[] args) {
new Yahtzee().start(args);
}
public void run() {
IODialog dialog = getDialog();
nPlayers = dialog.readInt("Enter number of players");
while(true) {
if(nPlayers <= MAX_PLAYERS) break;
nPlayers = dialog.readInt("You can only enter up to " + MAX_PLAYERS +" number of players. Enter number of players");
}
playerNames = new String[nPlayers];
categoryScores = new int [nPlayers + 1][N_CATEGORIES+1];
selectedCategories = new int[nPlayers+1][N_CATEGORIES+1];
for (int i = 1; i <= nPlayers; i++) {
playerNames[i - 1] = dialog.readLine("Enter name for player " + i);
}
display = new YahtzeeDisplay(getGCanvas(), playerNames);
playGame();
}
private void playGame() {
for(int i = 0; i < N_SCORING_CATEGORIES; i++) {
for(int j=1; j <= nPlayers; j++) {
initializeFirstRoll(j);
secondAndThirdRoll(j);
selectCategory(j);
}
}
calculateResults();
calculateWinner();
}
/* In the beginning of a players turn,
* the player clicks on "Roll Dice",
* the Dice results are displayed and
* stored in the diceResults array */
private void initializeFirstRoll(int playerNumber) {
for(int i = 0; i < N_DICE; i++) {
int dieRoll = rgen.nextInt(1,6);
dieResults[i] = dieRoll;
}
display.printMessage(playerNames[playerNumber - 1] + "'s turn! Click the " + "\"Roll Dice\" " + "button to roll the dice.");
display.waitForPlayerToClickRoll(playerNumber);
display.displayDice(dieResults);
}
/* For the second and third roll,
* the player selects the dice he or she wants to re-roll,
* the selected dice are re-rolled, and the new
* dice values are displayed and stored in the diceResults array */
private void secondAndThirdRoll(int playerNumber) {
for (int i = 0; i < 2; i++) {
display.printMessage("Select the dice you wish to re-roll and click " + "\"Roll Again\"");
display.waitForPlayerToSelectDice();
for(int j = 0; j < N_DICE; j++) {
if(display.isDieSelected(j) == true) {
int dieRoll = rgen.nextInt(1,6);
dieResults[j] = dieRoll;
}
}
display.displayDice(dieResults);
}
}
/* Pre-condition: The player has rolled the dice three times.
* The player selects the category for the dice.
* The player cannot select a category that he/she already chose in a previous turn.*/
private void selectCategory(int playerNumber) {
while(true) {
display.printMessage("Select a category for this roll");
category = display.waitForPlayerToSelectCategory();
if(selectedCategories[playerNumber][category] == 0) {
calculateCategoryScore(playerNumber);
break;
}
}
}
/* Pre-condition: The user selected a category he/she has not previously selected.
* Assigns 1 to the selectedCategories array to keep track of selected categories.
* Checks to see if the selected category matches the dice configuration,
* and calculates the score. If it does not match, assigns the score of 0.
* Post-condition: Shows the score category and total score in the scorecard.
*/
private void calculateCategoryScore(int playerNumber) {
selectedCategories[playerNumber][category] = 1;
int totalScore;
if(checkCategory(dieResults, category) == true) {
setCategoryScore(playerNumber, category);
int score = categoryScores[playerNumber][category];
display.updateScorecard(category, playerNumber, score);
calculateTotalScores(playerNumber);
totalScore = categoryScores[playerNumber][TOTAL];
display.updateScorecard(TOTAL, playerNumber, totalScore);
}
else {
categoryScores[playerNumber][category] = 0;
display.updateScorecard(category, playerNumber, 0);
calculateTotalScores(playerNumber);
totalScore = categoryScores[playerNumber][TOTAL];
display.updateScorecard(TOTAL, playerNumber, totalScore);
}
}
/*sets the score in the categoryScores matrix for each player
based on the scoring category they chose after rolling the dice*/
private void setCategoryScore(int playerNumber, int category) {
int score = 0;
if(category >= ONES && category <= SIXES) {
for(int i = 0; i < N_DICE; i++) {
if(dieResults[i] == category) {
score += category;
}
}
}
else if(category == THREE_OF_A_KIND || category == FOUR_OF_A_KIND || category == CHANCE) {
for(int i = 0; i<N_DICE; i++) {
score += dieResults[i];
}
}
else if(category == FULL_HOUSE) {
score = 25;
}
else if(category == SMALL_STRAIGHT) {
score = 30;
}
else if(category == LARGE_STRAIGHT) {
score = 40;
}
else if(category == YAHTZEE) {
score = 50;
}
categoryScores[playerNumber][category] = score;
}
/*sets the total scores for each player */
private void calculateTotalScores(int playerNumber) {
int upperScore = 0;
int lowerScore = 0;
int totalScore = 0;
for(int i = ONES; i <= SIXES; i++) {
upperScore += categoryScores[playerNumber][i];
}
for(int i = THREE_OF_A_KIND; i <= CHANCE; i++) {
lowerScore += categoryScores[playerNumber][i];
}
totalScore = upperScore + lowerScore;
categoryScores[playerNumber][UPPER_SCORE] = upperScore;
categoryScores[playerNumber][LOWER_SCORE] = lowerScore;
categoryScores[playerNumber][TOTAL] = totalScore;
}
/* Pre-condition: All players have completed the game.
* Calculates and displays the Upper Score, Upper Bonus, and LowerScore */
private void calculateResults() {
for(int i = 1; i <= nPlayers; i++) {
display.updateScorecard(UPPER_SCORE, i, categoryScores[i][UPPER_SCORE]);
display.updateScorecard(LOWER_SCORE, i, categoryScores[i][LOWER_SCORE]);
if(categoryScores[i][UPPER_SCORE] >= 63) {
categoryScores[i][UPPER_BONUS] = 35;
}
display.updateScorecard(UPPER_BONUS, i, categoryScores[i][UPPER_BONUS]);
categoryScores[i][TOTAL] = categoryScores[i][TOTAL] + categoryScores[i][UPPER_BONUS];
display.updateScorecard(TOTAL, i, categoryScores[i][TOTAL]);
}
}
/* Pre-condition: The game has ended, and all the final scores have been added up.
* Calculates which player has the highest score and what the highest score is
* and prints that information in a message at the very end of the game.*/
private void calculateWinner() {
int winningScore = 0;
int winningPlayerNumber = 0;
for(int i = 1; i<=nPlayers; i++) {
int x = categoryScores[i][TOTAL];
if( x > winningScore) {
winningScore = x;
winningPlayerNumber = i - 1;
}
}
display.printMessage("Congratulations, " + playerNames[winningPlayerNumber] + ", you're the winner with a total score of " + winningScore + "!");
}
/* Pre-condition: The player has finished rolling the dice and selects a category.
* This method returns true if the selected category matches
* to the actual category correctly, and false if it does not match. */
private boolean checkCategory(int[] dice, int category) {
boolean categoryMatch = false;
if(category >= ONES && category <= SIXES || category == CHANCE) {
categoryMatch = true;
}
else {
//creates an array for each possible dice value (1-6)
ArrayList <Integer> ones = new ArrayList<Integer>();
ArrayList <Integer> twos = new ArrayList<Integer>();
ArrayList <Integer> threes = new ArrayList<Integer>();
ArrayList <Integer> fours = new ArrayList<Integer>();
ArrayList <Integer> fives = new ArrayList<Integer>();
ArrayList <Integer> sixes = new ArrayList<Integer>();
/*goes through each rolled die and puts 1 as a place-holder into the appropriate ArrayList
* e.g. if the first die value is 1, then 1 is added to the ones ArrayList or
* if the second die value is 5, then 1 is added to the fives ArrayList*/
for(int i = 0; i < N_DICE; i++) {
if(dice[i] == 1) {
ones.add(1);
}
else if(dice[i] == 2) {
twos.add(1);
}
else if(dice[i] == 3) {
threes.add(1);
}
else if(dice[i] == 4) {
fours.add(1);
}
else if(dice[i] == 5) {
fives.add(1);
}
else if(dice[i] == 6) {
sixes.add(1);
}
}
if(category == THREE_OF_A_KIND) {
if(ones.size() >= 3 || twos.size() >= 3 || threes.size() >= 3 || fours.size() >= 3 || fives.size() >= 3 || sixes.size() >= 3) {
categoryMatch = true;
}
}
else if(category == FOUR_OF_A_KIND) {
if(ones.size() >= 4 || twos.size() >= 4 || threes.size() >= 4 || fours.size() >= 4 || fives.size() >= 4 || sixes.size() >= 4) {
categoryMatch = true;
}
}
else if(category == YAHTZEE) {
if(ones.size() == 5 || twos.size() == 5 || threes.size() == 5 || fours.size() == 5 || fives.size() == 5 || sixes.size() == 5) {
categoryMatch = true;
}
}
else if(category == FULL_HOUSE) {
if(ones.size() == 3 || twos.size() == 3 || threes.size() == 3 || fours.size() == 3 || fives.size() == 3 || sixes.size() == 3) {
if(ones.size() == 2 || twos.size() == 2 || threes.size() == 2 || fours.size() == 2 || fives.size() == 2 || sixes.size() == 2) {
categoryMatch = true;
}
}
}
else if(category == LARGE_STRAIGHT) {
if(ones.size() == 1 && twos.size() == 1 && threes.size() == 1 && fours.size() == 1 && fives.size() == 1){
categoryMatch = true;
}
else if(twos.size() == 1 && threes.size() == 1 && fours.size() == 1 && fives.size() == 1 && sixes.size() == 1) {
categoryMatch = true;
}
}
else if(category == SMALL_STRAIGHT) {
if(ones.size() >= 1 && twos.size() >= 1 && threes.size() >= 1 && fours.size() >= 1) {
categoryMatch = true;
}
else if(twos.size() >= 1 && threes.size() >= 1 && fours.size() >= 1 && fives.size() >= 1) {
categoryMatch = true;
}
else if(threes.size() >= 1 && fours.size() >= 1 && fives.size() >= 1 && sixes.size() >= 1) {
categoryMatch = true;
}
}
}
return categoryMatch;
}
}

@srobert1953

srobert1953 commented Jan 4, 2016

Hi, with testing your code, I am getting wrong score. If you roll after 3 attempts three 3's for example, and you want to assign it to Three of a kind, your score is 11. It should be 9. Also, if you get four 6's and click on Four of a kind, your score is 25, should be 24.

Looking at the code, you should change the setCategoryScore method, as it counts all dices numbers for Three of a kind and four of a kind. You consider these two as Chance kategory, which counts all dices numbers. Instead, they should count only the dices which have the three/four numbers on it. (Example: if you roll 2, 1, 5, 5, 5 - You should count only the 3 5's for Three of a kind kategory with result of 15, not 18).

Sorry, something went wrong.

@Relynn

Relynn commented Apr 19, 2017

srobert1953 - in yahtzee, for 3 of a kind the score you get is from all of the dice... As well as the value of 4 of a kind...

).

You can find extra paper copies of these handouts in the "Handout Hangout" on the 1st floor of Gates, B wing in the side entrance lobby, between rooms 182 and 188.

Copies of the lecture slides are photocopied at six slides per page. This strategy saves paper but makes them too small for some people to read. The notation [ ] indicates a copy of a handout generated in a much larger font, with two slides per page.

[ ]
[ ]
[ ]
[ ]

For DSS Special Agents, protecting Team USA golfers is dream assignment

DSS Special Agent Dan Bair (center) and his Diplomatic Security Service Office of Mobile Security Deployments team plan their next move after providing security for the DSS motorcade carrying a foreign dignitary in New York City for the 74th UN General Assembly, Sept. 22, 2019. (U.S. Department of State photo)

DSS Special Agent Dan Bair (center) and his Diplomatic Security Service Office of Mobile Security Deployments team plan their next move after providing security for the DSS motorcade carrying a foreign dignitary in New York City for the 74th UN General Assembly, Sept. 22, 2019. (U.S. Department of State photo)

Change Text Size

Dan Bair jokes that he justifies the many rounds of golf he plays with his buddies by telling his wife he’s trying to get good enough to start a new career on the PGA TOUR Champions when he turns 50.

Of course, the man who carries a 13.8 handicap knows that’s a pipe dream. Besides, he likes his day job as a Special Agent with the Diplomatic Security Service, which is the law enforcement and security division of the U.S. Department of State.

The Army veteran, who flew Black Hawk helicopters in Iraq and Afghanistan, has traveled to 42 countries in his nearly nine years with the DSS. He’s investigated transnational crimes, monitored security concerns in Somalia and protected political leader summits around the world.

Bair’s current assignment is close to his heart, though. He and Special Agent Amanda Salazar are providing support and security for the Team USA’s men’s and women’s golf teams at the Olympic Games in Paris.

The men’s competition will be held Aug. 1-4 at Le Golf National, which is about 15 minutes from the famed Palace of Versailles, while the women take center stage there a week later.

The men representing the U.S. are world No. 1 Scottie Scheffler, Xander Schauffele (winner of the 2020 Olympic gold medal), Wyndham Clark and Collin Morikawa. The women’s team features the world No. 1 and reigning Olympic champion Nelly Korda, as well as Lilia Vu and Rose Zhang.

Bair and Salazar, who have been planning for the Olympics for the past two years, are there to protect them. They are also assigned to the U.S. men’s and women’s mountain biking teams for the competition on July 28-29.

DSS Special Agent Dan Bair (in sunglasses) meets with Santiago 2023 organizers and Chilean security officials at the National Stadium to prepare for the Pan American Games in Santiago, Chile, June 8, 2023.  (U.S. Department of State photo)

DSS Special Agent Dan Bair (in sunglasses) meets with Santiago 2023 organizers and Chilean security officials at the National Stadium to prepare for the Pan American Games in Santiago, Chile, June 8, 2023. (U.S. Department of State photo)

The DSS has agents like Bair and Salazar at every Olympic venue and works in concert with French authorities, who are responsible for the overall security of the Olympic Games and Paralympics, as well as the International Golf Federation and U.S. and International Olympic committees.

“We’re the only law enforcement federal agency that gets to do things like this,” Bair said. “So, to say it wasn't a neat experience would be a lie. I’m honored. I'm humbled that I get to be around them, but at the same time, my job is to focus elsewhere, but I can't say that I'm not excited about it, for sure.

“We get to be around the best players in the world at the peak of their game at the Olympics. So, it's just another notch in our strange careers, whether you're at historical summits with political figures or you're at the Olympics with top Olympians in the world. So, excited about it for sure.”

Bair was an occasional golfer until he and his family moved to Virginia where they live on a course called Dominion Valley. The 40-year-old loves being outside as well as the camaraderie of the game, and he plays as much as possible – even sneaking in a quick nine on the day he left for Paris. For the record, he shot 43, making double bogey on his last hole.

Bair is a fan of all the members of the U.S. teams, but Schauffele – winner of two major championships this summer – is a particular favorite. He likes the consistency in his swing and says when he’s “pretending that I can golf,” Bair pretends that he’s the newly minted Champion Golfer of the Year.

And while he’ll obviously be focused on security, Bair hopes to learn by osmosis: “Maybe seeing these guys in person, I'll learn at least one little training aid or something that I can take back with me to get (my handicap) even lower,” he said.

Dan Bair pilots a Blackhawk helicopter while serving in the Army Aviation Unit in Afghanistan, 2011. (Courtesy Dan Bair)

Dan Bair pilots a Blackhawk helicopter while serving in the Army Aviation Unit in Afghanistan, 2011. (Courtesy Dan Bair)

Salazar, who will take the lead role with the U.S. women’s team, is looking forward to seeing if Korda can win another gold medal.

“I think that winning multiple medals in multiple Games is just sort of like the tip of the hat and really sort of solidifying your place as one of the best in the world,” Salazar said.

Salazar took a different path to the DSS than Bair. She went to college at the University of Delaware, where she played rugby and majored in hospitality management, later running food and beverage outlets at private clubs around the Washington, D.C., area. She wanted to travel, though, and a mentor steered her toward the federal government and eventually, the State Department.

She has worked in diplomatic security for the last 11 years. She spent three of those years assigned to the Secretary of State’s Protective Division, where she worked at political summits, sporting events and the United Nations General Assembly.

The DSS operates at more than 270 U.S. diplomatic posts in over 170 countries, and more than 30 U.S. cities. Salazar’s posts have included Istanbul, Turkey, and Bogota, Colombia, and most recently Bangkok, Thailand. She is headed next to Islamabad, Pakistan, where the aspiring golfer has heard there are some interesting courses.

“I’m excited to check it out,” she said.

DSS Special Agent Amanda Salazar in front of Air Force 2, supporting the U.S. Delegation to the 2022 APEC Leader’s Summit. (Courtesy Amanda Salazar)

DSS Special Agent Amanda Salazar in front of Air Force 2, supporting the U.S. Delegation to the 2022 APEC Leader’s Summit. (Courtesy Amanda Salazar)

Like Bair, Salazar is looking forward to the competition. It will undoubtedly be very different than when she volunteered at the McDonald’s Championship on the LPGA Tour for two years working as the standard bearer for Sei Young Kim and Seon Hwa Lee.

“Truly this is a dream come true,” Salazar said. “I have been trying to line up my assignments to this opportunity since I started with DSS, and I feel so fortunate to finally make it work. I think as a kid, especially in the United States, you watch the Olympics on TV, and it just is such a special time of year and for me, particularly the Summer Olympics.

“I'm really excited and ecstatic to be here.”

Hi there 👋 and welcome to CS106A!

CS106A introduces code and computer programming for people who have not programmed before. Code and programming are central to so much in modern life, yet code can appear to be impossibly opaque. By working gradually and with its army of section leaders, CS106A takes students into the world code, building things they could not have imagined.

Instructor: Cynthia Bailey Lee, [email protected]

SL: Selaine Nicole Rodriguez, [email protected]

For SSEA, we will be previewing the first 3-4 weeks of the CS106A course, staying fairly faithful to what the course looks like in the regular school year. The full CS106A course will cover all the important topics of basic programming in Python: types, numbers, strings, functions, linear collections, dictionaries, logic, decomposition, good programming style, whole-program structure, text, file-processing, debugging, and performance. We'll also touch on more advanced topics you might want in the future, including lambdas, comprehensions, modules, and Jupyter notebooks.

Python is a huge language with many advanced features, and CS106A does not cover all of Python's features. CS106A teaches the important core features, and you will be able to solve real programming problems with just this course.

Other Courses: CS105 CS106A/B CS193Q CME193

CS106A is the first course in programming and computer science, for people who with zero experience. CS106B is the second course, teaching more advanced programming and computer science for people who know basic programming. CS105 is a more lightweight introduction to CS ideas, but without as much coding as CS106A. CS193q is a 1 unit seminar that teaches Python very very quickly - geared for people who already know how to program but do not know Python.

CME193 is a course in applied Python for scientists and engineers. It is a course one could take after CS106A.

Python Resources

In lecture we'll have links to some online code exercises on an "experimental server" set up by Nick Parlante, another CS106A instructor. Other times we will distribute a .zip file with that day's code examples.

We'll use web resources as our Python reference as we go, and Nick Parlante maintains a free Python Guide with more detail on Python topics (linked off the course page too).

There is no required textbook, and a book is not needed for this course. However, if a student insisted on a recommendation, "Introducing Python" by Lubanovic is a good introductory book.

Python 3 / PyCharm

We will use Python version 3. You will install Python and PyCharm (the "integrated development environment, IDE) as part os assignment 0. At the start we'll use the experimental server which works without installing anything. Later we will do larger exercises where you will use Python 3 and PyCharm installed on your computer. We'll have detailed instructions for that when we get there.

Lab In Lecture

We will experiment integrating little exercises within lecture, so expect to do some exercises live as we go. Education research shows that doing a little activity with what you just saw helps a lot with learning. (see Carl Wieman, Stanford School of Education)

The full CS106A has assignments weekly programming assignments. During SSEA, we will complete parts of assignments similar to those used in the school year.

Although there are no grades during SSEA, we strive to not interfere with your ability to properly earn credit in the full CS106A if/when you take it. We attempt to offer homework and other practice that will not be the same as the school year ones, in hopes that you won't run into any trouble with possible plagiarism by turning in the same work in real CS106A. However, you should be aware of the course's policies on plagiarism, the Honor Code, and re-submitting work you did previously, in case an issue arises later. That policy is explained here:

In the spirit of collegial and cooperative learning, you are free to discuss ideas and approaches with other students, and then implement the solution yourself. The key is this: all the code you submit you should type in and get working yourself . In particular, it is not ok to share or paste in someone else's code or get code from a previous quarter. It is not ok to look at someone else's code. You should not be looking at another student's homework code.

For discussion or tying out ideas, the many lecture examples work well and of course it's fine for everyone to look at and experiment with that code.

Web search: it's fine if you search the web to find the right 2 line phrase to solve something, like "sort strings" - programmers do that sort of search all the time, and finding and using short phrases like that is fine. Do not, however, search for a whole homework function and paste in what you find. We want you to write that code.

The Computer Science department produces many honor code cases at Stanford. This is not because CS is a magnet for cheating; it's just that online submissions provide a large body of evidence, and computer science has tools which do an extremely good job of finding cheating.

Each homework submission has a section where you can write notes for the grader. If you think a bit of collaboration may have crossed the line, mention it in your README notes for that homework. You can never get in honor code trouble for collaboration clearly described in this way.

As mentioned above, CS106A exams will very much resemble the homework problems. So that's an additional reason you need to author and understand your own code.

On a related note, when you are done with a homework - please don't post your code on the internet! That causes problems for us and for people trying to learn the material later.

Philosophy and the Honor Code

It's not that people can be divided into cheaters and non-cheaters in some pre-ordained way, though that is an easy way to think about life. It's more that the stress and bad decision making of a particular situation make a cheater of someone. If you feel you are in that position, contact Chris and I promise we'll work something out where you can pass this class vs. making a huge mistake.

Topics and Weekly Schedule

See the course calendar for up-to-date details.

Stanford University

Stanford engineering, s tanford e ngineering e verywhere, cs106a - programming methodology, lecture 10 - importance of private variables.

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

Importance Of Private Variables

Extending The Student Class

Overriding Methods

The acm.graphics Package

Methods Common To All GObjects

Interfaces And Methods Defined By Them

The BouncingBall Program Example

The Geometry Of The GLabel Class

The GArc Class

  • 1 - Welcome to CS106A
  • 2 - Handout Information
  • 3 - Karel and Java
  • 4 - The History of Computing
  • 5 - Variables
  • 6 - readInt() and readDouble()
  • 7 - The Loop and a Half Problem
  • 8 - Information Hiding
  • 9 - Strings
  • 10 - Importance of Private Variables
  • 11 - The GImage Class
  • 12 - Enumeration
  • 13 - String Processing
  • 14 - Memory
  • 15 - Pointer Recap
  • 17 - Multi-dimensional Arrays
  • 18 - A Wrap Up of Multi-dimensional Arrays
  • 19 - An Interface
  • 21 - Review of Interactors and Listeners
  • 22 - Overview of NameSurfer - The Next Assignment
  • 23 - Introduction to Lecture's material - Searching
  • 24 - Principles of Good Software Engineering for Managing Large Amounts of Data
  • 25 - Defining a Social Network for Our Purposes
  • 26 - Introduction to the Standard Java Libraries
  • 27 - Life After CS106A
  • 28 - The Graphics Contest Winners
  • About the Lecture TITLE: Lecture 10 - Importance of Private Variables DURATION: 47 min TOPICS: Importance of Private Variables Extending the Student Class Overriding Methods The acm.graphics Package GCanvas Methods Common to All GObjects Interfaces and Methods Defined by Them The BouncingBall Program Example The Geometry of the GLabel Class The GArc Class

Course Details

Course description.

This course is the largest of the introductory programming courses and is one of the largest courses at Stanford. Topics focus on the introduction to the engineering of computer applications emphasizing modern software engineering principles: object-oriented design, decomposition, encapsulation, abstraction, and testing. Programming Methodology teaches the widely-used Java programming language along with good software engineering principles. Emphasis is on good programming style and the built-in facilities of the Java language. The course is explicitly designed to appeal to humanists and social scientists as well as hard-core techies. In fact, most Programming Methodology graduates end up majoring outside of the School of Engineering. Prerequisites: The course requires no previous background in programming, but does require considerable dedication and hard work.

  • DOWNLOAD All Course Materials

Sahami, Mehran

Outside of work, I enjoy spending time with family, playing the guitar, going on outdoor excursions, and sleeping (which seems to be getting rarer and rarer these days).

Lecture 1
No Handouts
No handouts

Assignments

Section assignments.

AssignmentSolutionsDistributed
Lecture 4
Lecture 7
Lecture 10
Lecture 13
Lecture 16
Lecture 18
Lecture 21
Lecture 24
Lecture 27

Programming Assignments

AssignmentInstructionsStarter CodeDistributed
1. Karel Lecture 2
2. Simple Java Lecture 6
3. Breakout! Lecture 10
4. Hangman Lecture 14
5. Yahtzee! Lecture 18
6. NameSurfer Lecture 22
7. FacePamphlet Lecture 25
Practice Midterm
Practice Final
Windows Users
Macintosh Users
Software Resources

Course Sessions (28):

Watch Online: Download: Duration:
Watch Now Download 50 min
Welcome to CS106A, Course Staff, Why is the class called Programming Methodology?, Are you in the right class?, Class Logistics, Assignments and Grading, Extensions, Midterm and Final, Grade Breakdown, The Honor Code, Why Karel?

Transcripts

Watch Online: Download: Duration:
Watch Now Download 48 min
Handout Information, Section Sign-up, Karel Commands, An Algorithm vs Program, Syntax of a Karel Program, Running a Karel Program, Creating Methods, SuperKarel, A for Loop, A While Loop, Karel Conditions, If Statement, Putting it All Together
Watch Online: Download: Duration:
Watch Now Download 51 min
Karel and Java, Common Errors, Comments, Pre-conditions and Post-conditions, Decomposition, The DoubleBeepers Example, Importance of Good Software Engineering, The Right Decomposition, The CleanUpKarel Example
Watch Online: Download: Duration:
Watch Now Download 48 min
The History of Computing, Computer Science vs Programming, What Does the Computer Understand?, The Compilation Process, Java is an Object Oriented Language, Inheritance, Instance of a Class, The acm.program Hierarchy, Your First Java Program, A ConsoleProgram Example, The Graphics Window, The Sending-Messages-to-a-GLabel Example
Watch Online: Download: Duration:
Watch Now Download 49 min
Variables, Data Types for Variables, Syntax for Using Variables, Classes as Types, Objects as Variables, Invoking Methods on Objects, Graphics Coordinates, Operations on the GObject Class and its Subclasses, Drawing Geometrical Objects, A FunGraphics Example, Expressions and Operators
Watch Online: Download: Duration:
Watch Now Download 56 min
readInt() and readDouble(), The Division Operator w.r.t ints and Doubles, Order of Precedence for Operators, Type Casting, Shorthands, Constants, The Boolean Data Type, Value Comparisons, Boolean Expressions, Short Circuit Evaluation, Statement Blocks, Scope of Variables, Cascading if, The Switch Statement, The For Loop, The While Loop
Watch Online: Download: Duration:
Watch Now Download 51 min
The Loop and a Half Problem, For Versus While Loop, The CheckerBoard Program Example, Methods in Java, Examples of Methods, The FactorialExample Program, Returning Objects from Methods
Watch Online: Download: Duration:
Watch Now Download 49 min
Information Hiding, The Void Return Type, Parameter Passing Between Methods, Bad Times with Methods, Using Classes, Instance variables vs Local Variables, The RandomGenerator Program Example, The RollDice Program Example, The setSeed() Method
Watch Online: Download: Duration:
Watch Now Download 52 min
Strings, Writing Your Own Class, Public and Private Visibility, Creating a New Class, The Constructor Method, Shadowing of Variables and the 'this' Keyword, Using the Created Class, Objects are Called by Reference not Called by Value, Class Variables, The JavaDoc, The Student Program Example
Watch Online: Download: Duration:
Now Playing Download 47 min
Importance of Private Variables, Extending the Student Class, Overriding Methods, The acm.graphics Package, GCanvas, Methods Common to All GObjects, Interfaces and Methods Defined by Them, The BouncingBall Program Example, The Geometry of the GLabel Class, The GArc Class
Watch Online: Download: Duration:
Watch Now Download 50 min
The GImage Class, The GPolygon Class, The GCompound Class, Event Driven Programs, The ClickForFace Program Example, Responding to Mouse Events, Responding to Keyboard Events, The UFO program Example
Watch Online: Download: Duration:
Watch Now Download 49 min
Enumeration, Characters, The ASCII Subset of Unicode, Reading Characters, Math on Characters, char as a Primitive Type; the Character Class, Strings and Their Manipulations
Watch Online: Download: Duration:
Watch Now Download 47 min
String Processing, Tokenizers, Encryption
Watch Online: Download: Duration:
Watch Now Download 46 min
Memory, Different Sections of Memory for Different Types of Variables, Memory Allocation Mechanics, The Pointer Viewpoint, The Binky Pointer Fun Video
Watch Online: Download: Duration:
Watch Now Download 48 min
Pointer Recap, Why are Objects 'Call by Reference' Instead of 'Call of Value'?, Wrapper Classes for Primitive Types, Files, Code for Opening, Reading and Closing Files, Exceptions, Code for Writing Files
Watch Online: Download: Duration:
Watch Now Download 50 min
Array, Creating a New Array, The ++ Operator, Actual Size / Effective Size of the Array, An Array as a Parameter, Initialize an Array During Creation, An ArrayList
Watch Online: Download: Duration:
Watch Now Download 50 min
Multi-dimensional Arrays, An ArrayList, The Template Class, Methods in the ArrayList Class, An Example Program Using ArrayList, ArrayLists Hold Objects, An Example Program with an ArrayList of Glabels, The GrayImage Example Program
Watch Online: Download: Duration:
Watch Now Download 47 min
A Wrap Up of Multi-dimensional Arrays, The ArrayList Way, Pros and Cons : ArrayList vs. Array, Debugging, Approaches to Debugging, The Debugger in Eclipse
Watch Online: Download: Duration:
Watch Now Download 50 min
An Interface, How are Interfaces Implemented, A Map, The HashMap Class, Methods of the HashMap, The Collection Hierarchy, The Map Hierarchy, An Iterator, A HashMap Example
Watch Online: Download: Duration:
Watch Now Download 45 min
GUI, Interactors in the Context of a Java Program, The Swing Interactor Hierarchy, Window Regions, Creating Interactors, Example Programs, Exploring More Interactors, The InteractiveDrawFace Program Example
Watch Online: Download: Duration:
Watch Now Download 48 min
Review of Interactors and Listeners, Example Programs, The Use of the Two Ways Shown in the Examples - Using getSouce and getActionCommand, TextField Example, Layouts, The Temperature Conversion Example, The TextAndGraphics Example
Watch Online: Download: Duration:
Watch Now Download 46 min
Overview of NameSurfer - The Next Assignment, Components and Containers, Listeners for Components, Create a Program Which Extends Program, The ComponentListener Interface, The MusicShop Example Program, The MusicShopDisplay Example Program
Watch Online: Download: Duration:
Watch Now Download 51 min
Introduction to Lecture's material - Searching, Sorting and Algorithmic Efficiency, Searching, Linear Search, Efficiency of Linear Search, Binary Search, Efficiency of Binary Search, Comparing Search Efficiencies, Sorting, The Selection Sort Algorithm, Efficiency of Selection Sort, The Radix Sort Algorithm
Watch Online: Download: Duration:
Watch Now Download 47 min
Principles of Good Software Engineering for Managing Large Amounts of Data, Principles of Design, The Collection Hierarchy, Useful Methods of Collection, The FlyTunes Example Program - An Online Music Store, Defining the Song Class, Defining the Album Class, Seeing the Program Run, Considering the Data Structures Needed, Reusing Data - Shallow Copy vs. Deep Copy, The FlyTunesStore Program Code
Watch Online: Download: Duration:
Watch Now Download 47 min
Defining a Social Network for Our Purposes, See What the Program Needs to Do, The Six Degrees of Separation Phenomenon, Concurrency, A Thread, The Runnable Interface, Creating a Thread, Example Program, Having Shared Data Between Your Threads
Watch Online: Download: Duration:
Watch Now Download 42 min
Introduction to the Standard Java Libraries, A JAR File, Creating a JAR File, Creating an Applet, Standard Java Programs Without Using the ACM Libraries, Other Resources - Learning More Java
Watch Online: Download: Duration:
Watch Now Download 42 min
Life After CS106A, The CS Major, Other Possible Majors
Watch Online: Download: Duration:
Watch Now Download 42 min
The Graphics Contest Winners, Review for the Final, Example Question 1, Example Question 2, A Wrap-up

Stanford Center for Professional Development

  • Stanford Home
  • Maps & Directions
  • Search Stanford
  • Emergency Info
  • Terms of Use
  • Non-Discrimination
  • Accessibility

© Stanford University, Stanford, California 94305

IMAGES

  1. CS106A Assignment 5: Yahtzee Part 1

    cs106a assignment 5

  2. CS106A Assignment 5: Yahtzee: Part 3

    cs106a assignment 5

  3. Building block approach: CS106A

    cs106a assignment 5

  4. The stages of completing a CS106A assignment the night before it's due

    cs106a assignment 5

  5. CS106A: Wrap-up

    cs106a assignment 5

  6. cs106a

    cs106a assignment 5

VIDEO

  1. Code.org Lesson 10.2 ArrayList Algorithms

  2. Collect Newspaper Karel

  3. BEST Way to Self Learn Java FAST (How I Taught Myself to Code)

  4. EEC 3204 Assignment 5- Covid and Early Childhood Education

  5. Cs610 Assignment 1 2023 || Cs610 Assignment 1 Solution fall 2023 || Cs610 Assignment 1 Solution 2023

  6. Code.org Lesson 1.1 Project Planning

COMMENTS

  1. CS106A Assignments

    All the assignment starter bundles for CS106A can be found here. Each download should include everything you need to start working on the assignment. ... Assignment #5: 50-assignment-5.pdf: Assignment5.zip [new FacePamphlet.jar] Mar 12: Assignment #6: 57-assignment-6.pdf: Assignment6.zip [TeachingMachine.zip] Mar 12: Adventure Contest: 58 ...

  2. CS106A Assignment 5: Yahtzee Part 1

    Sorry I felt rushed but I hope this explains the process.This video is designed for learning purposes only. The original sources comes from the Stanford web...

  3. Assignment #5

    Download ZIP. Assignment #5 - Yahtzee (Stanford-CS106A) Raw. Yahtzee.java. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters.

  4. This is the solution to Stanford CS106A Yahtzee Assignment 5

    It should be 9. Also, if you get four 6's and click on Four of a kind, your score is 25, should be 24. Looking at the code, you should change the setCategoryScore method, as it counts all dices numbers for Three of a kind and four of a kind. You consider these two as Chance kategory, which counts all dices numbers.

  5. CS106A Assignment 5: Yahtzee: Part 2

    This video is designed for learning purposes only. The original sources comes from the Stanford website. You can Youtube them to find it. This is Assignme...

  6. CS 106A

    The final step is to submit your assignment. This assignment may (optionally) be done in pairs. As a reminder, you may only pair up with others with the same section time and location. Note: In general, limit yourself to using Java syntax taught in lecture, and the parts of the textbook we have read, up through the release of this assignment ...

  7. CS106A Assignment 5

    5/2 Dictionaries 17. 5/4 Nested Structures 18. 5/9 String Parsing 19. 5/11 Tuples Sorting 20. 5/13 Classes and Objects 21. 5/16 Ethics 22. 5/18 Memory 23. 5/20 Search and Indexing 24. 5/23 The Internet 25. 5/25 Life After CS106A 26. 5/27 Advanced Python 27. 6/1 Wrap Up

  8. CS106A

    In CS106A this quarter we are hosting a Contest where you can program anything you like using the concepts and tools we learn in class. See the contest handout for more details. Assignment 5 released. 2021072115. We have released all parts of assignment 5. The assignment is due due Tuesday, July 27th. Check out part a. Use what we learned in ...

  9. PDF Eric Roberts Handout #50 CS 106A February 19, 2010 Assignment #5

    Assignment #5—FacePamphlet 2.0 The original version of FacePamphlet was designed by Mehran Sahami. Due: Monday, March 1 This assignment has two goals. The first is to give you an opportunity to use Java interactors to create an interactive application complete with buttons and various kinds of text fields, along with a graphical display.

  10. Cs 106a assignment 5

    CS106A Code in Place Diagnostic Solutions; Preview text. Chris Piech Assignment 5 CS 106A Feb 16, 2017. Assignment #5—ImageShop Due: 11AM PST on Monday, Feb 26 This assignment may be done in pairs (which is optional, not required) Based on handouts by Marty Stepp, Eric Roberts and Keith Schwarz.

  11. PDF Mehran Sahami Handout #35 CS 106A November 5, 2007 Assignment #5

    CS 106A November 5, 2007 Assignment #5 — Yahtzee!™ Due: 3:15pm on Wednesday, November 14th Based on a handout written by Eric Roberts and Julie Zelenski. Note: Yahtzee™ is the trademarked name of a game produced by Hasbro. We refer to this game for educational purposes only. Okay, we also like to have fun playing the game.

  12. GitHub

    Solutions to all assignments for Stanford Engineering Everywhere online course CS106A - danpaz/cs106a-assignments

  13. CS106A Handouts

    CS106A Handouts. Handouts. This is the repository for all handouts that are given out in class, section, and practice sessions. All documents here are in Adobe Acrobat format; the reader for this format is available for free (look for the Acrobat Reader logo at the bottom of the Adobe Systems web site ). You can find extra paper copies of these ...

  14. CS106A Code in Place Diagnostic Solutions

    Cs 106a assignment 5; Preview text. Post Diagnostic Report The purpose of the Diagnostic was to help you self assess where you can improve. Every ... notoriously one of the hardest concepts in the first half of CS106A. These lecture videos cover functions and return values: Problem 2b: Ride the Rollercoaster ...

  15. Stanford Engineering Everywhere

    The course is explicitly designed to appeal to humanists and social scientists as well as hard-core techies. In fact, most Programming Methodology graduates end up majoring outside of the School of Engineering. Prerequisites: The course requires no previous background in programming, but does require considerable dedication and hard work.

  16. CS106A Home

    The 106A final exam is Friday, June 3rd from 8:30-11:30am. Locations will be based on your last name. Last name: A-H should go to room: Biship Auditorium (in Lathrop) Last name: I-Z should go to room: CEMEX Auditorium (in Graduate School of Business - Knight Management Center, Zambrano Hall) We have posted a handout with exam information and a ...

  17. For DSS Special Agents, protecting Team USA golfers is dream assignment

    Bair's current assignment is close to his heart, though. He and Special Agent Amanda Salazar are providing support and security for the Team USA's men's and women's golf teams at the ...

  18. Stanford Engineering Everywhere

    This course is the largest of the introductory programming courses and is one of the largest courses at Stanford. Topics focus on the introduction to the engineering of computer applications emphasizing modern software engineering principles: object-oriented design, decomposition, encapsulation, abstraction, and testing. Programming Methodology teaches the widely-used Java programming language ...

  19. Rafael Montero designated for assignment: Astros dump reliever in ...

    T he Houston Astros designated veteran reliever Rafael Montero for assignment on Wednesday as part of a series of roster moves that also saw the club option ... plus his $11.5 million salary for ...

  20. Red Sox' Triston Casas starts rehab assignment after months out ...

    First baseman Triston Casas began a rehab assignment with Worcester on Tuesday night, with the WooSox winning 11-6 against the Buffalo Bisons at Polar Park. Casas last played for the Red Sox on ...

  21. CS106A

    YEAH Hours. CS106A YEAH Hours are Your Early Assignment Help Hours, a weekly session intended to help students get started on the CS106A assignments. We'll break the assignment handout into manageable chunks, go over useful resources, and discuss approaches for major milestones of the assignment.

  22. URGENT! My Assignment is due 2nd August 2024. I am trying to Access

    Both messages mean the same thing: You're probably using a URL that is no longer valid to reach the journals you're trying to reach. (Technically, it means that the hostname - the name of the server you're trying to reach - doesn't match the server's name on its security certificate.)

  23. Section 19:31Y-1.11

    Section 19:31Y-1.11 - Assignment of rights of rehabilitation agreement (a) A business entity who has entered into a rehabilitation agreement pursuant to N.J.A.C. 19:31Y-1.8(b) may, upon notice to and written consent of the Authority, pledge, assign, transfer, or sell any, or all, of its rights, title, and interest in and to the rehabilitation agreement and in the tax credit awards payable ...

  24. CS106A Syllabus

    CS106A is the first course in programming and computer science, for people who with zero experience. CS106B is the second course, teaching more advanced programming and computer science for people who know basic programming. ... IDE) as part os assignment 0. At the start we'll use the experimental server which works without installing anything ...

  25. Stanford Engineering Everywhere

    The course is explicitly designed to appeal to humanists and social scientists as well as hard-core techies. In fact, most Programming Methodology graduates end up majoring outside of the School of Engineering. Prerequisites: The course requires no previous background in programming, but does require considerable dedication and hard work.

  26. Houston Astros designate Rafael Montero for assignment amid $34 ...

    A month and a half after parting ways with Jose Abreu, the Houston Astros are following suit by designating relief pitcher Rafael Montero for assignment. The 33-year-old was halfway into a three ...

  27. PDF CS 106A

    handouts and assignment files. Discussion sections In addition to lecture, you must also sign up for a weekly 50-minute section. In order to take CS 106A, you must sign up for a section between 5:00P.M. Thursday, September 27th and 5:00P.M. Sunday, September 30th. The signup form will be available on the

  28. Stanford Engineering Everywhere

    The course is explicitly designed to appeal to humanists and social scientists as well as hard-core techies. In fact, most Programming Methodology graduates end up majoring outside of the School of Engineering. Prerequisites: The course requires no previous background in programming, but does require considerable dedication and hard work.

  29. Stanford Engineering Everywhere

    This course is the largest of the introductory programming courses and is one of the largest courses at Stanford. Topics focus on the introduction to the engineering of computer applications emphasizing modern software engineering principles: object-oriented design, decomposition, encapsulation, abstraction, and testing. Programming Methodology teaches the widely-used Java programming language ...