查看: 6412| 回复: 21
跳转到指定楼层
上一主题 下一主题
收起左侧

Stanford CS106a #4 Assignment4讨论帖

全局:
先跟各位道个歉,没有及时发布这次assignment,这几天实在是事情太多。好了,废话少说

时间:2012.8.7-2012.8.10

课程:
12. Character and String
13. Problem solving with strings
14. Objects and memory
15. File processing & Exception handling
16. Debugging Strategies

作业:
Assignment 4 hangman.java
due: 2012.8.10

建议:
本次作业的难度不大,主要用到的知识就是String和之前画图的知识。hangman是一个猜字游戏
但是关于后面HangmanLexicon的运用需要注意,就是所猜的词在HangmanLexicon之中
调用HangmanLexicon.txt时要用到15课的知识。可以先编之前的部分
加油!
单选投票, 共有 15 人参与投票
您所在的用户组没有投票权限

上一篇:[Udacity CS 262] Programming Languages (Week #3)
下一篇:[Udacity CS 262] Programming Languages (Week #4)
🔗
 楼主| yiyiyaya 2012-8-7 17:11:28 | 只看该作者
全局:
本帖最后由 yiyiyaya 于 2012-8-7 17:15 编辑
  1. import acm.program.*;
  2. import acm.util.*;

  3. public class Hangman extends ConsoleProgram {
  4.    
  5.         public void init(){
  6.                 canvas = new HangmanCanvas();
  7.                 add(canvas);
  8.         }
  9.     public void run() {
  10.             canvas.reset();
  11.                 println("Welcome to Hangman!");
  12.                 String word= lexicon.getWord(rgen.nextInt(0,lexicon.getWordCount()-1));
  13.                 int trialTimes = 8;
  14.                 int length = word.length();
  15.                 String line = "";
  16.                 for(int j=0;j<word.length();j++){
  17.                         line = line + "-";
  18.                 }
  19.                 println("The word now looks like this:" +line );
  20.                 println("You have 8 guesses left.");
  21.                 while(trialTimes>0){
  22.                     String S = readLine("Your guess:");
  23.                     char ch = S.charAt(0);
  24.                     ch = Character.toUpperCase(ch);
  25.                     if(!(ch>='A'&&ch<='Z')){
  26.                             println("the guess is illegal.");
  27.                     }
  28.                     else {
  29.                   
  30.                     boolean isCorrect=false;
  31.                
  32.                     for(int i=0;i<word.length();i++) {
  33.                             if (ch == word.charAt(i)) {
  34.                                     isCorrect = true;        
  35.                                     println("That guess is correct.");
  36.                                     if(i==0){
  37.                                             line = ch+line.substring(i+1, length);
  38.                                             if(!line.equals(word)) {
  39.                                                 println("The word now looks like this:"+line);
  40.                                             }
  41.                                           
  42.                                     } else if (i==length-1) {
  43.                                             line = line.substring(0,i)+ch;
  44.                                             if(!line.equals(word)){
  45.                                                 println("The word now looks like this:"+line);
  46.                                             }
  47.                                     } else {
  48.                                             line = line.substring(0,i)+ch+line.substring(i+1, length);
  49.                                             if(!line.equals(word)){
  50.                                             println("The word now looks like this:"+line);
  51.                                             }
  52.                                     }
  53.                            }
  54.                         
  55.                    }
  56.                    if(isCorrect) {
  57.                           if(!line.equals(word)) {
  58.                                   canvas.displayWord(line);
  59.                               println("You have "+trialTimes+" guesses left.");
  60.                           }
  61.                    }
  62.                    else {
  63.                           canvas.noteIncorrectGuess(ch);
  64.                           println("There are no "+ ch +"'s in the word.");
  65.                       trialTimes--;
  66.                       println("The word now looks like this:"+line);
  67.                       println("You have "+trialTimes+" guesses left.");
  68.                   
  69.                
  70.                    }
  71.                    if(line.equals(word)) {
  72.                            println("You guessed the word: "+word);
  73.                            println("You win.");
  74.                            break;
  75.                    }
  76.                 }
  77.                 if(trialTimes == 0){
  78.                     println("You're completely hung.");
  79.                     println("The word was: "+word);
  80.                     println("You lose.");
  81.                 }
  82.                 }
  83.         
  84.         }
  85.     private newHangmanLexicon lexicon = new newHangmanLexicon();
  86.     private RandomGenerator rgen =  RandomGenerator.getInstance();
  87.     private HangmanCanvas canvas;
  88.   
  89. }
复制代码
  1. /*
  2. * File: HangmanCanvas.java
  3. * ------------------------
  4. * This file keeps track of the Hangman display.
  5. */

  6. import acm.graphics.*;

  7. public class HangmanCanvas extends GCanvas {

  8. /** Resets the display so that only the scaffold appears */
  9.         public void reset() {
  10.                 removeAll();
  11.                 int x = getWidth();
  12.                 int y = getHeight();
  13.                
  14.                 double x0 = (x/2)-BEAM_LENGTH;
  15.                 double y0 = (y-SCAFFOLD_HEIGHT-50)/2;
  16.                
  17.                 GLine beam = new GLine(x0,y0,x0+BEAM_LENGTH,y0);
  18.                 add(beam);
  19.                 GLine scaffold = new GLine(x0,y0,x0,y0+SCAFFOLD_HEIGHT);
  20.                 add(scaffold);
  21.                 GLine rope = new GLine(x0+BEAM_LENGTH,y0,x0+BEAM_LENGTH,y0+ROPE_LENGTH);
  22.                 add(rope);
  23.                
  24.                 add(wordInfo,40,(y+SCAFFOLD_HEIGHT)/2 + 10);  //单词猜测情况  
  25.                 add(wrongList,40,(y+SCAFFOLD_HEIGHT)/2 + 40); //猜测错误的字母

  26.         }

  27. /**
  28. * Updates the word on the screen to correspond to the current
  29. * state of the game.  The argument string shows what letters have
  30. * been guessed so far; unguessed letters are indicated by hyphens.
  31. */
  32.         public void displayWord(String word) {
  33.                 wordInfo.setFont("Serif-20");  
  34.                 wordInfo.setLabel(word);

  35.         }

  36. /**
  37. * Updates the display to correspond to an incorrect guess by the
  38. * user.  Calling this method causes the next body part to appear
  39. * on the scaffold and adds the letter to the list of incorrect
  40. * guesses that appears at the bottom of the window.
  41. */
  42.         public void noteIncorrectGuess(char letter) {
  43.                 int x = getWidth();
  44.                 int y = getHeight();
  45.                 String guessWord;  
  46.                 /*we use the wrongList to store the wrong ch.
  47.                  *And then use the guessWord.length() as the switch index. String.valueOf
  48.                  */
  49.                 wrongList.setLabel(wrongList.getLabel() + String.valueOf(letter));  
  50.                 guessWord = wrongList.getLabel();

  51.         switch(guessWord.length()){ //guessWord.length() is very important!!I haven't thought about it before.
  52.                
  53.             case 1:
  54.                     double xHead = x/2-HEAD_RADIUS;
  55.                         double yHead = (y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH;
  56.                     GOval head = new GOval(xHead,yHead,HEAD_RADIUS*2,HEAD_RADIUS*2);
  57.                     add(head);
  58.                 break;
  59.                
  60.             case 2:
  61.                     
  62.                 double yBody = (y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH + HEAD_RADIUS*2;
  63.                 GLine body = new GLine(x/2,yBody,x/2,yBody+BODY_LENGTH);
  64.                     add(body);
  65.                 break;
  66.                
  67.                
  68.             case 3:
  69.                 double xLeftArm = x/2-UPPER_ARM_LENGTH;
  70.                     double yLeftArm = (y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH + HEAD_RADIUS*2 + ARM_OFFSET_FROM_HEAD;
  71.                     GLine upperLeftArm = new GLine(xLeftArm,yLeftArm,xLeftArm+UPPER_ARM_LENGTH,yLeftArm);
  72.                     GLine lowerLeftArm = new GLine(xLeftArm,yLeftArm,xLeftArm,yLeftArm+LOWER_ARM_LENGTH);
  73.                     add(upperLeftArm);
  74.                     add(lowerLeftArm);
  75.                 break;
  76.                
  77.                
  78.             case 4:
  79.                     double xRightArm = x/2;
  80.                         double yRightArm = (y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH + HEAD_RADIUS*2 + ARM_OFFSET_FROM_HEAD;
  81.                     GLine upperRightArm = new GLine(xRightArm,yRightArm,xRightArm+UPPER_ARM_LENGTH,yRightArm);
  82.                     GLine lowerRightArm = new GLine(xRightArm+UPPER_ARM_LENGTH,yRightArm,xRightArm+UPPER_ARM_LENGTH,yRightArm+LOWER_ARM_LENGTH);
  83.                     add(upperRightArm);
  84.                     add(lowerRightArm);
  85.                 break;
  86.                
  87.         
  88.             case 5:
  89.                     double xLeftLeg = x/2-HIP_WIDTH;
  90.                         double yLeftLeg = (y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH + HEAD_RADIUS*2+BODY_LENGTH;
  91.                     GLine leftHip = new GLine(xLeftLeg,yLeftLeg,xLeftLeg+HIP_WIDTH,yLeftLeg);
  92.                     GLine leftLeg = new GLine(xLeftLeg,yLeftLeg,xLeftLeg,yLeftLeg+LEG_LENGTH);
  93.                     add(leftHip);
  94.                     add(leftLeg);
  95.             break;
  96.                
  97.                
  98.             case 6:
  99.                     double xRightLeg = x/2;
  100.                         double yRightLeg = (y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH + HEAD_RADIUS*2+BODY_LENGTH;
  101.                     GLine RightHip = new GLine(xRightLeg,yRightLeg,xRightLeg+HIP_WIDTH,yRightLeg);
  102.                     GLine RightLeg = new GLine(xRightLeg+HIP_WIDTH,yRightLeg,xRightLeg+HIP_WIDTH,yRightLeg+ LEG_LENGTH);
  103.                     add(RightHip);
  104.                     add(RightLeg);
  105.                 break;
  106.                
  107.                
  108.             case 7:
  109.                     double xLeftFoot = x/2-HIP_WIDTH-FOOT_LENGTH;
  110.                         double yLeftFoot =(y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH + HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH;
  111.                     GLine leftFoot = new GLine(xLeftFoot,yLeftFoot,xLeftFoot+FOOT_LENGTH,yLeftFoot);
  112.                     add(leftFoot);
  113.                 break;
  114.                
  115.                
  116.             case 8:
  117.                     double xRightFoot = x/2+HIP_WIDTH;
  118.                         double yRightFoot = (y-SCAFFOLD_HEIGHT-50)/2 + ROPE_LENGTH + HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH;
  119.                     GLine rightFoot = new GLine(xRightFoot,yRightFoot,xRightFoot+FOOT_LENGTH,yRightFoot);
  120.                     add(rightFoot);
  121.                 break;
  122.         }
  123.         }

  124. /* Constants for the simple version of the picture (in pixels) */
  125.         private static final int SCAFFOLD_HEIGHT = 360;
  126.         private static final int BEAM_LENGTH = 144;
  127.         private static final int ROPE_LENGTH = 18;
  128.         private static final int HEAD_RADIUS = 36;
  129.         private static final int BODY_LENGTH = 144;
  130.         private static final int ARM_OFFSET_FROM_HEAD = 28;
  131.         private static final int UPPER_ARM_LENGTH = 72;
  132.         private static final int LOWER_ARM_LENGTH = 44;
  133.         private static final int HIP_WIDTH = 36;
  134.         private static final int LEG_LENGTH = 108;
  135.         private static final int FOOT_LENGTH = 28;
  136.    
  137.         
  138.         private GLabel wrongList = new GLabel("");  
  139.         private GLabel wordInfo = new GLabel("");

  140. }
复制代码
  1. import java.io.*;
  2. import java.util.*;

  3. public class newHangmanLexicon {
  4.        
  5.         public newHangmanLexicon() {
  6.                
  7.                 try {
  8.                         rd = new BufferedReader(new FileReader("HangmanLexicon.txt"));//在try的里面
  9.                         while(true) {
  10.                                 String line = rd.readLine();
  11.                                 if(line==null) break;
  12.                                 lexicon.add(line);
  13.                         }
  14.                         rd.close();
  15.                 } catch(IOException ex) {
  16.                         System.out.println("Cannot read the file");//必须有System.out 光是println不行
  17.                 }
  18.         }
  19.         public int getWordCount() {
  20.                 return lexicon.size();
  21.         }
  22.         public String getWord(int index) {
  23.                 return lexicon.get(index);
  24.         }
  25.         private BufferedReader rd;
  26.         private ArrayList<String> lexicon = new ArrayList<String>();

  27. }
复制代码


回复

使用道具 举报

🔗
zhuolinliu8 2012-8-7 17:25:14 | 只看该作者
全局:
Hangman.java
  1. /*
  2. * File: Hangman.java
  3. * ------------------
  4. * This program will eventually play the Hangman game from
  5. * Assignment #4.
  6. */

  7. import acm.graphics.*;
  8. import acm.program.*;
  9. import acm.util.*;

  10. import java.awt.*;

  11. public class Hangman extends ConsoleProgram {
  12.        
  13.         private HangmanCanvas canvas = new HangmanCanvas();
  14.         private RandomGenerator rgen = RandomGenerator.getInstance();
  15.     private HangmanLexicon word_index = new HangmanLexicon();
  16.         private boolean flag;
  17.        
  18.         public void run() {
  19.                 /** Initialize */
  20.                 setLayout(new GridLayout(1,2));
  21.                 add(canvas);
  22.                 validate();
  23.                 canvas.reset();
  24.                
  25.             int time_left = 8;
  26.             char guess_char;
  27.             println("Welcome to Hangman!");
  28.            
  29.             /** Choose the word */
  30.             String answer = word_index.getWord(rgen.nextInt(0,word_index.getWordCount()-1));
  31.             String word_inpro = "";
  32.             for(int i = 0; i < answer.length(); i++)
  33.                     word_inpro = word_inpro + "-";
  34.             canvas.displayWord(word_inpro);
  35.            
  36.             /** Running main function */
  37.                 while(time_left > 0){
  38.                         println("The word now looks like this: "+ word_inpro);
  39.                         println("You have "+ time_left + " guesses left.");
  40.                         guess_char = Character.toUpperCase(readLine("Your guess: ").charAt(0));
  41.                         flag = false;
  42.                         word_inpro = replaceChar(answer, word_inpro,guess_char);
  43.                         if(flag == false){
  44.                                 time_left--;
  45.                                 canvas.noteIncorrectGuess(guess_char);
  46.                         }
  47.                         else canvas.displayWord(word_inpro);
  48.                         /** Correct answer */
  49.                         if(answer.equals(word_inpro)){
  50.                                 println("That guess is correct.\nYou guessed the word: " +
  51.                                                 answer + "\nYou win.");
  52.                                 break;
  53.                         }               
  54.                 }
  55.                
  56.                 if (time_left == 0) println("The word was: " + answer + "\nYou lose.");
  57.         }
  58.        
  59.         private String replaceChar(String ans, String str, char ch){
  60.                 String result = "";
  61.                 for(int i = 0; i< str.length(); i++){
  62.                         if(ans.charAt(i) == ch){
  63.                                 result += ch;
  64.                                 flag = true;
  65.                         }
  66.                         else result += str.charAt(i);
  67.                 }
  68.                 return result;
  69.         }

  70. }
复制代码
HangmanCanvas.java
  1. /*
  2. * File: HangmanCanvas.java
  3. * ------------------------
  4. * This file keeps track of the Hangman display.
  5. */

  6. import acm.graphics.*;
  7. import java.awt.*;

  8. public class HangmanCanvas extends GCanvas {

  9. /** Resets the display so that only the scaffold appears */
  10.         public void reset() {
  11.                 add(new GLine(50,50,50,50+SCAFFOLD_HEIGHT));
  12.                 add(new GLine(50,50,50+BEAM_LENGTH,50));
  13.                 add(new GLine(50+BEAM_LENGTH,50,50+BEAM_LENGTH,50+ROPE_LENGTH));
  14.         }

  15. /**
  16. * Updates the word on the screen to correspond to the current
  17. * state of the game.  The argument string shows what letters have
  18. * been guessed so far; unguessed letters are indicated by hyphens.
  19. */
  20.         public void displayWord(String word) {
  21.                 if(getElementAt(50,100+SCAFFOLD_HEIGHT)!=null)
  22.                         remove(getElementAt(50,100+SCAFFOLD_HEIGHT));
  23.                 GLabel word_display = new GLabel(word,50,100+SCAFFOLD_HEIGHT);
  24.                 word_display.setFont(new Font("TimesRoman", Font.PLAIN, 30));
  25.                 add(word_display);
  26.         }

  27. /**
  28. * Updates the display to correspond to an incorrect guess by the
  29. * user.  Calling this method causes the next body part to appear
  30. * on the scaffold and adds the letter to the list of incorrect
  31. * guesses that appears at the bottom of the window.
  32. */
  33.         private String error_guess="";
  34.         private int body_part = 0;
  35.         public void noteIncorrectGuess(char letter) {
  36.                 /** Wrong guesses at the bootom of the window */
  37.                 error_guess += letter;
  38.                 if(getElementAt(50,125+SCAFFOLD_HEIGHT)!=null)
  39.                         remove(getElementAt(50,125+SCAFFOLD_HEIGHT));
  40.                 GLabel error_display = new GLabel(error_guess,50,125+SCAFFOLD_HEIGHT);
  41.                 error_display.setFont(new Font("TimesRoman", Font.PLAIN, 20));
  42.                 add(error_display);
  43.                
  44.                 /** Draw body part */
  45.                 switch(++body_part){
  46.                 case 1: add(new GOval(50+BEAM_LENGTH-HEAD_RADIUS,50+ROPE_LENGTH,HEAD_RADIUS*2,HEAD_RADIUS*2));
  47.                                 break;  //head
  48.                 case 2: add(new GLine(50+BEAM_LENGTH,LEG_BEGIN-BODY_LENGTH,50+BEAM_LENGTH,LEG_BEGIN));
  49.                                 break; //body
  50.                 case 3:        add(new GLine(50+BEAM_LENGTH,ARM_BEGIN,50+BEAM_LENGTH-UPPER_ARM_LENGTH,ARM_BEGIN));
  51.                                 add(new GLine(50+BEAM_LENGTH-UPPER_ARM_LENGTH,ARM_BEGIN,50+BEAM_LENGTH-UPPER_ARM_LENGTH,
  52.                                                 ARM_BEGIN+LOWER_ARM_LENGTH));
  53.                                 break;  //left arm
  54.                 case 4:        add(new GLine(50+BEAM_LENGTH,ARM_BEGIN,50+BEAM_LENGTH+UPPER_ARM_LENGTH,ARM_BEGIN));
  55.                                 add(new GLine(50+BEAM_LENGTH+UPPER_ARM_LENGTH,ARM_BEGIN,50+BEAM_LENGTH+UPPER_ARM_LENGTH,
  56.                                                 ARM_BEGIN+LOWER_ARM_LENGTH));
  57.                                 break;        //right arm
  58.                 case 5: add(new GLine(50+BEAM_LENGTH,LEG_BEGIN,50+BEAM_LENGTH-HIP_WIDTH,LEG_BEGIN));
  59.                                 add(new GLine(50+BEAM_LENGTH-HIP_WIDTH,LEG_BEGIN,50+BEAM_LENGTH-HIP_WIDTH,
  60.                                                 LEG_BEGIN+LEG_LENGTH));
  61.                                 break; //left leg
  62.                 case 6: add(new GLine(50+BEAM_LENGTH,LEG_BEGIN,50+BEAM_LENGTH+HIP_WIDTH,LEG_BEGIN));
  63.                                 add(new GLine(50+BEAM_LENGTH+HIP_WIDTH,LEG_BEGIN,50+BEAM_LENGTH+HIP_WIDTH,
  64.                                                 LEG_BEGIN+LEG_LENGTH));
  65.                                 break; //right leg
  66.                 case 7:        add(new GLine(50+BEAM_LENGTH-HIP_WIDTH,LEG_BEGIN+LEG_LENGTH,
  67.                                                 50+BEAM_LENGTH-HIP_WIDTH-FOOT_LENGTH,LEG_BEGIN+LEG_LENGTH));
  68.                                 break; //left foot       
  69.                 case 8: add(new GLine(50+BEAM_LENGTH+HIP_WIDTH,LEG_BEGIN+LEG_LENGTH,
  70.                                                 50+BEAM_LENGTH+HIP_WIDTH+FOOT_LENGTH,LEG_BEGIN+LEG_LENGTH));//right foot
  71.                 }
  72.         }

  73. /* Constants for the simple version of the picture (in pixels) */
  74.         private static final int SCAFFOLD_HEIGHT = 360;
  75.         private static final int BEAM_LENGTH = 144;
  76.         private static final int ROPE_LENGTH = 18;
  77.         private static final int HEAD_RADIUS = 36;
  78.         private static final int BODY_LENGTH = 144;
  79.         private static final int ARM_OFFSET_FROM_HEAD = 28;
  80.         private static final int UPPER_ARM_LENGTH = 72;
  81.         private static final int LOWER_ARM_LENGTH = 44;
  82.         private static final int HIP_WIDTH = 36;
  83.         private static final int LEG_LENGTH = 108;
  84.         private static final int FOOT_LENGTH = 28;
  85.         private static final int LEG_BEGIN = 50+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH;
  86.         private static final int ARM_BEGIN = LEG_BEGIN-BODY_LENGTH+ARM_OFFSET_FROM_HEAD;
  87. }
复制代码
HangmanLexicon.java
  1. /*
  2. * File: HangmanLexicon.java
  3. * -------------------------
  4. * This file contains a stub implementation of the HangmanLexicon
  5. * class that you will reimplement for Part III of the assignment.
  6. */

  7. import acm.util.*;
  8. import java.util.*;
  9. import java.io.*;

  10. public class HangmanLexicon {
  11.         private ArrayList<String> dic = new ArrayList<String>();
  12.        
  13.         HangmanLexicon(){
  14.                 BufferedReader rd = null;
  15.                 try{
  16.                         rd = new BufferedReader(new FileReader("HangmanLexicon.txt"));
  17.                         String line = rd.readLine();
  18.                         while(line != null){
  19.                                 dic.add(line);
  20.                                 line = rd.readLine();
  21.                         }
  22.                         rd.close();
  23.                 } catch (IOException ex){System.out.println("NO FILE!");}
  24.         }

  25. /** Returns the number of words in the lexicon. */
  26.         public int getWordCount() {
  27.                 return dic.size();
  28.         }

  29. /** Returns the word at the specified index. */
  30.         public String getWord(int index) {
  31.                 return dic.get(index);
  32.         }
  33. }
复制代码
回复

使用道具 举报

🔗
gotoo 2012-8-8 11:14:48 | 只看该作者
全局:
我错了 这周social的太多了 明天开始赶上进度!
回复

使用道具 举报

🔗
 楼主| yiyiyaya 2012-8-8 19:47:54 | 只看该作者
全局:
gotoo 发表于 2012-8-8 11:14
我错了 这周social的太多了 明天开始赶上进度!

加油哈!
回复

使用道具 举报

🔗
nprotect 2012-8-12 03:25:39 | 只看该作者
全局:
本帖最后由 nprotect 于 2012-8-12 03:55 编辑

实际上,这次作业需要用到数组的,做到最后才发现,在17,18,19里面讲的吧。程序写的比较粗糙,字体也没调。 不过,这次作业我个人感觉最难的在Hangman部分中如何排除单词的重复字母上,比如说hubble中的两个b, fuzzy中的两个z,甚至还有3个相同的字母。 貌似indexOf方法只能返回最先的索引,在这里得设计循环排除已经找到的,相同的字母。 先贴上吧。。。已经迟了。
回复

使用道具 举报

🔗
nprotect 2012-8-12 03:58:11 | 只看该作者
全局:
本帖最后由 nprotect 于 2012-8-12 04:04 编辑

Hangman:
  1. /*
  2. * File: Hangman.java
  3. * ------------------
  4. * This program will eventually play the Hangman game from
  5. * Assignment #4.
  6. */

  7. import acm.graphics.*;
  8. import acm.program.*;
  9. import acm.util.*;

  10. import java.awt.*;

  11. public class Hangman extends ConsoleProgram {

  12. private int index; // the index of the word chosen by program for people to guess
  13. private int indexOfStr; // the index of string "-------"
  14. private int chance = 8; // chances for try
  15. private char c; // read the input word
  16. private String str = ""; // Initialization str for empty
  17. private HangmanCanvas canvas; // object "canvas" belong to the class "HangmanCanvas"
  18. private RandomGenerator rgen = RandomGenerator.getInstance();

  19. /** add canvas besides console program*/
  20. public void init(){
  21. canvas = new HangmanCanvas();
  22. add(canvas);
  23. }
  24. /** main method*/
  25. public void run() {
  26. println("Welcome to Hangman!");
  27. HangmanLexicon HangObject = new HangmanLexicon();
  28. int r1 = HangObject.getWordCount(); // return how many words the list have
  29. int r2 = rgen.nextInt(1, r1); // random number
  30. String returnWords = HangObject.getWord(r2); //returnWords store a random word
  31. int Num = returnWords.length(); // Num store word's length
  32. println("For testing, I give your the word: " +returnWords); // Only for testing the program
  33. /** initialize string str for "-------", output begin words*/
  34. for (int i=0; i<Num; i++) str += "-";
  35. println("The word now looks like this: "+str);
  36. println("You have 8 guesses left");
  37. canvas.reset();
  38. while (chance>0){
  39. String temp = readLine("Your Guess: ");
  40. c = temp.charAt(0); // read the input word and store it in char c
  41. indexOfStr = str.indexOf(c); // read index of c in str, store it in indexOfStr
  42. if (indexOfStr !=-1) { // indexOfStr != -1 means already exist same word in str
  43. int temp2 = indexOfStr;
  44. while (temp2 !=-1){
  45. indexOfStr = temp2;
  46. temp2 = str.indexOf(c, indexOfStr+1); //temp2 =-1,jump out of while loop
  47. }
  48. index = returnWords.indexOf(c, indexOfStr+1);
  49. judgeForReplace();
  50. }
  51. else { // indexOfStr =-1 means no same word in str
  52. index = returnWords.indexOf(c);
  53. judgeForReplace();
  54. }
  55. }
  56. println("You have no chance for guess, YOU LOSE!");
  57. }
  58. /** method: judgeForReplace()*/
  59. private void judgeForReplace(){
  60. if (index !=-1){
  61. str = str.substring(0, index)+c+str.substring(index+1); // replace the letter
  62. canvas.displayWord(str);
  63. println("That guess is correct.");
  64. println("The word now looks like this: "+str);
  65. println("You have " + chance + " guesses left.");
  66. }
  67. else {
  68. println("There are no "+ c +" in the words");
  69. println("The word now looks like this: "+str);
  70. chance--;
  71. println("You have " + chance + " guesses left.");
  72. canvas.noteIncorrectGuess(c);
  73. }
  74. }
  75. } // class ends
复制代码

HangmanCanvas:
  1. /*
  2. * File: HangmanCanvas.java
  3. * ------------------------
  4. * This file keeps track of the Hangman display.
  5. */

  6. import acm.graphics.*;

  7. public class HangmanCanvas extends GCanvas {
  8. /** Resets the display so that only the scaffold appears */
  9. public void reset() {
  10. GLine scaffold = new GLine(getWidth()/2-BEAM_LENGTH, BEAM_OFFSET_FROM_TOP, getWidth()/2-BEAM_LENGTH, SCAFFOLD_HEIGHT+BEAM_OFFSET_FROM_TOP);
  11. GLine beam = new GLine (getWidth()/2-BEAM_LENGTH, BEAM_OFFSET_FROM_TOP, getWidth()/2, BEAM_OFFSET_FROM_TOP);
  12. GLine rope = new GLine (getWidth()/2, BEAM_OFFSET_FROM_TOP, getWidth()/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH);
  13. add(scaffold);
  14. add(beam);
  15. add(rope);
  16. }
  17. /**
  18. * Updates the word on the screen to correspond to the current
  19. * state of the game. The argument string shows what letters have
  20. * been guessed so far; unguessed letters are indicated by hyphens.
  21. */
  22. public void displayWord(String word) {
  23. GLabel flag = new GLabel(word, getWidth()/2-BEAM_LENGTH, SCAFFOLD_HEIGHT+BEAM_OFFSET_FROM_TOP+20);
  24. add(flag);
  25. }
  26. /**
  27. * Updates the display to correspond to an incorrect guess by the
  28. * user. Calling this method causes the next body part to appear
  29. * on the scaffold and adds the letter to the list of incorrect
  30. * guesses that appears at the bottom of the window.
  31. */
  32. public void noteIncorrectGuess(char letter) {
  33. GOval head = new GOval (getWidth()/2-HEAD_RADIUS, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH, HEAD_RADIUS*2, HEAD_RADIUS*2);
  34. GLine body = new GLine (getWidth()/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2, getWidth()/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH);
  35. GLine leftArm1 = new GLine (getWidth()/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD, getWidth()/2-UPPER_ARM_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD);
  36. GLine leftArm2 = new GLine (getWidth()/2-UPPER_ARM_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD, getWidth()/2-UPPER_ARM_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD+LOWER_ARM_LENGTH);
  37. GLine rightArm1 = new GLine (getWidth()/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD, getWidth()/2+UPPER_ARM_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD);
  38. GLine rightArm2 = new GLine (getWidth()/2+UPPER_ARM_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD, getWidth()/2+UPPER_ARM_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+ARM_OFFSET_FROM_HEAD+LOWER_ARM_LENGTH);
  39. GLine leftLeg1 = new GLine (getWidth()/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH, getWidth()/2-HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH);
  40. GLine leftLeg2 = new GLine (getWidth()/2-HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH, getWidth()/2-HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH);
  41. GLine rightLeg1 = new GLine (getWidth()/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH, getWidth()/2+HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH);
  42. GLine rightLeg2 = new GLine (getWidth()/2+HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH, getWidth()/2+HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH);
  43. GLine leftFoot = new GLine (getWidth()/2-HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH, getWidth()/2-HIP_WIDTH/2-FOOT_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH);
  44. GLine rightFoot = new GLine (getWidth()/2+HIP_WIDTH/2, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH, getWidth()/2+HIP_WIDTH/2+FOOT_LENGTH, BEAM_OFFSET_FROM_TOP+ROPE_LENGTH+HEAD_RADIUS*2+BODY_LENGTH+LEG_LENGTH);
  45. str += letter;
  46. GLabel lab = new GLabel (str, getWidth()/2-BEAM_LENGTH, SCAFFOLD_HEIGHT+BEAM_OFFSET_FROM_TOP+40);
  47. add(lab);
  48. int leng = str.length();
  49. switch (leng){
  50. case 1: add(head); break;
  51. case 2: add(body); break;
  52. case 3: add(leftArm1); add(leftArm2); break;
  53. case 4: add(rightArm1); add(rightArm2); break;
  54. case 5: add(leftLeg1); add(leftLeg2); break;
  55. case 6: add(rightLeg1); add(rightLeg2); break;
  56. case 7: add(leftFoot); break;
  57. case 8: add(rightFoot); break;
  58. }
  59. }
  60. /** Constants for the simple version of the picture (in pixels) */
  61. private static final int BEAM_OFFSET_FROM_TOP = 40;
  62. private static final int SCAFFOLD_HEIGHT = 360;
  63. private static final int BEAM_LENGTH = 144;
  64. private static final int ROPE_LENGTH = 18;
  65. private static final int HEAD_RADIUS = 36;
  66. private static final int BODY_LENGTH = 144;
  67. private static final int ARM_OFFSET_FROM_HEAD = 28;
  68. private static final int UPPER_ARM_LENGTH = 72;
  69. private static final int LOWER_ARM_LENGTH = 44;
  70. private static final int HIP_WIDTH = 36;
  71. private static final int LEG_LENGTH = 108;
  72. private static final int FOOT_LENGTH = 28;
  73. private String str = ""; // store the input wrong letter
  74. }
复制代码
HangmanLexicon:
  1. /*
  2. * File: HangmanLexicon.java
  3. * -------------------------
  4. * This file contains a stub implementation of the HangmanLexicon
  5. * class that you will reimplement for Part III of the assignment.
  6. */

  7. import acm.util.*;
  8. import java.util.*;
  9. import java.io.*;

  10. public class HangmanLexicon {
  11. private ArrayList<String> ShorterLexicon = new ArrayList<String>(); //ArrayList, String type
  12. HangmanLexicon(){
  13. BufferedReader rd = null;
  14. try{
  15. rd = new BufferedReader(new FileReader("ShorterLexicon.txt"));
  16. String line = rd.readLine(); // read the first line of word
  17. while(line != null){
  18. ShorterLexicon.add(line); // add word line by line in ArrayList
  19. line = rd.readLine(); // read the next line of word
  20. }
  21. rd.close();
  22. }
  23. catch (IOException ex){System.out.println("CANNOT FIND THE FILE");}
  24. }
  25. public int getWordCount() {
  26. return ShorterLexicon.size(); // return the number of elements in this list
  27. }
  28. public String getWord(int index) {
  29. return ShorterLexicon.get(index); // Returns the element at the specified position in this list
  30. }
  31. }
复制代码

回复

使用道具 举报

🔗
nprotect 2012-8-12 04:05:23 | 只看该作者
全局:
为啥我贴上来开头都对齐了
回复

使用道具 举报

🔗
 楼主| yiyiyaya 2012-8-12 11:16:00 | 只看该作者
全局:
nprotect 发表于 2012-8-12 04:05
为啥我贴上来开头都对齐了

可以重新再贴一次,应该就会好了
回复

使用道具 举报

🔗
jasonilove 2012-8-14 17:12:47 | 只看该作者
全局:
Hangman
  1. import acm.graphics.*;
  2. import acm.program.*;
  3. import acm.util.*;

  4. import java.awt.*;



  5. public class Hangman extends ConsoleProgram {
  6.        
  7.         private static final int GUESS_TIMES=8;
  8.        
  9.         public void init(){
  10.                 canvas=new HangmanCanvas();
  11.                 add(canvas);
  12.         }

  13.     public void run() {
  14.             guessLeft=GUESS_TIMES;
  15.             canvas.reset();
  16.             println("Welcome to Hangman!");           
  17.                 String word=getAWord();
  18.                 String wordVisible=initiate(word);
  19.                 while(true){
  20.                         println("The word now looks like this: "+wordVisible);
  21.                         println("You have "+guessLeft+" guesses left.");
  22.                         char cha=guessedChar();
  23.                         if(word.indexOf(cha)==-1){
  24.                                 println("There is no "+cha+"'s in the word.");
  25.                                 canvas.noteIncorrectGuess(cha);
  26.                                 guessLeft--;
  27.                         }
  28.                         else{
  29.                                 println("The guess is correct.");
  30.                                 wordVisible=updateWord(wordVisible,word,cha);
  31.                                 println("The word now looks like this: "+wordVisible);

  32.                         }
  33.                         canvas.displayWord(wordVisible);
  34.                         if(guessLeft==0){
  35.                                 println("You're completely hung.");
  36.                                 println("The word was: "+word);
  37.                                 println("You lose.");
  38.                                 return;
  39.                         }
  40.                         else if(word.equals(wordVisible)){
  41.                                 println("You win.");
  42.                                 return;
  43.                         }                       
  44.                 }               
  45.         }
  46.    
  47.     private String updateWord(String str, String word,char cha){
  48.             int i=0;
  49.             while(true){
  50.                     if(word.indexOf(cha,i)==-1){
  51.                             return str;
  52.                     }
  53.                     else {
  54.                             str=str.substring(0,word.indexOf(cha, i))+cha+str.substring(word.indexOf(cha, i)+1);
  55.                             i=word.indexOf(cha, i)+1;
  56.                     }
  57.             }
  58.     }
  59.    
  60.     private char guessedChar(){
  61.             while(true){
  62.                     String str=readLine("Your guess: ");
  63.                     if(str.length()==1){
  64.                             char a=str.charAt(0);
  65.                             if(a>='A'&&a<='Z'){
  66.                                     return a;
  67.                             }
  68.                             if(a>='a'&&a<='z'){
  69.                                     return (char)(a+'A'-'a');
  70.                             }
  71.                     }
  72.                         println("Not valid.");
  73.             }
  74.     }
  75.    
  76.     private String initiate(String a){
  77.             String b="";
  78.             for(int i=0;i<a.length();i++){
  79.                     b+="-";
  80.             }
  81.             return b;
  82.     }
  83.    
  84.     private String getAWord(){
  85.             int a=rgen.nextInt(0,lex.getWordCount());
  86.             return lex.getWord(a);
  87.     }
  88.     private HangmanLexicon lex=new HangmanLexicon();
  89.     private RandomGenerator rgen=new RandomGenerator();
  90.     private int guessLeft;
  91.     private HangmanCanvas canvas;

  92. }
复制代码
HangmanCanvas
  1. import acm.graphics.*;

  2. public class HangmanCanvas extends GCanvas {
  3.        
  4.         private GLabel label=new GLabel("");
  5.         private String wrongGuesses="";
  6.         private GLabel labelOfWrongGuess=new GLabel("");
  7.         private int wrongTimes=0;

  8. /** Resets the display so that only the scaffold appears */
  9.         public void reset() {
  10.                 removeAll();
  11.                 int startPointX=getWidth()/2-BEAM_LENGTH;
  12.                 int startPointY=getHeight()/2-BODY_LENGTH-2*HEAD_RADIUS-ROPE_LENGTH;
  13.                 add(new GLine(startPointX,startPointY,startPointX,startPointY+SCAFFOLD_HEIGHT));
  14.                 add(new GLine(startPointX,startPointY,startPointX+BEAM_LENGTH,startPointY));
  15.                 add(new GLine(startPointX+BEAM_LENGTH,startPointY,startPointX+BEAM_LENGTH,startPointY+ROPE_LENGTH));
  16.                 add(label);
  17.                 add(labelOfWrongGuess);
  18.                
  19.         }

  20. /**
  21. * Updates the word on the screen to correspond to the current
  22. * state of the game.  The argument string shows what letters have
  23. * been guessed so far; unguessed letters are indicated by hyphens.
  24. */
  25.         public void displayWord(String word) {
  26.                 label.setLabel(word);
  27.                 label.setLocation(getWidth()/2-BEAM_LENGTH,getHeight()/2-BODY_LENGTH-2*HEAD_RADIUS-ROPE_LENGTH+SCAFFOLD_HEIGHT+2*label.getAscent());
  28.                 switch(wrongTimes){
  29.                 case 0:add(new GOval(getWidth()/2-HEAD_RADIUS,getHeight()/2-BODY_LENGTH-2*HEAD_RADIUS,2*HEAD_RADIUS,2*HEAD_RADIUS));break;
  30.                 case 1:add(new GLine(getWidth()/2,getHeight()/2-BODY_LENGTH,getWidth()/2,getHeight()/2));break;
  31.                 case 2:add(new GLine(getWidth()/2,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD,getWidth()/2-UPPER_ARM_LENGTH,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD));
  32.                                 add(new GLine(getWidth()/2-UPPER_ARM_LENGTH,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD,getWidth()/2-UPPER_ARM_LENGTH,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD+LOWER_ARM_LENGTH));
  33.                                 break;
  34.                 case 3:add(new GLine(getWidth()/2,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD,getWidth()/2+UPPER_ARM_LENGTH,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD));
  35.                                 add(new GLine(getWidth()/2+UPPER_ARM_LENGTH,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD,getWidth()/2+UPPER_ARM_LENGTH,getHeight()/2-BODY_LENGTH+ARM_OFFSET_FROM_HEAD+LOWER_ARM_LENGTH));
  36.                                 break;
  37.                 case 4:add(new GLine(getWidth()/2,getHeight()/2,getWidth()/2-HIP_WIDTH,getHeight()/2));
  38.                                 add(new GLine(getWidth()/2-HIP_WIDTH,getHeight()/2,getWidth()/2-HIP_WIDTH,getHeight()/2+LEG_LENGTH));
  39.                                 break;
  40.                 case 5:add(new GLine(getWidth()/2-HIP_WIDTH,getHeight()/2+LEG_LENGTH,getWidth()/2-HIP_WIDTH-FOOT_LENGTH,getHeight()/2+LEG_LENGTH));
  41.                                 break;
  42.                 case 6:add(new GLine(getWidth()/2,getHeight()/2,getWidth()/2+HIP_WIDTH,getHeight()/2));
  43.                                 add(new GLine(getWidth()/2+HIP_WIDTH,getHeight()/2,getWidth()/2+HIP_WIDTH,getHeight()/2+LEG_LENGTH));
  44.                                 break;
  45.                 default:add(new GLine(getWidth()/2+HIP_WIDTH,getHeight()/2+LEG_LENGTH,getWidth()/2+HIP_WIDTH+FOOT_LENGTH,getHeight()/2+LEG_LENGTH));
  46.                                 break;
  47.                 }
  48.                 wrongTimes++;
  49.         }

  50. /**
  51. * Updates the display to correspond to an incorrect guess by the
  52. * user.  Calling this method causes the next body part to appear
  53. * on the scaffold and adds the letter to the list of incorrect
  54. * guesses that appears at the bottom of the window.
  55. */
  56.         public void noteIncorrectGuess(char letter) {
  57.                 wrongGuesses+=letter;
  58.                 labelOfWrongGuess.setLabel(wrongGuesses);
  59.                 labelOfWrongGuess.setLocation(getWidth()/2-BEAM_LENGTH,getHeight()-2*label.getAscent());
  60.                
  61.         }

  62. /* Constants for the simple version of the picture (in pixels) */
  63.         private static final int SCAFFOLD_HEIGHT = 360;
  64.         private static final int BEAM_LENGTH = 144;
  65.         private static final int ROPE_LENGTH = 18;
  66.         private static final int HEAD_RADIUS = 36;
  67.         private static final int BODY_LENGTH = 144;
  68.         private static final int ARM_OFFSET_FROM_HEAD = 28;
  69.         private static final int UPPER_ARM_LENGTH = 72;
  70.         private static final int LOWER_ARM_LENGTH = 44;
  71.         private static final int HIP_WIDTH = 36;
  72.         private static final int LEG_LENGTH = 108;
  73.         private static final int FOOT_LENGTH = 28;

  74. }
复制代码
HangmanLexicon
  1. import acm.util.*;
  2. import java.util.*;
  3. import java.io.*;

  4. public class HangmanLexicon {
  5.         private ArrayList<String> strList=new ArrayList<String>();
  6.        
  7.         public HangmanLexicon(){
  8.                 try{
  9.                         BufferedReader rd=new BufferedReader(new FileReader("HangmanLexicon.txt"));
  10.                         while(true){
  11.                                 String line=rd.readLine();
  12.                                 if(line==null){
  13.                                         break;
  14.                                 }
  15.                                 else{
  16.                                         strList.add(line);
  17.                                 }
  18.                         }
  19.                         rd.close();
  20.                 }
  21.                 catch(IOException ex){
  22.                         throw new ErrorException(ex);
  23.                 }
  24.         }

  25. /** Returns the number of words in the lexicon. */
  26.         public int getWordCount() {
  27.                 return strList.size();
  28.         }

  29. /** Returns the word at the specified index. */
  30.         public String getWord(int index) {
  31.                 return strList.get(index);
  32.                 }
  33.         }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表