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;
}
*/
}