Модераторы: Rickert

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Разработка игры "Территория" (Точки), Java, с нуля 
:(
    Опции темы
Rpahut
Дата 18.2.2009, 21:39 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


0xdeadbeef
*


Профиль
Группа: Участник
Сообщений: 243
Регистрация: 9.4.2006

Репутация: 5
Всего: 7



А вы захват точек уже впаяли в программу? Если да, предлагаю сначала добавить подсчет очков.

Для начала добавим в GridsCanvas несколько переменных, для хранения очков:
Код

     private Color playerAColor = null;
     private Color playerBColor = null;
     private int playerAScores = 0;
     private int playerBScores = 0;


Выводить счет будем так:
Код

          // Add this code to the end of GridsCanvas.paintComponent()

          Font font = new Font("Arial", Font.BOLD, 12); // create bold Arial font size 12 points
          g.setFont(font); // use this font

          g.setColor(playerAColor);
          g.drawString( new String(""+playerAScores), 0, field2screen(rows)); // display scores for one player
          g.setColor(playerBColor);
          g.drawString( new String(""+playerBScores), field2screen(cols/2), field2screen(rows));  // display scores for other player


Метод пересчета очков.
Здесь творится полное ГГ, в основном потому что я сразу не подумал о том как будут считаться очки:
Код

     private void calculateScores() {
         Color ownerColor;

         // reset scores
         playerAScores = 0;
         playerBScores = 0;

         // loop for all points
         for(int j=0; j<rows; j++) {
             for(int i=0; i<cols; i++) {

                 // get capturer color
                 ownerColor = points[i][j].getCaptured();
                 // if no capturer - get initial point owner color
                 if( ownerColor==null ) ownerColor = points[i][j].getColor();

                 if( ownerColor!=null ) {
                     // if no A color yet assigned
                     if( playerAColor==null ) {
                         playerAColor = ownerColor;
                     }
                     // A is assigned but B is not
                     else if( playerBColor==null && ownerColor!=playerAColor ) {
                         playerBColor = ownerColor;
                     }

                     // compare colors and score player
                     if( ownerColor==playerAColor ) playerAScores++;
                     if( ownerColor==playerBColor ) playerBScores++;
                 }
             }
         }
     }

Вызывать этот метод нужно после того куска где захватываются точки:
Код

...
                    // if color changed
                    makeConnections(pointX, pointY);
                    for(int j=0; j<rows; j++) {
                        for(int i=0; i<cols; i++) {
                            wasHere = new boolean[cols][rows];
                            if( pointNotCaptured(i, j, playerColor)==0 ) {
                                points[i][j].setCaptured(playerColor);
                            }
                        }
                        calculateScores(); // <--
...

--------------------
C/C++ GameDevRSS Раздела программирования игрOpenGL - уроки от NeHeКак продать идею?
PM MAIL   Вверх
Qawra
Дата 19.2.2009, 19:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 188
Регистрация: 6.3.2007

Репутация: 3
Всего: 4



Я наверно его ещё не полностью впаяла .. или он пока просто себя не проявляет  визуально .. Я была  где-то здесь 
Код

import javax.swing.*;
import java.awt.*;

public class GridsCanvas  extends JPanel
{
     private  int rows=20;
     private  int cols=20;
     private  int cellSize=30 ;
     private DrawablePoint points[][]; // array to hold all possible  points
     
       
    public GridsCanvas(int r, int c,int cellSize) {
        this.rows = r;
        this.cols = c;
        this.cellSize=cellSize;
        
        setPreferredSize(new Dimension( (c+1)*cellSize, (r+1)*cellSize )); 
        // we make our window bigger than grid to have extra place 
        //and easier access to the points on the edge of the grids
        points = new DrawablePoint[cols][rows];
        makePoints(rows,cols); 
    }
    
    public void paintComponent(Graphics g) {
          g.translate(cellSize, cellSize); 
          //we move the grid right and down on the distance of the cellSize

          for (int i = 0; i < rows; i++)
               g.drawLine( i * cellSize, rows*cellSize-cellSize,  i * cellSize,0 );

          for (int j = 0; j < cols; j++)
               g.drawLine(0, cellSize*j, cols*cellSize-cellSize, cellSize*j); 

          for(int y=0; y<cols; y++) {
               for(int x=0; x<rows; x++) {
                    points[x][y].paint(g);  //  displays   points     
               }
          }
          g.translate(-cellSize, -cellSize);
     }
    
     public void makePoints ( int rows , int cols)
      {  for(int y=0; y<cols; y++)
            {for(int x=0; x<rows; x++) // pass screen coords to point constructor
             {  points[x][y] = new DrawablePoint( field2screen(x), field2screen(y) ); 
                 // create  all points     
            }      
          }
         }
         
     public boolean mouseWasClicked(int x, int y, Color playerColor) 
  { // accepts coordinates and the playerColor of the mouse click
         int pointX = screen2field(x); // count which point was clicked
         int pointY = screen2field(y);
         boolean result = false;
         if( goodCoords(pointX, pointY) ) {
             result = points[pointX][pointY].setNewColor(playerColor); // sets the  owner  color show that the point is occupied by player    
             if(result) {
                 // if color changed - create connections for this point
                 makeConnections(pointX, pointY);
              }    
          } // else - do nothing if coorditates is not good 
          return result;
       }
    
       
     private boolean goodCoords(int fieldX, int fieldY) {
       /*if X is zero or positive and  if Y is zero or positive 
       and  if X is less than field width and  if Y is less than field height...
       we can use   coordinates of the mouse click */
       if(fieldX>=0 && fieldY>=0 && fieldX<cols && fieldY<rows)  // ...good coordinates
       return true;

       else //  bad coordinates which dive  ArrayIndexOutOfBoundsException
       return false;
       }
   
     private int screen2field(int coord) { // screen to field convert coordinates
       return (coord-cellSize/2) /cellSize; 
  // shift  coordinates of the click by half cellSize to draw points on the corners of the grids  
      }

     private int field2screen(int coord) { // field to screen  convert coordinates
       return coord*cellSize;}
      
    private void makeConnections(int px, int py) 
    // create connection for the point ,px point x coordinate,py point y coordinate
    {
        DrawablePoint a, b;

        a = points[px][py]; // a - current point
        // for all eight points around current point
        for(int j=-1; j<=1; j++) {
            for(int i=-1; i<=1; i++) {
                if( goodCoords(px+i, py+j) ) {
                    b = points[px+i][py+j]; // b - point to check
                    
                    if(a!=b && b.getColor() == a.getColor()) // if not current point but have same color
                    {
                        // if no another diagonal connection in this cell already exists
                        if( !points[px][py+j].isConnectedTo(points[px+i][py]) ) {
                            a.connectTo(b); // connect a to b
                            b.connectTo(a); // connect b to a
                        }
                    }
                } // if goodcoords end
            } // loop i end
        } // loop j end
    }
  }


теперь я пытаюсь скомпелировать это 
Код

import javax.swing.*;
import java.awt.*;

public class GridsCanvas  extends JPanel
{
     private  int rows=20;
     private  int cols=20;
     private  int cellSize=30 ;
     private DrawablePoint points[][]; // array to hold all possible  points
     
     private Color playerAColor = null;
     private Color playerBColor = null;
     private int playerAScores = 0;
     private int playerBScores = 0;
     
    public GridsCanvas(int r, int c,int cellSize) {
        this.rows = r;
        this.cols = c;
        this.cellSize=cellSize;
        
        setPreferredSize(new Dimension( (c+1)*cellSize, (r+1)*cellSize )); 
        // we make our window bigger than grid to have extra place 
        //and easier access to the points on the edge of the grids
        points = new DrawablePoint[cols][rows];
        makePoints(rows,cols); 
    }
    
    public void paintComponent(Graphics g) {
          g.translate(cellSize, cellSize); 
          //we move the grid right and down on the distance of the cellSize

          for (int i = 0; i < rows; i++)
               g.drawLine( i * cellSize, rows*cellSize-cellSize,  i * cellSize,0 );

          for (int j = 0; j < cols; j++)
               g.drawLine(0, cellSize*j, cols*cellSize-cellSize, cellSize*j); 

          for(int y=0; y<cols; y++) {
               for(int x=0; x<rows; x++) {
                    points[x][y].paint(g);  //  displays   points     
               }
          }
          g.translate(-cellSize, -cellSize);
          
          Font font = new Font("Arial", Font.BOLD, 12); // create bold Arial font size 12 points
          g.setFont(font); // use this font

          g.setColor(playerAColor);
          g.drawString( new String(""+playerAScores), 0, field2screen(rows)); // display scores for one player
          g.setColor(playerBColor);
          g.drawString( new String(""+playerBScores), field2screen(cols/2), field2screen(rows));  // display scores for other player
     }
    
     public void makePoints ( int rows , int cols)
      {  for(int y=0; y<cols; y++)
            {for(int x=0; x<rows; x++) // pass screen coords to point constructor
             {  points[x][y] = new DrawablePoint( field2screen(x), field2screen(y) ); 
                 // create  all points     
            }      
          }
         }
         
     public boolean mouseWasClicked(int x, int y, Color playerColor) 
  { // accepts coordinates and the playerColor of the mouse click
         int pointX = screen2field(x); // count which point was clicked
         int pointY = screen2field(y);
         boolean result = false;
          
         if( goodCoords(pointX, pointY) ) {
             result = points[pointX][pointY].setNewColor(playerColor); // sets the  owner  color show that the point is occupied by player    
             if(result) {
                 // if color changed - create connections for this point
                 makeConnections(pointX, pointY);
                 for(int j=0; j<rows; j++) {
                        for(int i=0; i<cols; i++) {
                            wasHere = new boolean[cols][rows];
                            if( pointNotCaptured(i, j, playerColor)==0 ) {
                                points[i][j].setCaptured(playerColor);
                            }
                        }
                        calculateScores();
              }    
          } // else - do nothing if coorditates is not good 
          return result;
       }
    }
       
     private boolean goodCoords(int fieldX, int fieldY) {
       /*if X is zero or positive and  if Y is zero or positive 
       and  if X is less than field width and  if Y is less than field height...
       we can use   coordinates of the mouse click */
       if(fieldX>=0 && fieldY>=0 && fieldX<cols && fieldY<rows)  // ...good coordinates
       return true;

       else //  bad coordinates which dive  ArrayIndexOutOfBoundsException
       return false;
       }
   
     private int screen2field(int coord) { // screen to field convert coordinates
       return (coord-cellSize/2) /cellSize; 
  // shift  coordinates of the click by half cellSize to draw points on the corners of the grids  
      }

     private int field2screen(int coord) { // field to screen  convert coordinates
       return coord*cellSize;}
      
    private void makeConnections(int px, int py) 
    // create connection for the point ,px point x coordinate,py point y coordinate
    {
        DrawablePoint a, b;

        a = points[px][py]; // a - current point
        // for all eight points around current point
        for(int j=-1; j<=1; j++) {
            for(int i=-1; i<=1; i++) {
                if( goodCoords(px+i, py+j) ) {
                    b = points[px+i][py+j]; // b - point to check
                    
                    if(a!=b && b.getColor() == a.getColor()) // if not current point but have same color
                    {
                        // if no another diagonal connection in this cell already exists
                        if( !points[px][py+j].isConnectedTo(points[px+i][py]) ) {
                            a.connectTo(b); // connect a to b
                            b.connectTo(a); // connect b to a
                        }
                    }
                } // if goodcoords end
            } // loop i end
        } // loop j end
    }     
         private void calculateScores() {
         Color ownerColor;

         // reset scores
         playerAScores = 0;
         playerBScores = 0;

         // loop for all points
         for(int j=0; j<rows; j++) {
             for(int i=0; i<cols; i++) {

                 // get capturer color
                 ownerColor = points[i][j].getCaptured();
                 // if no capturer - get initial point owner color
                 if( ownerColor==null ) ownerColor = points[i][j].getColor();

                 if( ownerColor!=null ) {
                     // if no A color yet assigned
                     if( playerAColor==null ) {
                         playerAColor = ownerColor;
                     }
                     // A is assigned but B is not
                     else if( playerBColor==null && ownerColor!=playerAColor ) {
                         playerBColor = ownerColor;
                     }

                     // compare colors and score player
                     if( ownerColor==playerAColor ) playerAScores++;
                     if( ownerColor==playerBColor ) playerBScores++;
                 }
             }
         }
     }
    }

 и пока    wasHere = new boolean[cols][rows]; не компелируется .Не видит переменную . Наверно нужно создать её заранее как  член класса .
PM MAIL   Вверх
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Программирование игр, графики и искуственного интеллекта"
Rickert

НА ЗЛОБУ ДНЯ: Дорогие посетители, прошу обратить внимание что новые темы касающиеся новых вопросов создаются кнопкой "Новая тема" а не "Ответить"! Любые оффтопиковые вопросы, заданные в текущих тематических темах будут удалены а их авторы, при рецедиве, забанены.

  • Литературу, связанную с программированием графики, обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы связанные с программированием графики и мультимедии на языках С++ и Delphi
  • Вопросы по реализации алгоритмов рассматриваются здесь

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Rickert.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Программирование игр, графики и искусственного интеллекта | Следующая тема »


 




[ Время генерации скрипта: 0.0501 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.