Jump to content

How to make Tic-Tac-Toe with Undo and Replay (Stacks and Queues) in Java?

- - - - -

  • Please log in to reply
No replies to this topic

#1
mainframe004

mainframe004

    Newbie

  • Members
  • Pip
  • 1 posts
Hi, everyone. I'm new to this forum, and I really need help for a project. It's basically a Tic-Tac-Toe game that requires an Undo function and a Replay function. The undo basically removes the last move and returns the current turn to the previous player. The replay function basically plays the entire game session out, with the program copying the moves done by both players.

The project also requires that stacks and queues be used. From what I can understand, the undo button is going to depend on stacks while the replay button is going to depend on queues. In addition, the project requires that I create my own pop(), push(), peek(), enqueue() and dequeue() methods, which I already have. I'm just having trouble figuring out how to incorporate these into the game.

As for the game itself, I already have it working.

Here's the code for the custom stack and queue methods:


public class Stack {

	

	private String[] list;

	private int index;

	

	public Stack(int maxSize){

		this.list = new String[maxSize];

		index = 0;

	}


	public boolean push(String item){

		if(index != list.length)

		{

			list[index] = item;

			index++;

			return true;

		}

		

		else

			return false;

	}

	

	public String pop(){

		if(index != 0)

		{

			index--;

			return list[index];

		}

		

		else

			return null;

	}

	

	public String peek(){

		if(index != 0)

		{

			return list[index - 1];

		}

		

		else

			return null;

	}

	

}


public class Queue {

	

	private String[] list;

	private int index;

	

	public Queue(int maxSize){

		this.list = new String[maxSize];

		index = 0;

	}

	

	public boolean enqueue(String item){

		if(index != list.length)

		{

			list[index] = item;

			index++;

			return true;

		}

		

		else

			return false;

	}

	

	public String dequeue(){

		String item = list[0];

		for(int i = 0; i < index; i++){

			list[i] = list[i + 1];

		}

		

		index--;

		return item;

	}

}


What I have in mind is basically to put the appropriate methods in the actionPerformed method. For example, clicking one of the buttons on the game board would invoke the push() method to put a marker of the last turn on the stack, while clicking the undo button would invoke the pop() method to remove the last turn. Same logic goes for the queue. I just need to figure out how it's going to look on the GUI class.

Thanks to anyone who helps!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users