⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rand.java

📁 java程序
💻 JAVA
字号:
// Copyright (c) 2005 Sony Ericsson Mobile Communications AB
//
// This software is provided "AS IS," without a warranty of any kind. 
// ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, 
// INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A 
// PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. 
//
// THIS SOFTWARE IS COMPLEMENTARY OF JAYWAY AB (www.jayway.se)

package bluegammon.logic;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

/**
 * Global random generator. It must be global
 * so all methods needing random values accesses
 * the same methods. This is because we want similar
 * behaviour on both devices in a remote game, which
 * is achieved by agreeing on a mutual seed.
 * 
 * @author Peter Andersson
 */
public class Rand
{
  /** The seed */
  protected static long SEED = new Date().getTime();
  /** Native random generator */
  protected static Random RANDOM = new Random(SEED);

  /**
   * Sets the seed of the random generator.
   * @param seed	The seed of the random generator.
   */
  public static void setRandomSeed(long seed)
  {
    SEED = seed;
    RANDOM = new Random(seed);
  }

  /**
   * Returns a random integer ranging from Integer.MIN_VALUE to Integer.MAX_VALUE.
   * @return A random integer value.
   */
  public static int random()
  {
    return RANDOM.nextInt();
  }

  /**
   * Returns a random float ranging from -1.0f to 1.0f.
   * @return	A random float value.
   */
  public static float randomFloat()
  {
    return 2f * RANDOM.nextFloat() - 1f;
  }

  /**
   * Loads the seed into random generator.
   * @param dis	The stream to read from.
   * @return Number of bytes read.
   * @throws IOException if loading failed
   */
  public static int loadSeed(DataInputStream dis)
    throws IOException
  {
    setRandomSeed(dis.readLong());
    return 8;
  }
  
  /**
   * Writes the seed used by random generator.
   * @param dos The stream to write to,
   * @return Number of bytes written.
   * @throws IOException if saving failed
   */
  public static int saveSeed(DataOutputStream dos) 
    throws IOException
  {
    dos.writeLong(SEED);
    return 8;
  }

  /** Prevent construction */
  private Rand()
  {}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -