How can i detect a winner
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.Random;
public class TicTacToe extends JFrame {
private Board board;
static final char BLANK=' ', O='O', X='X';
private char position[]={ // Board position (BLANK, O, or X)
BLANK, BLANK, BLANK,
BLANK, BLANK, BLANK,
BLANK, BLANK, BLANK};
private int wins=0, losses=0, draws=0; // game count by user
// Start the game
public static void main(String args[]) {
new TicTacToe();
// Constructor of TicTacToe: Initialize settings
public TicTacToe() {
super("Tic Tac Toe");
add(board=new Board(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
// Board is what actually plays and displays the game
private class Board extends JPanel implements MouseListener {
// Constructor of Board
public Board() {
addMouseListener(this);
// Redraw the board
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w=getWidth();
int h=getHeight();
Graphics2D g2d = (Graphics2D) g;
// Draw the grid
g2d.setPaint(Color.WHITE);
g2d.fill(new Rectangle2D.Double(0, 0, w, h));
g2d.setPaint(Color.BLACK);
g2d.setStroke(new BasicStroke(4));
g2d.draw(new Line2D.Double(0, h/3, w, h/3));
g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));
g2d.draw(new Line2D.Double(w/3, 0, w/3, h));
g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));
// Draw the Os and Xs
for (int i=0; i<9; ++i) {
double xpos=(i%3+0.5)*w/3.0;
double ypos=(i/3+0.5)*h/3.0;
double xr=w/8.0;
double yr=h/8.0;
if (position==O) {
g2d.setPaint(Color.BLUE);
g2d.draw(new Ellipse2D.Double(xpos-xr, ypos-yr, xr*2, yr*2));
else if (position[i]==X) {
g2d.setPaint(Color.RED);
g2d.draw(new Line2D.Double(xpos-xr, ypos-yr, xpos+xr, ypos+yr));
g2d.draw(new Line2D.Double(xpos-xr, ypos+yr, xpos+xr, ypos-yr));
// Draw an O where the mouse is clicked
public void mouseClicked(MouseEvent e) {
int xpos=e.getX()*3/getWidth();
int ypos=e.getY()*3/getHeight();
int pos=xpos+3*ypos;
if (pos>=0 && pos<9 && position[pos]==BLANK) {
position[pos]=O;
repaint();
putX(); // computer plays
repaint();
// Ignore other mouse events
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
// Computer plays X
public void putX() {
// Check if game is over
if (won(O))
newGame(O);
else if (isDraw())
newGame(BLANK);
// Play X, possibly ending the game
else {
nextMove();
if (won(X))
newGame(X);
else if (isDraw())
newGame(BLANK);
// Play X in one of the empty spot
public void nextMove() {
int r;
do {
Random random=new Random();
r=random.nextInt(9); // move randomly
} while (position[r]!=BLANK);
position[r]=X;
// Return true if player has won
public boolean won(char player) {
// ********** put your code here **********
// ......if else
return false;
// Are all 9 spots filled? Return true if yes
public boolean isDraw() {
// ********** put your code here **********
// ......if else
return false;
// Start a new game
public void newGame(char winner) {
repaint();
// Announce result of last game. Ask user to play again.
String result;
if (winner==O) {
++wins;
result = "You Win!";
else if (winner==X) {
++losses;
result = "I Win!";
else {
result = "Tie";
++draws;
if (JOptionPane.showConfirmDialog(null,
"You have "+wins+ " wins, "+losses+" losses, "+draws+" draws\n"
+"Play again?", result, JOptionPane.YES_NO_OPTION)
!=JOptionPane.YES_OPTION) {
System.exit(0);
// Clear the board to start a new game
for (int j=0; j<9; ++j)
position[j]=BLANK;
// Computer starts first every other game
if ((wins+losses+draws)%2 == 1)
nextMove();
} // end inner class Board
} // end class TicTacToe
I am doing a Tic Tac Toe...but in the middle
I can't type the code to find the winner
can you all please help me??
That makes about 8 cross-posts for the same damn question in 1 day. Have you no concern for the requests of the forum members?
Similar Messages
-
How can I detect a dialog and respond?
I'm having trouble doing something that's probably not that hard. I'm trying to "Print to PDF" a bunch of old AppleWorks documents. When you open a document created in AppleWorks v6 it opens right up, but when you open a document created in AppleWorks 5 you get a dialog box that says, "This document was created by a previous version of AppleWorks. A copy will be opened and "[v6.0]" will be added to the filename."
Right now I open the file and then:
tell application "AppleWorks 6"
activate
repeat while not (exists front document)
delay .2
end repeat
end tell
When the dialog box pops up, there's no front document so the whole thing freezes until you hit OK. How can I detect this dialog box and dismiss it?
Thanks
PS
When the box is open I ran this and got this result:
/usr/bin/osascript -e 'tell application "System Events" to get properties of windows of application process "AppleWorks 6"'
minimum value:missing value, orientation:missing value, position:436, 153, class:window, role description:dialog, accessibility description:missing value, focused:missing value, title:missing value, size:412, 123, value:missing value, help:missing value, enabled:missing value, maximum value:missing value, role:AXWindow, entire contents:, subrole:AXDialog, selected:missing value, name:missing value, description:dialog, minimum value:missing value, orientation:missing value, position:8, 76, class:window, role description:floating window, accessibility description:missing value, focused:missing value, title:Starting Points, size:631, 189, value:missing value, help:missing value, enabled:missing value, maximum value:missing value, role:AXWindow, entire contents:, subrole:AXFloatingWindow, selected:missing value, name:Starting Points, description:floating window, minimum value:missing value, orientation:missing value, position:4, 22, class:window, role description:floating window, accessibility description:missing value, focused:missing value, title:Button Bar, size:612, 51, value:missing value, help:missing value, enabled:missing value, maximum value:missing value, role:AXWindow, entire contents:, subrole:AXFloatingWindow, selected:missing value, name:Button Bar, description:floating windowHi,
The simplest would be to set the application preferences in the script.
Like this :
-- *** set prefs ****
tell application "AppleWorks 6"
activate
set oldPrefs to its preferences
copy oldPrefs to tPrefs
tell tPrefs
set old version warning to false --doesn't show the old version warning alert
set converted file suffix to true -- append “[v6.0]” to documents converted from older formats
set locked file warning to false
set paint reduction warning to false
end tell
set preferences to tPrefs
end tell
-- *** end set prefs ****
--**** your script, example ***
set tfiles to choose file with multiple selections allowed
tell application "AppleWorks 6"
repeat with i in tfiles
open i
tell front document
-- do something
end tell
end repeat
end tell
--**** end your script ***
-- *** reset prefs ****
tell application "AppleWorks 6" to set preferences to oldPrefs -
How can I detect a certain text within a field within CASE using IF
Dear all,
for a transformation / generation of values receiving from R/3 into BW I try to
manupulate three fields. I have a problem detecting a string in a field.
I am using a CASE with several WHEN clauses on one field. Depending on the
value, an IF is integrated. There I look into another field evaluating, if it contains
a certain string. E.g. IF STRING CP 'xyz' OR 'abc'.
System gives error for the locigal expression. I also tried CS, but same error.
How can I detect a certain text within a field and which is the right logical
expression.
Many thanks in advance!!!
ClaudiaHi,
Folow the blow example...
May be it helps....
DATA: hex1 TYPE string,
hex2 TYPE string.
hex1 = 'FFFF'.
hex2 = '123FF'.
IF hex1 CP hex2.
ENDIF.
Cheers,
SImha. -
Hello Everyone,
We all know whenever we try to connect to a PC which is not on network, we get UnKnownHostException etc..... by which we can detect that the corresponding PC is not an network(intranet/internet)
But when i send a msg from my PC to my PC, it works fine even if the network is down. I hv provided my PC's IP address instead of using localhost or 127.0.0.1 which reduces the possibility that the msg will not be traversed thru the network.
Any IDEA how this works.
Is There any possible way by which i can detect that my PC is not on network or the PC to which i'm trying to connect is not on network .......
Pls help me out, its really urgent as to be implemented in my Project
Thanks In Advance
Sahil ShaikhHello Surtee
I have developed a Messeging Service for the eCRM Apllication my company is developing and we r in the final stage of debugging.
Now whenever a user sends a msg to a PC which is not on network, the messaging service automatically sends an Offline mssg to that PC. But know i want ot distinguish wheather the PC to which i'm sending the msg is not on network or am I not on network based on this i need to perform diff. actions, hence i wanted to know that how can i detect .......
Pls see if u canhelp me out ......
Thanks
Sahil Shaikh -
How can we detect a virus on our mac?, How can we detect a virus on our mac?
We think we may have a virus from the USPS spam email. How can we detect a virus on our computer?
What makes you think there is a "virus"? Any symptoms...?
There are other types of malware (such as trojans) that can affect Mac OS X, but no viruses. A trojan would have to trick you into installing something (the malware) by making you think it is something else. You would be notified (by the system) that you are running a downloaded application for the first time, AND if something will be done to update your current system, you will be asked to authenticate (with your admin user name and password). If something like that comes up when you don't expect it, you should be suspicious (and NOT authenticate). Just opening an email won't do anything, even if it's an email that may affects Windows PCs.
This free utility can scan your Mac for malware.
http://www.clamxav.com/
Apparently, there is a version on the Mac App Store.
http://search.itunes.apple.com/WebObjects/MZContentLink.woa/wa/link?path=mac%2fC lamXav
In the past, when I bothered to run it a few times a year, the only things it found were junk emails that I had not bothered to delete with embedded malware, all of it aimed at Windows PCs. -
How can i detect the windows version
Hi,
How can I detect the windows version from Forms 6i?
I was used get_application_property(operating_system); But it only return MSWINDOWS, MSWINDOWS32, WIN32COMMON.
Any function or way can return the exact windows version(98/ME/NT/XP)?
Regards, WingYou may use Win_Api_Environment API call to get windows version.
I have sample code on my home PC if you need code send mail at [email protected] -
How can I detect the lable of CD or hard drive?
hi all
How can I detect the lable of CD or hard drive?
thanx ;)Hi,
Not to my knowmledge... you must use JNI to access the OS methods for that.
JRG -
How can I detect that there is an internet connection?
How can I detect that there is an internet connection?
Peter GoossensHow can I detect that there is an internet connection?
Peter Goossens
Peter,
You might want to experiment with this. It's not perfect, but...
Class
Imports System.IO
Imports System.Net
Namespace InternetConnection
Public Class SiteInfo
Private _displayName As String
Private _connectionString As String
Private Sub New(ByVal name As String, _
ByVal connectionString As String)
_displayName = name.Trim
_connectionString = connectionString.Trim
End Sub
''' <summary>
''' Gets the connection string of this instance.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property ConnectionString() As String
Get
Return _connectionString
End Get
End Property
''' <summary>
''' Gets the display name of this instance.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property DisplayName() As String
Get
Return _displayName
End Get
End Property
''' <summary>
''' A method which will add a new site to your collection of SiteInfo.
''' </summary>
''' <param name="siList">Your generic List(Of SiteInfo).</param>
''' <param name="displayName">The display name for this new instance
''' of SiteInfo.</param>
''' <param name="connectionString">The connection string for this
''' new instance of SiteInfo.</param>
''' <remarks></remarks>
Public Shared Sub AddNew(ByRef siList As List(Of SiteInfo), _
ByVal displayName As String, _
ByVal connectionString As String)
Try
If siList Is Nothing Then
Throw New NullReferenceException("The collection of SiteInfo cannot be null.")
ElseIf String.IsNullOrEmpty(displayName) OrElse displayName.Trim = "" Then
Throw New ArgumentException("The display name cannot be null or empty.")
ElseIf String.IsNullOrEmpty(connectionString) OrElse connectionString.Trim = "" Then
Throw New ArgumentException("The connection string cannot be null or empty.")
Else
If siList.Count > 0 Then
Dim findDuplicate As IEnumerable(Of SiteInfo) = _
From si As SiteInfo In siList _
Where si.DisplayName.ToLower.Replace(" "c, "") = _
displayName.ToLower.Replace(" "c, "") AndAlso _
si.ConnectionString.ToLower.Replace(" "c, "") = _
connectionString.ToLower.Replace(" "c, "")
If findDuplicate.Count <> 0 Then
Throw New ArgumentException("This is a duplicate entry.")
Else
siList.Add(New SiteInfo(displayName, connectionString))
End If
Else
siList.Add(New SiteInfo(displayName, connectionString))
End If
End If
Catch ex As Exception
Throw
End Try
End Sub
''' <summary>
''' A method which will return a boolean value to indicate internet
''' connection status.
''' </summary>
''' <param name="siList">Your generic List(Of SiteInfo).</param>
''' <param name="displayName">The display name for the instance
''' of SiteInfo to use.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function InternetIsConnected(ByVal siList As List(Of SiteInfo), _
ByVal displayName As String) As Boolean
Dim retVal As Boolean = False
Try
If siList Is Nothing Then
Throw New NullReferenceException("The collection of SiteInfo cannot be null.")
ElseIf siList.Count = 0 Then
Throw New ArgumentOutOfRangeException("Count", "The collection of SiteInfo cannot be empty.")
ElseIf String.IsNullOrEmpty(displayName) OrElse displayName.Trim = "" Then
Throw New ArgumentException("The display name cannot be null or empty.")
Else
Dim findInstance As IEnumerable(Of SiteInfo) = _
From si As SiteInfo In siList _
Where si.DisplayName.ToLower.Replace(" "c, "") = _
displayName.ToLower.Replace(" "c, "")
If findInstance.Count <> 1 Then
Throw New ArgumentException("This instance is not in the collection of SiteInfo.")
Else
retVal = TestConnection(findInstance.First.ConnectionString)
End If
End If
Catch ex As Exception
Throw
End Try
Return retVal
End Function
Private Shared Function TestConnection(ByVal url As String) As Boolean
Dim retVal As Boolean = False
Try
Dim request As WebRequest = WebRequest.Create(url)
Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
Using dataStream As Stream = response.GetResponseStream
Using reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
retVal = True
End Using
End Using
End Using
Catch ex As WebException
retVal = True
Catch ex As Exception
retVal = False
End Try
Return retVal
End Function
End Class
End Namespace
Example Usage
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim siList As New List(Of InternetConnection.SiteInfo)
InternetConnection.SiteInfo.AddNew(siList, _
"Test1", _
"http://dev.virtualearth.net/REST/v1/Locations/37221?o=xml")
InternetConnection.SiteInfo.AddNew(siList, _
"Test2", _
"nothing here")
InternetConnection.SiteInfo.AddNew(siList, "Test3", _
"www.google.com")
InternetConnection.SiteInfo.AddNew(siList, "Test4", _
"http://fls-online.com")
' This will return true:
Dim bool1 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test1")
' This will return false:
Dim bool2 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test2")
' This will return false:
Dim bool3 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test3")
' This will return true:
Dim bool4 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test4")
Stop
End Sub
End Class
Let me know your results please?
Still lost in code, just at a little higher level. -
How can I detect the PC show down event?
I want to save a file to a certain destination once the PC shut down event happened.
And the save process must be proceeded prior to the PC shutdown.
How can I detect the PC shut down event?Hi there
Try the "Application Instance Close?" Event.
Best regards
chris
CL(A)Dly bending G-Force with LabVIEW
famous last words: "oh my god, it is full of stars!" -
How can I detect in Business HTML that the app was called from portal?
How can I detect in Business HTML that the app was called from portal?
I need to distinguish whether the application was called from portal (URL iView) or by using an URL outside of portal.
So what I'm looking for is a variable or function that can be used like this:
`if (~within_portal==1)`
do this if called from portal
`else;`
do that if not called from portal
`end;`
For example, can I check in the program that there is a SSO2 cookie from the portal?
I'm using Integrated ITS in Basis 700.Here is the trick:
if (sapwp_active=="1")
in portal
else
without portal
end; -
How can I detect if I'm running a compiled versione of my application?
In my application I have included some special functions I don't want my customer to use. Since I will distribute the application as an .exe file, instead of cutting away those functions before releasing the .exe, I want to hide them when the application is runnig as an executable, and leave them active when running in the LV environment.
How can I detect if I'm running an executable or the LV environment? Do I have to scan the application name until I find an .exe different from labview.exe or there is another way to obtain the flag (something similar to CVI function InStandaloneExecutable() for example)?
Roberto
Proud to use LW/CVI from 3.1 on.
My contributions to the Developer Zone Community
If I have helped you, why not giving me a kudos?An application property exists:Application:Kind
with the following values: Development System, Runtime System, Student Edition, or Embedded LabVIEW.
greetings from the Netherlands -
How can I detect the vertices of a rectangle in my image ?
I have applied a gradientMagnitude operator to my Image, and now I can see the shape of a rectangle with also other lines.
How can I detect the vertices of the rectangle in my image?
thank youRight mouse click the song and select "Get Info", go to option tab and check both Start Time and Stop Time. Type in the Start and Stop time then click OK
-
How can i detect if the picture or swf file is produced from legal flash?
I have recently bought images and swf files from a student for my website.
I've just realized that the images and swf might be from pirated flash product because i found out that
the original flash is really and i mean really pricey! I don't believe he bought an original product.
How do i detect if it is from a legal product? I'm worried as i'm going to put it in my website.
I can't get the guy who did this for me as he is in another country already.
If it is possible to detect this and it is indeed from pirated product, how can i make it legal again?
Please help.Hey Rob,
Its the same question, just that i want to know if it is possible to trace the source if the file is an image.
If it is not possible to trace the source be it a swf or an image file, then i will just upload it to my website.
I wouldn't bother to check if it came from a pirated flash product.
The image is created from flash 8 just for me. It is not downloaded from another source.
Thanks. -
How can I detect that a device is from Motorola !
hi all !
I want to detect if my device is a Motorola one, to do so, I was checking the class com.motorola.extensions.ScalableImage, if it's present I know that the device is a Motorola.
but, now, I have some devices (V8) that didn't support this class, so how can I do otherwise ?
I saw that there's an API named get URL from flex, but i don't now more about !
some one can help me ?
Regards, Idircheck this out
// detecting NOKIA or SonyEricsson
try {
final String currentPlatform = System.getProperty("microedition.platform");
if (currentPlatform.indexOf("Nokia") != -1) {
return "nokia";
} else if (currentPlatform.indexOf("SonyEricsson") != -1) {
return "SE";
} catch (Throwable ex) {
// detecting SAMSUNG
try {
Class.forName("com.samsung.util.Vibration");
return "samsung";
} catch (Throwable ex) {
// detecting MOTOROLA
try {
Class.forName("com.motorola.multimedia.Vibrator");
return "motorola";
} catch (Throwable ex) {
try {
Class.forName("com.motorola.graphics.j3d.Effect3D");
return "motorola";
} catch (Throwable ex2) {
try {
Class.forName("com.motorola.multimedia.Lighting");
return "motorola";
} catch (Throwable ex3) {
try {
Class.forName("com.motorola.multimedia.FunLight");
return "motorola";
} catch (Throwable ex4) {
// detecting SIEMENS
try {
Class.forName("com.siemens.mp.io.File");
return "siemens";
} catch (Throwable ex) {
// detecting LG
try {
Class.forName("mmpp.media.MediaPlayer");
return "LG";
} catch (Throwable ex) {
try {
Class.forName("mmpp.phone.Phone");
return "LG";
} catch (Throwable ex1) {
try {
Class.forName("mmpp.lang.MathFP");
return "LG";
} catch (Throwable ex2) {
try {
Class.forName("mmpp.media.BackLight");
return "LG";
} catch (Throwable ex3) {
} pravin -
In AS3 how can you detect if someone pulls their camera out of the USB port?
In AS3 if the SWF gets a hold of someone's camera successfully and they start streaming video across and everything, but then mid-stream, either they accidentally wiggle their camera out of the USB port, or the camera just sort of breaks down, or something else like that, how could you detect it from that user's side? I've tried using event listeners and also polling different variables every five seconds, but neither has worked; none of the public properties of Camera or its events seem to act funny at all when something like that happens. And apparently you can't just keep scanning the computer for devices (for good reason, I guess).
Is there something I'm missing here? Is there a way to detect from a user's copy of a SWF (FP or AIR, but much more importantly FP) when their camera has effectively stopped as the result of something going wrong, such as them wiggling it out of the computer by mistake? If so how? Thanks!Run your code and disconnect your camera. What are the common properties of it? Does your stream stop? Return only a specific color frame? Those things are usable to detect it but you're right in saying you can't detect much more than a loss of packets from a NetStream object.
Maybe you are looking for
-
How can I change the background color of odd/even rows in a panelCollection
Hi everyone. I'm using a panelCollection and I need to change the backgroung color for odd/even rows in the table, how can I do this, using a stylesheet, is there a special selector or property for this? globalResultCollection (UIPanelCollection obje
-
Syncing with reinstalled iTunes
I had to reflash my hard drive due to a trojan problem. When I reinstalled iTunes, it no longer pairs with my iPod Classic and will not sync content from my ipod to iTunes. I was only able to transfer iTunes store purchases from the ipod to iTunes.
-
I just don´t remember how to open folders always in list view. Thank you.
-
Use value from tabular form column in the LOV where clause of another column
Hi Using APEX 4.2 on 11g In a tabular form I want to filter the values in a Popup Key LOV based on the value of another column (same row). i.e. I want to get the value of one column and use it in the where clause for the Popup LOV on the same row. e.
-
Is an iphone (5 in specific) made for a specific carrier?
My mom deactivated her iphone 5 and gave it to me. It was Verizon. I use t-mobile so I go to the T-mobile shop and buy a smaller SIM for it. The employees said I couldn't because of the carrier type.they stated it wouldn't work. I don't know if that'