楼主: yiyiyaya
跳转到指定楼层
上一主题 下一主题
收起左侧

Stanford CS106A #3 Assignment3讨论贴

无效楼层,该帖已经被删除
🔗
zuohr 2012-10-7 09:13:32 | 只看该作者
全局:
求教一个课本上的习题(The art and science of Java:Chapter 9 Programming exercise 11题)
如何在GLabel的实例上添加MouseListener,当点击这个对象时实现一定的操作?
问题背景是这样的,这个习题要求创建以颜色名字为内容的GLabel,比如RED,BLUE,但是显示随机的颜色,当鼠标点住这个GLabel时,暂时显示和名字相同的颜色,鼠标放开的时候又显示随机颜色。
如果用课上介绍的方法,用getElementAt(),返回的是GObject对象,返回的GObject就没法判断GLabel的字符串内容了,进而就无法给他设定特点的颜色了。
所以我想应该是在每个GLabel上添加MouseListeners,当这个GLabel检测到点击的时候实现对这个对象操作,这样应该就可以用GLabel里的Method了。
我看到GLabel有addMouseListener(MouseListener listener)这个method,但是里面要传递一个MouseListener对象,请问这个对象在哪里定义,如何定义?
谢谢。
回复

使用道具 举报

🔗
zjlxz 2013-3-18 13:53:14 | 只看该作者
全局:
本帖最后由 zjlxz 于 2013-3-18 13:57 编辑

怎么样能粘出像ls这样的代码。。。

回复

使用道具 举报

全局:
昨天被move恶心了好久,今天好容易能正常运行了实话说最后判输赢那里实在不想管了……brick count总是传不到位,但是实在不想动脑子了。。。。就这样吧。。。
最后就变成输三次显示youlose,但是赢了也会继续bounce输三次又是you lose,比较残酷。不能理解的是为什么偶尔球可以打到最底端还能弹起来,虽然出现这种情况的概率不多,但是明明没有写在碰到底端弹起来的代码啊……完全不能理解
  1. /*
  2. * File: Breakout.java
  3. * -------------------
  4. * Name:
  5. * Section Leader:
  6. *
  7. * This file will eventually implement the game of Breakout.
  8. */

  9. import acm.graphics.*;
  10. import acm.program.*;
  11. import acm.util.*;

  12. import java.applet.*;
  13. import java.awt.*;
  14. import java.awt.event.*;

  15. public class Breakout extends GraphicsProgram {

  16. /** Width and height of application window in pixels */
  17.         public static final int APPLICATION_WIDTH = 400;
  18.         public static final int APPLICATION_HEIGHT = 600;

  19. /** Dimensions of game board (usually the same) */
  20.         private static final int WIDTH = APPLICATION_WIDTH;
  21.         private static final int HEIGHT = APPLICATION_HEIGHT;

  22. /** Dimensions of the paddle */
  23.         private static final int PADDLE_WIDTH = 60;
  24.         private static final int PADDLE_HEIGHT = 10;

  25. /** Offset of the paddle up from the bottom */
  26.         private static final int PADDLE_Y_OFFSET = 30;

  27. /** Number of bricks per row */
  28.         private static final int NBRICKS_PER_ROW = 10;

  29. /** Number of rows of bricks */
  30.         private static final int NBRICK_ROWS = 10;

  31. /** Separation between bricks */
  32.         private static final int BRICK_SEP = 4;

  33. /** Width of a brick */
  34.         private static final int BRICK_WIDTH =
  35.           (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;

  36. /** Height of a brick */
  37.         private static final int BRICK_HEIGHT = 8;

  38. /** Radius of the ball in pixels */
  39.         private static final int BALL_RADIUS = 10;

  40. /** Offset of the top brick row from the top */
  41.         private static final int BRICK_Y_OFFSET = 70;

  42. /** Number of turns */
  43.         private static final int NTURNS = 3;
  44.        
  45.        
  46.         public void init(){
  47.                 addMouseListeners();
  48.         }
  49.        
  50.        
  51. /* Method: run() */
  52. /** Runs the Breakout program. */
  53.         public void run() {
  54.                 /* You fill this in, along with any subsidiary methods */
  55.                 addBricks();       
  56.                 addPaddle();
  57.                 //must be needed for moving paddle, otherwise .java will not run normally when mouse is in window
  58.                 //not sure but guess this one is to notify run() method that there is a paddle exist
  59.                 addBall();
  60.                 while(true){
  61.                         processGame();
  62.                 if(gameOver()){
  63.                         addBall();
  64.                         processGame();
  65.                         life--;
  66.                 }
  67.                 if(life==0){
  68.                         GLabel label=new GLabel("you lose", 195, 300);
  69.                         add(label);
  70.                         break;
  71.                 }
  72.                
  73.                
  74.                 }
  75.                
  76.                
  77.                
  78.                

  79.         }       
  80.        
  81.         private void processGame(){
  82.                 while(!gameOver()){
  83.                         ball.move(vx,vy);
  84.                         if(ball.getX()+BALL_RADIUS>=getWidth() || ball.getX()<=0){
  85.                                 vx=-vx;
  86.                                 ball.move(vx,vy);
  87.                         }
  88.                         if(ball.getY()<=0){
  89.                                 vy=-vy;
  90.                                 ball.move(vx,vy);
  91.                         }
  92.                        
  93.                         getCollidingObject();
  94.                        
  95.                        
  96.                        
  97.                         pause(10);
  98.                         //pause must be in while, with moveball. moveball must be in while
  99.         }
  100.         }
  101.        
  102.         private void getCollidingObject(){
  103.                
  104.                 for (int i=0;i<2;i++){
  105.                         for (int j=0;j<2;j++){
  106.                                 GObject collider = getElementAt(ball.getX()+i*BALL_RADIUS,ball.getY()+j*BALL_RADIUS);
  107.                 if (collider!=null){
  108.                 if(collider==Paddle){
  109.                         vy=-vy;
  110.                         ball.move(vx,vy);
  111.                 }  else  {
  112.                        
  113.                         vy=-vy;
  114.                         ball.move(vx,vy);
  115.                         remove(collider);
  116.                        
  117.                                        
  118.                         //cannot write "if(collider==rect){..." since it only recognize the last rect added,
  119.                         //and the ball will pass through all other rects. but the only colliders beside the paddle are the bricks,
  120.                         //so using exclusion method the rects can be figured out.
  121.                        
  122.                 }
  123.                 }
  124.                
  125.                         }
  126.                 }
  127.                
  128.                
  129.         }
  130.        
  131.        
  132.         private boolean gameOver(){
  133.                 return(ball.getY()>=getHeight());
  134.         }
  135.        
  136.        
  137.         private void addPaddle(){
  138.                 Paddle=new GRect(PADDLE_WIDTH,PADDLE_HEIGHT);
  139.                 Paddle.setFilled(true);
  140.                
  141.         }
  142.        
  143.         public void mouseMoved(MouseEvent e){
  144.                 if(e.getX() <= WIDTH-PADDLE_WIDTH/2 && PADDLE_WIDTH/2<=e.getX()){
  145.                         add(Paddle,0,getHeight()-PADDLE_Y_OFFSET-PADDLE_HEIGHT/2);  
  146.                         //must be in mouseMoved method; if in run() method, paddle will disappear when mouse moves
  147.                         Paddle.move(e.getX()-PADDLE_WIDTH/2, 0);
  148.                 } else if (e.getX() > WIDTH-PADDLE_WIDTH/2){
  149.                         add(Paddle,WIDTH-PADDLE_WIDTH,getHeight()-PADDLE_Y_OFFSET-PADDLE_HEIGHT/2);
  150.                 }
  151.                
  152.         }
  153.        
  154.         private void addBall(){
  155.                 ball=new GOval(BALL_RADIUS,BALL_RADIUS);
  156.                 ball.setFilled(true);
  157.                 add(ball,WIDTH/2-BALL_RADIUS,HEIGHT/2-BALL_RADIUS);
  158.                
  159.         }
  160.        
  161.        
  162.        
  163.        
  164.        
  165.        
  166.        
  167.         private void addBricks(){
  168.                 addTwoRows(Color.RED, BRICK_Y_OFFSET);
  169.                 addTwoRows(Color.ORANGE,(BRICK_HEIGHT+BRICK_SEP)*2+BRICK_Y_OFFSET);
  170.                 addTwoRows(Color.YELLOW,(BRICK_HEIGHT+BRICK_SEP)*4+BRICK_Y_OFFSET);
  171.                 addTwoRows(Color.GREEN,(BRICK_HEIGHT+BRICK_SEP)*6+BRICK_Y_OFFSET);
  172.                 addTwoRows(Color.CYAN,(BRICK_HEIGHT+BRICK_SEP)*8+BRICK_Y_OFFSET);
  173.                 }
  174.        
  175.         private void addTwoRows(Color x, double y){
  176.                 double center =(WIDTH-(NBRICK_ROWS*BRICK_WIDTH+(NBRICK_ROWS-1)*BRICK_SEP))/2;
  177.                 for(int j=0;j<2;j++){
  178.                         for(int i=0;i<NBRICKS_PER_ROW;i++){
  179.                                 rect=new GRect(center+(BRICK_WIDTH+BRICK_SEP)*i,y+(BRICK_HEIGHT+BRICK_SEP)*j,BRICK_WIDTH,BRICK_HEIGHT);
  180.                                 rect.setFilled(true);
  181.                                 rect.setColor(x);
  182.                                 add(rect);
  183.                         }
  184.                 }
  185.         }
  186.                
  187.         private int life=2;
  188.         private GRect rect;
  189.         private GRect Paddle;
  190.         private GOval ball;
  191.         private RandomGenerator rgen=RandomGenerator.getInstance();
  192.         private double vx=rgen.nextDouble(1.0,3.0), vy=3.0;{
  193.         if(rgen.nextBoolean(0.5))vx=-vx;
  194.         }
  195.         //must state true vx here, otherwise if only denote vx and vy, default velocity would be 0 and ball wouldn't bounce back
  196.         //
  197. }
复制代码
回复

使用道具 举报

🔗
littlelab 2013-7-18 13:40:58 | 只看该作者
全局:
还在进行吗?花了一个星期的时间,在实验之余写了个带声音带分数的。(不知道直接粘贴上来行不行,见笑了)

/*
* File: Breakout.java
* -------------------
* Name:
* Section Leader:
*
* This file will eventually implement the game of Breakout.
*/

import acm.graphics.*;
import acm.program.*;
import acm.util.*;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Breakout extends GraphicsProgram {

/** Width and height of application window in pixels */
        public static final int APPLICATION_WIDTH = 400;
        public static final int APPLICATION_HEIGHT = 600;

/** Dimensions of game board
*  Should not be used directly (use getWidth()/getHeight() instead).
*  * */
        private static final int WIDTH = APPLICATION_WIDTH;
        private static final int HEIGHT = APPLICATION_HEIGHT;

/** Dimensions of the paddle */
        private static final int PADDLE_WIDTH = 60;
        private static final int PADDLE_HEIGHT = 10;

/** Offset of the paddle up from the bottom */
        private static final int PADDLE_Y_OFFSET = 30;

/** Number of bricks per row */
        private static final int NBRICKS_PER_ROW = 10;

/** Number of rows of bricks */
        private static final int NBRICK_ROWS = 10;

/** Separation between bricks */
        private static final int BRICK_SEP = 4;

/** Width of a brick */
        private static final int BRICK_WIDTH =
          (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;

/** Height of a brick */
        private static final int BRICK_HEIGHT = 8;

/** Radius of the ball in pixels */
        private static final int BALL_RADIUS = 12;

/** Offset of the top brick row from the top */
        private static final int BRICK_Y_OFFSET = 70;

/** Number of turns */
       
        private static final int NTURNS = 5;  // number of turns

        private int started = 0;  // A flag to determine whether playGame should respond to mouse click
        private int ready = 0;    // A flay to determine whether it is ready to clean canvas
        private int stopped = 0;  // A flay to determin whether the game is paused
        private GOval ball;
        private GRect paddle;
        private double vx, vy;   // the velocity of the ball
        private RandomGenerator rgen =  RandomGenerator.getInstance(); // generate the horizontal velocity randomly
        private int bricknum = NBRICK_ROWS*NBRICKS_PER_ROW;
        private int turnnum = NTURNS;  // count how many bricks left
        private AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");
        private GLabel score;
        private final int velocityY=3;
       
/* Method: run() */
/** Runs the Breakout program. */
        public void run() {
                /* You fill this in, along with any subsidiary methods */
                addMouseListeners();  // must add listener before initiate game
                initGame();
        }
       
        // Init the game
        private void initGame(){
                bricknum = NBRICK_ROWS*NBRICKS_PER_ROW;
                started = 0;
                createWall();   // draw bricks
                createPaddle(); // draw paddle
                createBall();   // draw ball
                createScore();
                while(started ==0); // wait for click to start
                playGame();     
        }
       
        // Remove all the remaining GObjects in the canvas
        private void clearCanvas(){
                for (int i =0; i<getWidth();i++){
                        for (int j=0; j<getHeight();j++){
                                GObject canvasPoint = getElementAt(i,j);
                                if (canvasPoint!=null){
                                        remove(canvasPoint);
                                }
                        }
                }       
        }
       
        // Create the wall at the top of the screen
        private void createWall(){
                // wx and wy are start point of the wall
                double wx = 0;
                double wy = BRICK_Y_OFFSET;
                for (int i = 0; i<NBRICK_ROWS; i++){
                        for (int j=0; j<NBRICKS_PER_ROW; j++){
                                GRect brick = new GRect(wx+j*(BRICK_WIDTH+BRICK_SEP),wy+i*(BRICK_HEIGHT+BRICK_SEP),
                                                BRICK_WIDTH,BRICK_HEIGHT);
                                brick.setFilled(true);
                                // select color for different rows
                                switch(i){
                                case 0:
                                case 1: brick.setFillColor(Color.RED); break;
                                case 2:
                                case 3: brick.setFillColor(Color.ORANGE); break;
                                case 4:
                                case 5: brick.setFillColor(Color.YELLOW); break;
                                case 6:
                                case 7: brick.setFillColor(Color.GREEN); break;
                                case 8:
                                case 9: brick.setFillColor(Color.CYAN); break;
                                }
                        add(brick);
                        }
                }
                return;
        }
       
        // Create the paddle
        private void createPaddle(){
                double px = getWidth()/2;
                double py = getHeight()- PADDLE_Y_OFFSET - PADDLE_HEIGHT;
                paddle = new GRect(px-PADDLE_WIDTH/2,py,PADDLE_WIDTH,PADDLE_HEIGHT);
                paddle.setFilled(true);
                paddle.setFillColor(Color.BLACK);
                add(paddle);
                return;
        }
       
        // Create the ball
        private void createBall(){
                double bx = getWidth()/2 - BALL_RADIUS;
                double by = getHeight() - PADDLE_Y_OFFSET - PADDLE_HEIGHT - 2*BALL_RADIUS;
                ball = new GOval(bx, by, 2*BALL_RADIUS, 2*BALL_RADIUS);
                ball.setFilled(true);
                ball.setFillColor(Color.BLACK);
                add(ball);
                return;
        }
       
        private void createScore(){
                score = new GLabel("SCORE: "
                                + (NBRICK_ROWS*NBRICKS_PER_ROW-bricknum)
                                +"/"
                                + (NBRICK_ROWS*NBRICKS_PER_ROW),0, getHeight());
                add(score);
        }
/////////////////////////////////////////////////////////////////////////////////////////       
        // Once clicked the game, the game starts
        public void mousePressed(MouseEvent e){
                // started determines whether the game should start upon mouse click.
                // for a initiated game, started = 0.
                // Once it responds the mouse click, it will never respond to mouse click any more,
                // until the game ends.
                if (stopped == 1){   // when the game is paused, clicking mouse means you are ready to clean the canvas
                        ready = 1;

                }
                if (started == 0){   // when the game has not been started yet, clicking mouse means to start the game.
                        started = 1;
                        stopped = 0;
                }
                //println(ready);
               
        }
       
        // paddle tracks the mouse position
        public void mouseDragged(MouseEvent e){
                double mx = e.getX();
                double my = getHeight()- PADDLE_Y_OFFSET - PADDLE_HEIGHT;
                if ((mx>=0)&&(mx<= getWidth()-PADDLE_WIDTH))
                        paddle.setLocation(mx,my); // use set location to change the position of the paddle
        }
///////////////////////////////////////////////////////////////////////////////////////////////////////       
        // start the game, the ball begins to move
        private void playGame(){
                vx = rgen.nextDouble(1.0,3.0); // generate the velocity randomly
                if (rgen.nextBoolean(0.5)) vx = -vx;  // generate the velocity direction randomly.
                vy = -velocityY;
                while (isOver()==0){
                        ball.move(vx, vy);
                        add(ball);
                        pause(20);
                        checkBouncing();  // check whether the ball reaches the left, right and top boundary
                        checkCollision(); // check whether the ball collides with the bricks and paddle
                        updateScore();
                }
               
                if (isOver()==1){  // if lose game in one round
                        turnnum--;     // remaining turns reduced by one
                        if (isGameOver()){  // if there is no chances left
                                GLabel label = new GLabel("You lose the game",0,0);
                                double ldx = getWidth()/2-label.getWidth()/2;
                                double ldy = getHeight()/2+label.getAscent()/2;
                                label.move(ldx, ldy);
                                add(label);
                        }
                        else{  // if you still have chances
                                GLabel label = new GLabel("You have "+turnnum+ " chances",0,0);
                                double ldx = getWidth()/2-label.getWidth()/2;
                                double ldy = getHeight()/2+label.getAscent()/2;
                                label.move(ldx, ldy);
                                add(label);
                                ready = 0;
                                stopped = 1;
                                while (ready == 0);
                                clearCanvas();  // remove all remaining GObjects in the canvas       
                                initGame();  // restart the game
                        }
                }
                if (isOver()==2){  // if win the game
                        GLabel label = new GLabel("You win the game",0,0);
                        double ldx = getWidth()/2-label.getWidth()/2;
                        double ldy = getHeight()/2+label.getAscent()/2;
                        label.move(ldx, ldy);
                        add(label);
                }
        }
////////////////////////////////////////////////////////////////////////////////////////////////////       
        // Check whether the ball reaches the left or right or top boundary
        private void checkBouncing(){
                if ((ball.getX()<=0)||(ball.getX()+2*BALL_RADIUS> getWidth())){
                        vx = - vx;
                }
                if (ball.getY()<=0){
                        vy = -vy;
                }
        }
       
        // Check whether win or lose the game in one round
        private int isOver(){
                if (bricknum == 0)
                        return 2;  // win the game
                if (isFailure()){
                        return 1;  // lose the game
                }
                return 0;     // the game continues
        }
       
        // Check whether you missed the ball
        private boolean isFailure(){
                if (ball.getY()>=getHeight()-PADDLE_Y_OFFSET+PADDLE_HEIGHT){
                        return true;
                }
                return false;
        }
       
        // Check whether the game is over
        private boolean isGameOver(){
                if (turnnum == 0)
                        return true;
                return false;
        }
       
        // check whether the ball collides with other GObject and deal with the GObject
        private void checkCollision(){
                GObject collider = getCollidingObject();
                if (collider == null)  // does not collide
                        return;
                bounceClip.play();     // collides, play music
                if ((collider != paddle)&&(collider != score)){ // collide with the bricks
                        remove(collider);   // remove the brick
                        bricknum--;         // remaining bricks reduced by one
                }
        }
       
       
        // Check four corner of the ball to decide whether it collides.
        // change the velocity direction if it collides
        private GObject getCollidingObject(){
                // upper
                GObject colObject1 = getElementAt(ball.getX()+BALL_RADIUS,ball.getY()-1);
                // right
                GObject colObject2 = getElementAt(ball.getX()+2*BALL_RADIUS+1,ball.getY()+BALL_RADIUS);
                // left
                GObject colObject3 = getElementAt(ball.getX()-1,ball.getY()+BALL_RADIUS);
                // bottom
                GObject colObject4 = getElementAt(ball.getX()+BALL_RADIUS,ball.getY()+2*BALL_RADIUS+1);
                if ((colObject1!=null)&&(colObject1!=score)){
                        vy = velocityY;
                        return colObject1;
                }
                if ((colObject2!=null)&&(colObject2!=score)){
                        vx = -vx;
                        return colObject2;
                }
                if ((colObject3!=null)&&(colObject3!=score)){
                        vx = -vx;
                        return colObject3;
                }
                if ((colObject4!=null)&&(colObject4!=score)){
                        vy = -velocityY;
                        return colObject4;
                }
                return null;
        }

        private void updateScore(){
                score.setLabel("SCORE: "
                                + (NBRICK_ROWS*NBRICKS_PER_ROW-bricknum)
                                +"/"
                                + (NBRICK_ROWS*NBRICKS_PER_ROW));
        }

}



回复

使用道具 举报

🔗
littlelab 2013-7-18 14:13:03 | 只看该作者
全局:
为什么我贴的帖子这么丑。。。。
回复

使用道具 举报

🔗
sum0mer 2013-7-18 19:14:08 | 只看该作者
全局:
求问为什么按照要求安装了eclipse,但是编写的时候,明明有run,运行时还是会提出错误提示:
workspace dose not cantain a main type [do you have a public void run() method?]
非常感谢!
回复

使用道具 举报

🔗
littlelab 2013-7-19 14:50:50 | 只看该作者
全局:
sum0mer 发表于 2013-7-18 19:14
求问为什么按照要求安装了eclipse,但是编写的时候,明明有run,运行时还是会提出错误提示:
workspace do ...

我还没有出现这个问题,不过是不是你的Java版本不对?
回复

使用道具 举报

🔗
sewen67 2013-8-1 22:15:12 | 只看该作者
全局:
楼主你好,我自己在看CS106A的视频,自己做了Assignment1,2,3,4。不知可否贴上我的作业?那我先贴下3和4吧,1和2做的比较糙。在研究5和6呢,自己做有点吃力啊。感谢感谢。
回复

使用道具 举报

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

本版积分规则

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