游戏代码部分-------game包------PieceBuffer.java

package game;
/**
 *
环状缓冲区 PieceBuffer
 *
用于存放游戏所用的方块形状索引
 * @see #PieceBuffer()
 * @see #PieceBuffer(int s)
 * @see #put(int n)
 * @see #get()
 */
public class PieceBuffer {
  /**
默认缓冲大小1024*/
  private static final int D_SIZE = 1024;
  /**
缓冲是否完成标志*/
  private volatile boolean fin = false;
  /**
缓冲数组的首指针*/
  private volatile int head;
  /**
缓冲数组的尾指针*/
  private volatile int tail;
  /**
当前缓冲的大小*/
  private volatile int length;
  /**
缓冲的大小*/
  private int size;
  /**
缓冲数组*/
  public int[] pbuffer;
  /**
   *
默认构造器
   *
构造默认大小的缓冲
   */
  public PieceBuffer() {
    head = tail = length = 0;
    fin = false;
    pbuffer = new int[D_SIZE];
  }
  /**
   *
构造器
   * @param s
指定缓冲的大小
   */
  public PieceBuffer(int s) {
    head = tail = length = 0;
    fin = false;
    size = s;
    pbuffer = new int[s];
  }
  /**
   *
取模运算
   * @param x
缓冲的索引
   * @return 
size后的值
   */
  private int mod(int x) {
    return (x >= size ? x - size : x);
  }
  /**
   *
判断缓冲区是否为空
   * @return
如果长度为0 返回 true
   */
  public synchronized boolean is_empty() {
    return length == 0;
  }

  /**
   *
判断缓冲区是否为满
   * @return
如果长度为缓冲区的大小 返回 true
   */
  public synchronized boolean is_full() {
    return length == size;
  }

  /**
   *
返回生产者的完成标志
   * @return fin
的值
   */
  public synchronized boolean finished() {
    return fin;
  }
  /**
   *
设置生产者的完成标志
   * @param v
   */
  public synchronized void finished(boolean v) {
    fin = v;
    notify();
  }
  /**
   *
向缓冲区首添加一个数值
   * @param n
添加的数值
   */

  public synchronized void put(int n) {
    pbuffer[tail++] = n;
    length++;
    tail = mod(tail);
  }
  /**
   *
从环冲区尾取一个值
   * @return
返回从环冲区取出的值
   */

  public synchronized int get() {
    int p;
    p = pbuffer[head++];
    length--;
    head = mod(head);
    return p;
  }

  /**
   *
清空缓冲区
   */
  public void clearpbuffer() {
    for (int i = 0; i < size; i++)
      pbuffer[i] = 0;
    head = tail = length = 0;
    fin = false;
  }

  public void initPBuffer(int pbSize)
{
  for (int i = 0; i < pbSize; i++)
    put( (int) (Math.random() * 7));
}

/*
     public synchronized void put(int n)
     {
    while(is_full())
    {
      try{
        wait();//
等待,直到有数据被取出
      }catch(InterruptedException e){}
    }
    pbuffer[tail++] = n;
    length++;
    tail = mod(tail);
    notify();
     }
    public synchronized int get()
    {
      int p;
      while (is_empty())
      {
          try {
            wait();
          }
          catch (InterruptedException e) {}
      }
      p = pbuffer[head++];
      length--;
      head = mod(head);
      notify();
      return p;
    }
*/
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值