Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Центр помощи > [Java] Игра в кости


Автор: Xentar 25.4.2007, 16:09
Народ, необходима помощь в написании игрушки на джава.
Игрушка должна содержать небольшой графический интерфейсик, собственно,
логику можно вообще не программировать,
у меня как раз сложности с созданием графических элементов.

Автор: Alary 26.4.2007, 12:12
Из условия вообще не понятно что делать: 1) что за игрушка? что с костями делатся? 2) как она на компе выполнятся должна - как апплет в браузере или J2SE?

Автор: Xentar 26.4.2007, 13:42
Она должна быть не в браузере, а как отдельное приложение.
Кости типа крутяться.
Вечерком скину то, что есть.

Автор: Paranorma 26.4.2007, 20:50
Выкладываю по просьбе Xentar"a код его программы

Код

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

/**
 * Shows a pair of dice that are rolled when the user clicks a button
 * that appears below the dice.
 */
public class DicePanelWithButton extends JPanel {
   
   private int die1 = 4;  // The values shown on the dice.
   private int die2 = 3;
   
   private Timer timer;   // Used to animate rolling of the dice.
   
   /**
    *  The constructor sets up the panel.  It creates the button and
    *  the drawing surface panel on which the dice are drawn and puts
    *  them into a BorderLayout.  It adds an ActionListener to the button
    *  that rolls the dice when the user clicks the button.
    */
   public DicePanelWithButton() {
      
      setLayout(new BorderLayout(2,2));
      setBackground(Color.BLUE);  // Will show through the gap in the BorderLayout.
      setBorder(BorderFactory.createLineBorder(Color.BLUE,2));
      
      JPanel dicePanel = new JPanel() {
         public void paintComponent(Graphics g) { 
            super.paintComponent(g);  // fill with background color.
            drawDie(g, die1, 10, 10); // Just draw the dice.
            drawDie(g, die2, 55, 55);
         }
      };
      dicePanel.setPreferredSize( new Dimension(100,100) );
      dicePanel.setBackground( new Color(200,200,255) );  // light blue
      add(dicePanel, BorderLayout.CENTER);
      
      JButton rollButton = new JButton("Roll!");
      rollButton.addActionListener( new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            roll();
         }
      });
      add(rollButton, BorderLayout.SOUTH);
      
   } // end constructor
   
   /**
    * Draw a die with upper left corner at (x,y).  The die is
    * 35 by 35 pixels in size.  The val parameter gives the
    * value showing on the die (that is, the number of dots).
    */
   void drawDie(Graphics g, int val, int x, int y) {
      g.setColor(Color.white);
      g.fillRect(x, y, 35, 35);
      g.setColor(Color.black);
      g.drawRect(x, y, 34, 34);
      if (val > 1)  // upper left dot
         g.fillOval(x+3, y+3, 9, 9);
      if (val > 3)  // upper right dot
         g.fillOval(x+23, y+3, 9, 9);
      if (val == 6) // middle left dot
         g.fillOval(x+3, y+13, 9, 9);
      if (val % 2 == 1) // middle dot (for odd-numbered val's)
         g.fillOval(x+13, y+13, 9, 9);
      if (val == 6) // middle right dot
         g.fillOval(x+23, y+13, 9, 9);
      if (val > 3)  // bottom left dot
         g.fillOval(x+3, y+23, 9, 9);
      if (val > 1)  // bottom right dot
         g.fillOval(x+23, y+23, 9,9);
   }
   
   
   /**
    * Run an animation that randomly changes the values shown on
    * the dice 10 times, every 100 milliseconds.
    */
   private void roll() {
      if (timer != null)
         return;
      timer = new Timer(100, new ActionListener() {
         int frames = 1;
         public void actionPerformed(ActionEvent evt) {
            die1 = (int)(Math.random()*6) + 1;
            die2 = (int)(Math.random()*6) + 1;
            repaint();
            frames++;
            if (frames == 10) {
               timer.stop();
               timer = null;
            }
         }
      });
      timer.start();
   }
   
   
} // end class DicePanelWithButton


Код

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
 * Main.java
 *
 * Created on 25 Апрель 2007 г., 19:23
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

//package javaapplication2;

/**
 *
 * @author Администратор
 */
public class Main {
    
    /** Creates a new instance of Main */
    public Main() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

//      JButton okButton = new JButton("OK");

      JFrame window = new JFrame("Кости...");
      DicePanelWithButton content = new DicePanelWithButton();
//       content.setContentPane(content2);
//      content2.add(displayPanel, BorderLayout.CENTER);
//      JPanel content = new JPanel();
      
//      content.setLayout(new BorderLayout());
//      content.add(displayPanel, BorderLayout.CENTER);
//      content.add(okButton, BorderLayout.SOUTH);
      window.setContentPane(content);
      window.pack();
      window.setSize(250,250);
      Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
      window.setLocation( (screensize.width - window.getWidth())/2, (screensize.height - window.getHeight())/2 );
      window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      window.setResizable(false);  // User can't change the window's size.
      window.setVisible(true);
    }
    
}

Автор: LSD 26.4.2007, 22:42
Цитата(Xentar @  26.4.2007,  14:42 Найти цитируемый пост)
Кости типа крутяться.

Что ты под этим подразумеваешь? Ты хочешь получить полноценную 3D анимацию вращения костей?

Автор: Xentar 27.4.2007, 13:38
Нет, мелькание точек в кубиках. Но, это уже есть в классе, терь надо из него полноценное приложение сделать....

Автор: LSD 27.4.2007, 22:26
Цитата(Xentar @  27.4.2007,  14:38 Найти цитируемый пост)
терь надо из него полноценное приложение сделать.... 

А чего там нехватает, кроме логики (которуй ты вроде как и сам можешь написать)?

Автор: Alary 28.4.2007, 11:42
Какие пункты должно быть в меню? 
Что еще должны делать кости кроме того, что крутиться? В чем суть игры? Просто бросил кости и посмотрел какие числа выпали, сложил сумму и все? тогда сколько костей кидать? или еще что-то происходить должно? http://www.azartgames.com/index.php?option=com_content&task=blogcategory&id=17&Itemid=31
и кто с кем играет - человек с компом или два человека друг с другом?

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)