473,699 Members | 2,838 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help needed WRT text based adaptation of the TicTacToe game.

oedipus
6 New Member
I am currently learning java at school and thus far we have oly dealt with the text-based compiler JGrasp; therefore; my attempt to code Tictactoe or "X and O's" game is written as a text based program.

I have made use of a 2 dimensional integer array to represent the 3x3 grid. Each block therefore has a co-ordinate.eg. grid[0][0].Initially all blocks in the grid are equal to zero. The computer uses ones(1) and the player uses twos(2).The user is prompted to enter the row and column number and their choice is entered.

The problemm arises when the computer has to respond by choosig a block to play in. I thought that i could solve this by generating random numbers. The glitch is that when the same set of random co-ordinates is generated it appears as though the computer hasnt played at all. This means that as yet the game is still un-playable.

Expand|Select|Wrap|Line Numbers
  1.       int row3;
  2.       int col3;
  3.       int win;
  4.        public void game()
  5.       {
  6.          display_grid();
  7.          for(int loop=4;loop>=0&&win!=1;loop--){   
  8.             System.out.println("Computers turn:");                            
  9.             int row2=(int)(Math.random()*2+0);                 
  10.             int col2=(int)(Math.random()*2+0);                 
  11.             while(grid[row2][col2]==2||grid[row2][col2]==1){//glitch is somewhere here.
  12.                row3=row2;                                      
  13.                col3=col2;                                      
  14.             }                                                  
  15.             grid[row3][col3]=1; 
  16.             display_grid();
  17.  
There are 16 possible outcomes ,all of which are catered for later in the program. I would like some suggestions/help to get the computer to stop picking the same position over and over again, and also to ensure that each block can only be used once.

Thank you.
Aug 9 '10 #1
10 2522
Frinavale
9,735 Recognized Expert Moderator Expert
You need to provide a "seed" to the random method. (See Math.Random(see d) for more info).

If you don't specify a different seed each time then the same random number will be the result.

Try using the current date/time as the seed for the random method (it's always changing)
Aug 9 '10 #2
oedipus
6 New Member
Frinavle-
Thank you for your time , however I think that I may have left something to be desired in the phrasing of my question. What I actually wanted to know was how to get the program to stop overwriting blocks on the grid that already have a value.
The information that you gave me was extremely interesting and I have read up on it. I have no doubt that at some later juncture it will prove invaluable. I will be extremely grateful for any help regarding the problem stated in this reply-i.e.How do I get the program to stop overwriting elements in the array that already have a value?
Aug 11 '10 #3
Frinavale
9,735 Recognized Expert Moderator Expert
Initialize your array with an invalid number like -1 or 0 or something (since your users are using 1 and 2).

Now, only write a 1 or 2 in the array if that particular element doesn't have a 1 or 2 already in it (as long as it's less than 1). If there is a 1 or 2 already in the array at the element selected, tell the user that they have to choose a different spot (or if it's the computer's turn, have it generate a new random selection until it was successful)

-Frinny
Aug 11 '10 #4
oedipus
6 New Member
-Frinavale
Thank you once again for your insight.I have already initialised all the elements intthe array to 0.The problem I am currently experiencing is that I cannot find the right code/syntax to do what you have suggested.
The way I see it is as follows:
-In a do-while loop(is that the correct loop?)generate the random element.
-Then check whether the value of the random element is <1.
--If it is less than 1, the loop will terminate and then after the loop, assign the value 1 to the element.
--If it is greater than 1, the loop will continue to run until an element is generated that is less than 1.

Is this what it should look like?
Also, could you please show me an example of the syntax used to seed a random integer number using seconds (I've tried it but keep getting an error.)?
Expand|Select|Wrap|Line Numbers
  1. //grid is the name of the 2d array.
  2. int row;
  3. int column;
  4. do{
  5. row=(int)(Math.random()*2+0);
  6. column=(int)(Math.random()*2+0);
  7. }while(grid[row][column]>0);
  8. grid[row][column]=1;
  9.  
Thanks-Oedipus
Aug 12 '10 #5
Frinavale
9,735 Recognized Expert Moderator Expert
What is the error message that you are seeing?
Aug 12 '10 #6
oedipus
6 New Member
-Frinavale
I cannot recall exactly what it was as I tried it out a while ago . It was something like "Random cannot be applied to int". I think I may have also messed up in getting the current time.
Aug 12 '10 #7
Frinavale
9,735 Recognized Expert Moderator Expert
The reason you're seeing this error is because Math.random() returns a Random Object which is not an int.

You use this Random object to get a random int (or you could use it to get a random double etc...it depends on your needs but in this case you're looking for an int)

So, you need a random integer in the range 0 to 2. The Random Object's "nextInt" method can give you this.

Make sure that you have:
Expand|Select|Wrap|Line Numbers
  1. import java.util.Random;
Or:
Expand|Select|Wrap|Line Numbers
  1.  import java.util.*;


Ok, now create a new instance Random class so that you can use this instances to call the "nextInt()" method. This method will return a random int. You can specify the range by providing the upper limit to the nextInt() method...so to return an int within the range of 0 and 2 you would provide the nextInt method with "3" (RandomInstance .nextInt(3))...


Expand|Select|Wrap|Line Numbers
  1.   Random generator = new Random();
  2.   int row;
  3.   int column;
  4.   do{
  5.     row = generator.nextInt(3);
  6.     column = generator.nextInt(3);
  7.   }while(grid[row][column]>0)
  8.  
-Frinny
Aug 12 '10 #8
oedipus
6 New Member
-Frinavale
Thank you,thank you and thank you.
It turns out that was all I really needed.I truly appreciate your help.
On the topic of my avatar, its actually a My Chemical Romance avatar. Perhaps the owner of the site is a fan?

Many, many thanks-Oedipus
Aug 12 '10 #9
Frinavale
9,735 Recognized Expert Moderator Expert
No problem :)

You have the possibility of running into an endless loop with your current code. I hope you are checking to make sure that a move can be made before running :)

Off topic: it turns out there was some strangeness going on with my browser that made some people's avatars look like the owners...After clearing cache & refreshing the browser your real avatar was reviled to me....I still think there was a weak conspiracy to make me look crazy!
Aug 12 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

6
2965
by: Sims | last post by:
Hi, Given a string $txt and an array of strings $txt_array what would be the best/fastest way to search in _insensitive_ case if $txt is in $text_array and, if it is, where is it? Because I want to use the array with an ID Something like,
1
2024
by: supportgeek | last post by:
Greetings. Would anyone know the right direction to point me on this one? I need to read text from a Windows Application based on cursor position. And enter text based on what is read. Example:(the interface of the windows application would look something like this.)
2
2137
by: AlternativaMente | last post by:
I need help to build a simcity-like game. Exspecially I don't know how I can render the graphics. I'm looking for a not-too-difficult way to do it Thanks in advance Emanuele
9
1667
by: silverchrono | last post by:
this is my first semester in C and im trying to figure out how to reset a counter. heres why im trying to do. void text() 59 printf("You can end entering the text by using '#'\n"); 60 int i=0; 61 int j=0;
0
1562
by: Jmay | last post by:
hey, im trying to create a text based game i guess, with networkin i jsut want it to go on the lan network, im wondering how could i create a program that has a client that sends a msg to a server then saves it, and then get the client to pick up this info later, so basicly Client ---> Server ---> database (save) database --> client (to get) or something to that idea just wondering if someone can post a few examples and then...
1
2615
by: Joel Fireman | last post by:
Help Needed: Upgrade Fedora 4 / Apache 2 to PHP 5.2.x from 5.0.4 I've been testing Joomla as a content manager for the County offices, and it looks pretty good. Unfortunately, I decided to upgrade it from the 1.0.13 version to 1.5 as we get ready to go live with the web site... and the update installation gives an error in XML processing, which seems (from what I've been able to dredge up in forum discussions) to stem from a known bug in...
3
1776
by: Mefistofeles | last post by:
Hello. Need help to make text-based radio buttons. On my calender site I want to have text that works like radio buttons. Exampel, bold text is the selected radio-text. Jan Feb Mar Apr May Jun Jul Aug ..... This is my code right now:
0
1299
by: Fratyr | last post by:
Hello Experts. This is my fourth time im starting to learn PHP/MySQL/AJAX All the times i tried, was boring, because i was learning only the syntax commands. Now i do another way. I decided to build up something that i would like to call "its mine!" So it will probably be simple text-based mmorpg game. Everything goes well until this: Database MySQL scheme. How would i build the tables? I mean, i know how, but i also know that there...
1
1224
by: gresey4 | last post by:
i have a question how do i make in game accounts in my text based game EX(In a game like Hobo wars or Urbandead OR deadawaken they have small accounts for the people who registered and play their game like that
0
11605
by: JosAH | last post by:
A Simple Text-Based Menu System Read this this post; there are numerous posts like that: a newbie struggling with some sort of menu implementation. They want nested menus of course and an option to quit the entire thing. Of course they tie their 'business rules' tight together with their (feeble) attempts of their individual menu items and get heavily entangled in complicated control structures. The post (see the link above) made me write...
0
8685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9171
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.