Create a Tic-Tac-Toe Animation - java

I want to create a simple animation of a game so you can see the playout of a game. It should be an animation in which you just see the game Tic-Tac-Toe played. I have the states of the games in a description. So player 1 marks a cell = state 1; player 2 marks a cell = state 2 etc..
I currently have the game parsed in a ruby program; it will be easy to display just one state (like in the image), but how do I create an animation from it? Is there an easy way to do this? I'm open to solutions in every language but it shouldn't take to much time to implement. I want to show such an animation in a presentation.
<state1>
cell(1,1,x).
cell(1,2,o).
cell(1,3,o).
cell(2,1,o).
cell(2,2,x).
cell(2,3,x).
cell(3,1,b).
cell(3,2,b).
cell(3,3,x).
</state1>
<state2>
...
</state2>

Since you already know how to display one state, the way to animate that is to display each state one after the other in sequence.
Display the first state and set a timer, then when the timer goes off show the next state and set another delay, and so on through all the states.
Since you said you are open to all languages I don't really want to bother with any specific code beyond that high-level overview. For example, in Flash/ActionScript I would use TweenLite to display the symbols with a delay, but I don't know if that specific code would be of any use to you.
I've never programmed Ruby but it probably has a command like setDelay() or setTimer() or something. If not, the same effect can be accomplished with a main loop that will check the time each cycle and if the delay has been long enough it shows the next state.

For ruby you can have a awesome tic-tac-toe from https://github.com/grosser/tic_tac_toe
just do "gem install tic_tac_toe"

Related

Timer in Greenfoot

I'm making a game right now and want to add a timer to count down to my end game screen, I can get the text to show up on my game screen but the numbers won't go down.
Any feedback would help!
Biased note: Greenfoot is a great tool to learn to program in Java. Keep going! But learn to read documentation[1], please.
You are calling subtractTime() only in the constructor Timer(). This way it will be called only once at creation time of your Timer object.
Call it in the act() method instead.
It will be called every time when the Greenfoot system lets all actors and the current world, well, act. The time between the calls is controlled by the "Speed" control below the world's frame, or by the specific methods of the class Greenfoot.
If you need "real-time" values like seconds, do some research how to obtain seconds or milliseconds.
[1]: You can read Greenfoot's documentation in the Editor window by double-clicking on "World" or "Actor" in the class diagram on the right.

Avoiding while loop but still capturing each move by computer in the game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
May You please suggest me how to implement computer's move inside game without having while loop in main method which will eventually burden the thread?
As It is easy when I have game between 2 human players, because I can manage whose move it is by managing actionPerformed() method. So I dont need any loop.
I already have logic for computer's move inside computerPlays() method.
Probably it is bit easier if one player is human, one computer..where I can do something like: increase int n after each human move. and then in main()
if(n%2!=0)
{
computerPlays();
}
but I still need loop to have complete game flow.
What if both players are computer?
If You are willing to help me, please try using simpler words as I am pretty new to Java.
Thanks.
edit: whats wrong with question ?
Use a javax.swing.Timer to pace serial calls to the model, stopping the timer when the game ends. In the game cited here, press A to toggle animation when using the mouse. Each time you release the mouse, the computer, via the timer's handler, will first move the player and then advance the enemies; it repeats this sequence until there is no valid move or the game is won.
/** Animate one move; stop when no more moves or game won. */
public void actionPerformed(ActionEvent e) {
if (!game.move(mouseRow, mouseCol) || game.won()) timer.stop();
}
Your question seems to be vague, but i'll try to do my best, with general tips.
You should not use a loop to manage your game logic, this will make your GUI unresponsive, or totally freeze it.
Instead, you should use events to run the game. You could write a class which models your game logic, keeping an instance of this class in your "game panel".
Then, you register all the listeners you need to determine when the player is trying to make his move. Whenever an action is fired you could:
Ask your game class if the player has to move.
If not, you can ignore that event, or you can send a warning/error message to the user.
Else, you set the current state of your game class, doing all you need to prepare it for the next move.
Refresh your game panel (if needed) to make all the changes visible.
If the computer has to move, you invoke the corresponding method.
Once again, you refresh your game panel, and so on ...
As you can see, this way of programming is event driven, when something happens you need to change your model, and then you update your view.
If the computer and the player play the game by alternately moving, it's easy to make your computer play after every player move, else, you need to check who is moving every single time.
Also, since the computer could play too fast to let the user understand what happenened, you should consider using a Timer (see the official tutorial) to add some delay to every move.
Hope this helps!

How to make GUI wait for user input? [duplicate]

This question already has an answer here:
How to stop Java from running the entire code with out waiting for Gui input from The user
(1 answer)
Closed 5 years ago.
I'm a rather basic programmer who has been assigned to make a GUI program without any prior experience with creating a GUI. Using NetBeans, I managed to design what I feel the GUI should look like, and what some of the buttons should do when pressed, but the main program doesn't wait for the user's input before continuing. My question is, how do I make this program wait for input?
public class UnoMain {
public static void main(String args[]) {
UnoGUI form = new UnoGUI(); // GUI class instance
// NetBeans allowed me to design some dialog boxes alongside the main JFrame, so
form.gameSetupDialog.setVisible(true); // This is how I'm trying to use a dialog box
/* Right around here is the first part of the problem.
* I don't know how to make the program wait for the dialog to complete.
* It should wait for a submission by a button named playerCountButton.
* After the dialog is complete it's supposed to hide too but it doesn't do that either. */
Uno Game = new Uno(form.Players); // Game instance is started
form.setVisible(true); // Main GUI made visible
boolean beingPlayed = true; // Variable dictating if player still wishes to play.
form.playerCountLabel.setText("Players: " + Game.Players.size()); // A GUI label reflects the number of players input by the user in the dialog box.
while (beingPlayed) {
if (!Game.getCompleted()) // While the game runs, two general functions are repeatedly called.
{
Player activePlayer = Game.Players.get(Game.getWhoseTurn());
// There are CPU players, which do their thing automatically...
Game.Turn(activePlayer);
// And human players which require input before continuing.
/* Second part of the problem:
* if activePlayer's strategy == manual/human
* wait for GUI input from either a button named
* playButton or a button named passButton */
Game.advanceTurn();
// GUI updating code //
}
}
}
}
I've spent about three days trying to figure out how to integrate my code and GUI, so I would be grateful if someone could show me how to make this one thing work. If you need any other information to help me, please ask.
EDIT: Basically, the professor assigned us to make a game of Uno with a GUI. There can be computer and human players, the numbers of which are determined by the user at the beginning of the game. I coded the entire thing console-based at first to get the core of the game to work, and have since tried to design a GUI; currently this GUI only displays information about the game while it's running, but I'm not sure how to allow the code to wait for and receive input from the GUI without the program charging on ahead. I've investigated other StackOverflow questions like this, this, this, or this, but I cannot comprehend how to apply the answers to my own code. If possible, I'd like an answer similar to the answers in the links (an answer with code I can examine and/or use). I apologize if I sound demanding or uneducated and confusing; I've been working diligently on this project for a couple weeks and it's now due tomorrow, and I've been stressing because I can't advance until I figure this out.
TL;DR - How do I get my main program to wait and listen for a button click event? Should I use modal dialog boxes, or is there some other way to do it? In either case, what code needs to be changed to do it?
Unlike console based programming, that typically has a well defined execution path, GUI apps operate within a event driven environment. Events come in from the outside and you react to them. There are many types of events that might occur, but typically, we're interested in those generate by the user, via mouse clicks and keyboard input.
This changes the way an GUI application works.
For example, you will need to get rid of your while loop, as this is a very dangerous thing to do in a GUI environment, as it will typically "freeze" the application, making it look like your application has hung (in essence it has).
Instead, you would provide a serious of listeners on your UI controls that respond to user input and update some kind of model, that may effect other controls on your UI.
So, to try and answer your question, you kind of don't (wait for user input), the application already is, but you capture that input via listeners and act upon them as required.

Memory game - Make the 2 cards disappear after X time

I wanted to make a "memories" or "find pairs" game for Java, just to start with a basic game before starting something more difficult. My game works very well, but I just have 1 big problem. I don't really know how to hide the 2 images x seconds after the user clicks on the second one.
This is what is done:
The game is created with 4x4 buttons in a array
The values of the cards are distributed (name, position, icon)
The user then clicks on the first card, which shows up immediately
The user clicks on the second one, if the first is equal to the second one then disable the 2, if not then re-hide the 2.
But I don't know how I can make the program show the second card and then after x seconds hide the 2...
How can I solve this?
Depending on what framework you are using, there should be a timer utility available to you.
For instance, if you are using Swing, then you should be able to use javax.swing.Timer as suggested in the above comments. Follow this link for a simple Swing Timer tutorial. As they say on that page, swing timers can be used in one of two ways and one of those ways is:
To perform a task once, after a delay
This sounds like exactly what you are trying to achieve.
You could also try a library like Joda Time which has lots of features and options.
you should make match function and another unmatch function and inside the unmatch function
you can use setTimeout and give the two cards class(flip) when you choose them and after certain time and when they didn't match remove this flip class.

color fade animation for grid cells in swing Pin

I'm doing a path-finding project as part of my 4th year software engineering degree.
We're suppose to give visual representation to a bunch of multi-agent pathfinding algorithm. The simplest one is A* adapted for multiagents.
Anyway our environment is a grid map where every cell can be either blocked or used as part of an agent's path. What I want to do is use animation to give a good representation of the final movement of the agent, but animating color change in my grid.
I.E paint every step in the path for a second or so with some color to show how the agent moves.
And the other thing I want to do is to represent the way the algorithm works by painting the changes in the open list and closed list of the A* algorithm while its doing its calculation.
I'm using an adapted version of the observer design pattern to send events from my algorithm layer to my controller and GUI layer.
What I want to do in the GUI layer is every time a tile is added to the open list, I want to have that cell painted in some color and then have it fade away according to a predefined timer or maybe later add a slider to control this timer.
I looked at the code here. It seems pretty simple, the problem is that every tile animation has to be independent of the others to allow the algorithm and everything to keep running and different animations to start.
So what's the best way to achieve the results I'm looking for? Should I just open a different thread for each animation or have a pre-made thread for each cell?
Would that be an overkill for the application, since there can be up to 1000 cells and therefore close to 1000 threads performing animation.
Another issue I think I might encounter is the fact that it might happen that a cell will start its color fading animation and then will have to restart and I don't want the two animations to go at the same time (only one thread performing animation for the same cell at the same time).
I hope I was clear enough with what I'm trying to achieve, if someone has any ideas or thought it could really help me with my project.
You can find Trident animation library useful. More information at http://kenai.com/projects/trident/pages/Home
I would consider a scenario with a single animation thread only. You might e.g. try the following strategy:
standard event thread for swing events
one worker thread for your logic
only one additional for all animations
This third thread manages all animation within your gui. Therefore it maintains a list of animation actions to perform together with their timestamp. Such an action can be e.g. "set color of cell [1,2] to CF0000 # 17:01:00" in an approriate data structure. This list of actions is then filled by the worker thread with the animation actions (e.g. you may add several actions at once for a fading cell - 1) set to 100% # now; 2) set to 75% # now+10s; 3) set to 50% # now+20s ...). Make sure that this list is properly synchronized since it will be accessed from both threads.
If you keep this list sorted by timestamp it is quite easy to determine the which actions this thread has to do at any time. This thread has then a quite simple loop, e.g. something like
while(true) {
AnimationAction action = list.get(0);
if(action!=null && action.timestamp <= now()) {
action.perform(); // <= be sure that paint events occur in the edt
list.remove(0);
continue;
}
sleep(...);
}
Note that you can determine the time to sleep from the timestamp of the next action but consider that a new animation event arriving might have to interrupt this. Otherwise you can also sleep for some short amount of time.
Regarding your second question this thread might remove any actions from this list on demand for a special cell if a new action arrives. Therefore you might also maintain a secondary data structure in order to do this efficiently.
I'd use javax.swing.Timer and AlphaComposite, as demonstrated here.

Categories