Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Tic Tac Toe Multiplayer (Spiel) (Kleinprojekte)

Programmiere das Spiel Tic Tac Toe. (http://de.wikipedia.org/wiki/Tic_Tac_Toe)

- mit Grafischer Oberfläche

- mit mehreren Spielrunden

- mit Auswertung , wer gewonnen hat

Zusatzaufgabe:

- mit Computergegner (KI)

2 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

Kommentare (2)

Kevin 13. Dezember 2013 16:15   reply report
Habe meins nochmal bisschen gekürzt... war wirklich viel zu umständlich geschrieben :)
crouser 9. Dezember 2013 14:51   reply report
Meine Lösung ist etwas umständlich umgesetzt, da ich eine möglichst einfache Lösung bieten wollte, ohne groß Zeilen zu verschwenden. Dafür habe ich den kompletten Code durchkommentiert. Sollte halbwegs verständlich sein.

5 Lösung(en)

def Mausscroll(event):
    dir = 0
    if event.num == 5 or event.delta == -120:
        dir = 1
    if event.num == 4 or event.delta == 120:
        dir = -1
    zeichenbrett.yview_scroll(dir, "units")
def Unentschieden(n):
    global PunktzahlSp1, PunktzahlSp2, NameSp1, NameSp2, u, en
    n += (u * 400)
    zeichenbrett.create_text(500, n, text = PunktzahlSp1)
    zeichenbrett.create_text(600, n, text = PunktzahlSp2)
    if en == 19:
        NSp1 = (NameSp1)
        NSp2 = (NameSp2)
        hg = " hat gewonnen!"
        NSp1hg = NSp1 + hg
        NSp2hg = NSp2 + hg
        if PunktzahlSp1 == PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = "Unentschieden!")
        if PunktzahlSp1 > PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = (NSp1hg))
        if PunktzahlSp1 < PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = (NSp2hg))
def Spieler1(n):
    global PunktzahlSp1, PunktzahlSp2, NameSp1, NameSp2, u, en
    n += (u * 400)
    PunktzahlSp1 += 1
    zeichenbrett.create_text(500, n, text = PunktzahlSp1)
    zeichenbrett.create_text(600, n, text = PunktzahlSp2)
    if en == 19:
        NSp1 = (NameSp1)
        NSp2 = (NameSp2)
        hg = " hat gewonnen!"
        NSp1hg = NSp1 + hg
        NSp2hg = NSp2 + hg
        if PunktzahlSp1 == PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = "Unentschieden!")
        if PunktzahlSp1 > PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = (NSp1hg))
        if PunktzahlSp1 < PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = (NSp2hg))
def Spieler2(n):
    global PunktzahlSp2, PunktzahlSp2, NameSp1, NameSp2, u, en
    n += (u * 400)
    PunktzahlSp2 += 1
    zeichenbrett.create_text(600, n, text = PunktzahlSp2)
    zeichenbrett.create_text(500, n, text = PunktzahlSp1)
    if en == 19:
        NSp1 = (NameSp1)
        NSp2 = (NameSp2)
        hg = " hat gewonnen!"
        NSp1hg = NSp1 + hg
        NSp2hg = NSp2 + hg
        if PunktzahlSp1 == PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = "Unentschieden!")
        if PunktzahlSp1 > PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = (NSp1hg))
        if PunktzahlSp1 < PunktzahlSp2 :
            zeichenbrett.create_text(550, 7700, text = (NSp2hg))
def Buttons(y1, y2, y3, y4, y5, y6, y7, y8, y9):
    global u, button1, button2, button3, button4, button5, button6, button7, button8, button9
    u += 1    
    button1 = Button(zeichenbrett, text = "", command = B1 , anchor = W)
    button1.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button1_window = zeichenbrett.create_window(10, y1, anchor=NW, window=button1)
    button2 = Button(zeichenbrett, text = "", command = B2 , anchor = W)
    button2.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button2_window = zeichenbrett.create_window(110, y2, anchor=NW, window=button2)
    button3 = Button(zeichenbrett, text = "", command = B3 , anchor = W)
    button3.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button3_window = zeichenbrett.create_window(210, y3, anchor=NW, window=button3)
    button4 = Button(zeichenbrett, text = "", command = B4 , anchor = W)
    button4.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button4_window = zeichenbrett.create_window(10, y4, anchor=NW, window=button4)
    button5 = Button(zeichenbrett, text = "", command = B5 , anchor = W)
    button5.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button5_window = zeichenbrett.create_window(110, y5, anchor=NW, window=button5)
    button6 = Button(zeichenbrett, text = "", command = B6 , anchor = W)
    button6.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button6_window = zeichenbrett.create_window(210, y6, anchor=NW, window=button6)
    button7 = Button(zeichenbrett, text = "", command = B7 , anchor = W)
    button7.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button7_window = zeichenbrett.create_window(10, y7, anchor=NW, window=button7)
    button8 = Button(zeichenbrett, text = "", command = B8 , anchor = W)
    button8.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button8_window = zeichenbrett.create_window(110, y8, anchor=NW, window=button8)
    button9 = Button(zeichenbrett, text = "", command = B9 , anchor = W)
    button9.configure(width = 9, height = 5, activebackground = "#33B5E5", relief = FLAT)
    button9_window = zeichenbrett.create_window(210, y9, anchor=NW, window=button9)
def gitterzeichnen(a, b, c, d, e, h, j, n, o, aa, bb):
    global f
    if e > 0:
        gitter = Schildkroete(zeichenbrett)
        gitter.setX(0)
        gitter.setY(a)
        gitter.dreheLinks(90)
        gitter.gehe(300)
        gitter.setX(0)
        gitter.setY(b)
        gitter.gehe(300)
        gitter.dreheRechts(90)
        gitter.setX(100)
        gitter.setY(c)
        gitter.gehe(300)
        gitter.setX(200)
        gitter.setY(d)
        gitter.gehe(300)
        gitter.setX(450)
        gitter.setY(h)
        gitter.dreheLinks(90)
        gitter.gehe(200)
        gitter.setX(550)
        gitter.setY(j)
        gitter.dreheRechts(90)
        gitter.gehe(45)
        zeichenbrett.create_text(500, n, text = NameSp1)
        zeichenbrett.create_text(600, n, text = NameSp2)
        zeichenbrett.create_text(aa, o, text = "Kreuz")
        zeichenbrett.create_text(bb, o, text = "Kreis")
        if aa == 500:
            aa = 600
        elif aa == 600:
            aa = 500
        if bb == 500:
            bb = 600
        elif bb == 600:
            bb = 500
        a += 400
        b += 400
        c += 400
        d += 400
        h += 400
        j += 400
        n += 400
        o += 400
        e-=1
        gitterzeichnen( a, b, c, d, e, h, j, n, o, aa, bb)
def ztausch():
    global z
    if z == 1:
        z = 2
    elif z == 2:
        z = 1
def Spielstand():
    global u, y11, y12, y13, y14, y15, y16, y17, y18, y19, g, button1, button2, button3, button4, button5, button6, button7, button8, button9, z, q, en    
    if 1 in g and 2 in g and 3 in g or 4 in g and 5 in g and 6 in g or 7 in g and 8 in g and 9 in g or 1 in g and 4 in g and 7 in g or 2 in g and 5 in g and 8 in g or 3 in g and 6 in g and 9 in g or 1 in g and 5 in g and 9 in g or 3 in g and 5 in g and 7 in g :
        if q == 1:
            Spieler1(70)
        if q == 2:
            Spieler2(70)
        z = 1
        if 1 not in g and 11 not in g:
            button1.destroy()
        if 2 not in g and 12 not in g:
            button2.destroy()
        if 3 not in g and 13 not in g:
            button3.destroy()
        if 4 not in g and 14 not in g:
            button4.destroy()
        if 5 not in g and 15 not in g:
            button5.destroy()
        if 6 not in g and 16 not in g:
            button6.destroy()
        if 7 not in g and 17 not in g:
            button7.destroy()
        if 8 not in g and 18 not in g:
            button8.destroy()
        if 9 not in g and 19 not in g:
            button9.destroy()
        if q == 1:
            q = 2
        elif q == 2:
            q = 1
        g = []
        y11 += 400
        y12 += 400
        y13 += 400
        y14 += 400
        y15 += 400
        y16 += 400
        y17 += 400
        y18 += 400
        y19 += 400
        en += 1
        Buttons(y11, y12, y13, y14, y15, y16, y17, y18, y19)
    if 11 in g and 12 in g and 13 in g or 14 in g and 15 in g and 16 in g or 17 in g and 18 in g and 19 in g or 11 in g and 14 in g and 17 in g or 12 in g and 15 in g and 18 in g or 13 in g and 16 in g and 19 in g or 11 in g and 15 in g and 19 in g or 13 in g and 15 in g and 17 in g :
        if q == 1:
            Spieler2(70)
        if q == 2:
            Spieler1(70)
        z = 1
        if 1 not in g and 11 not in g:
            button1.destroy()
        if 2 not in g and 12 not in g:
            button2.destroy()
        if 3 not in g and 13 not in g:
            button3.destroy()
        if 4 not in g and 14 not in g:
            button4.destroy()
        if 5 not in g and 15 not in g:
            button5.destroy()
        if 6 not in g and 16 not in g:
            button6.destroy()
        if 7 not in g and 17 not in g:
            button7.destroy()
        if 8 not in g and 18 not in g:
            button8.destroy()
        if 9 not in g and 19 not in g:
            button9.destroy()
        if q == 1:
            q = 2
        elif q ==2:
            q = 1
        g = []
        y11 += 400
        y12 += 400
        y13 += 400
        y14 += 400
        y15 += 400
        y16 += 400
        y17 += 400
        y18 += 400
        y19 += 400
        en += 1
        Buttons(y11, y12, y13, y14, y15, y16, y17, y18, y19)
    if (1 in g or 11 in g) and(2 in g or 12 in g) and(3 in g or 13 in g) and(4 in g or 14 in g) and(5 in g or 15 in g) and(6 in g or 16 in g) and(7 in g or 17 in g) and(8 in g or 18 in g) and(9 in g or 19 in g):
        zeichenbrett.create_text(400, 50 + (u * 400), text = "Unentschieden")
        Unentschieden(70)
        z = 1
        if 1 not in g and 11 not in g:
            button1.destroy()
        if 2 not in g and 12 not in g:
            button2.destroy()
        if 3 not in g and 13 not in g:
            button3.destroy()
        if 4 not in g and 14 not in g:
            button4.destroy()
        if 5 not in g and 15 not in g:
            button5.destroy()
        if 6 not in g and 16 not in g:
            button6.destroy()
        if 7 not in g and 17 not in g:
            button7.destroy()
        if 8 not in g and 18 not in g:
            button8.destroy()
        if 9 not in g and 19 not in g:
            button9.destroy()
        g = []
        y11 += 400
        y12 += 400
        y13 += 400
        y14 += 400
        y15 += 400
        y16 += 400
        y17 += 400
        y18 += 400
        y19 += 400
        en += 1
        Buttons(y11, y12, y13, y14, y15, y16, y17, y18, y19)
def kreuzmalen(v, x, y):
    global g
    x2 = x + 100
    kreuz = Schildkroete(zeichenbrett)
    kreuz.setX(x)
    kreuz.setY(y)
    kreuz.dreheLinks(45)
    kreuz.gehe(141.4)
    kreuz.setX(x2)
    kreuz.setY(y)    
    kreuz.dreheRechts(90)
    kreuz.gehe(141.4)
    g += [v]
    ztausch()
    Spielstand()
def kreismalen(v, x, y):
    global g
    kreis = Schildkroete(zeichenbrett)
    kreis.setX(x)
    kreis.setY(y)
    for i in range (350):
        kreis.dreheLinks(1.4)
        kreis.gehe(1)
    g += [v]
    ztausch()
    Spielstand()
def B1():
    global u, button1
    kuY = 0 + (u*400)
    kiY = 50 + (u*400)
    button1.destroy()
    if z == 1 :
        kreuzmalen(1, 0, kuY)
    elif z == 2 :
        kreismalen(11, 10, kiY)
def B2():
    global u, button2
    kuY = 0 + (u*400)
    kiY = 50 + (u*400)
    button2.destroy()
    if z == 1 :
        kreuzmalen(2, 100, kuY)
    elif z == 2 :
        kreismalen(12, 110, kiY)
def B3():
    global u, button3
    kuY = 0 + (u*400)
    kiY = 50 + (u*400)
    button3.destroy()
    if z == 1 :
        kreuzmalen(3, 200, kuY)
    elif z == 2 :
        kreismalen(13, 210, kiY)
def B4():
    global button4, u
    kuY = 100 + (u*400)
    kiY = 150 + (u*400)
    button4.destroy()
    if z == 1 :
        kreuzmalen(4, 0, kuY)
    elif z == 2 :
        kreismalen(14, 10, kiY)
def B5():
    global button5, u
    kuY = 100 + (u*400)
    kiY = 150 + (u*400)
    button5.destroy()
    if z == 1 :
        kreuzmalen(5, 100, kuY)
    elif z == 2 :
        kreismalen(15, 110, kiY)
def B6():
    global button6, u
    kuY = 100 + (u*400)
    kiY = 150 + (u*400)
    button6.destroy()
    if z == 1 :
        kreuzmalen(6, 200, kuY)
    elif z == 2 :
        kreismalen(16, 210, kiY)
def B7():
    global button7, u
    kuY = 200 + (u*400)
    kiY = 250 + (u*400)
    button7.destroy()
    if z == 1 :
        kreuzmalen(7, 0, kuY)
    elif z == 2 :
        kreismalen(17, 10, kiY)
def B8():
    global button8, u
    kuY = 200 + (u*400)
    kiY = 250 + (u*400)
    button8.destroy()
    if z == 1 :
        kreuzmalen(8, 100, kuY)
    elif z == 2 :
        kreismalen(18, 110, kiY)
def B9():
    global button9, u
    kuY = 200 + (u*400)
    kiY = 250 + (u*400)
    button9.destroy()
    if z == 1 :
        kreuzmalen(9, 200, kuY)
    elif z == 2 :
        kreismalen(19, 210, kiY)       
import math
class Schildkroete:
    def __init__(self, zeichenbrett):
        self.__x = 100
        self.__y = 100
        self.__winkel = 0
        self.__bogenmass = 0
    def setX (self, x):
        self.__x=x
    def getX (self):
        return self.__x
    def setY (self, y):
        self.__y=y
    def getY (self):
        return self.__y
    def setWinkel (self,w):
        self.__winkel=w
        self.__bogenmass = math.pi * 2 * self.__winkel / 360
    def getWinkel (self):
        return self.__winkel
    def gehe(self, n):
        dx = n * math.sin (self.__bogenmass)
        dy = n * math.cos (self.__bogenmass)
        xNeu = self.__x + dx
        yNeu = self.__y + dy
        zeichenbrett.create_line(self.__x, self.__y, xNeu, yNeu)
        self.__x = xNeu
        self.__y = yNeu
    def dreheLinks(self, w):
        self.__winkel += w + 360
        self.__winkel = self.__winkel % 360
        self.__bogenmass = math.pi * self.__winkel / 360 * 2
    def dreheRechts(self, w):
        self.__winkel -= w + 360
        self.__winkel = self.__winkel % 360
        self.__bogenmass = math.pi * self.__winkel / 360 * 2
NameSp1 = str(input("Name von Spieler 1:"))
NameSp2 = str(input("Name von Spieler 2:"))
from tkinter import *
fenster = Tk()
zeichenbrett = Canvas(fenster, width = 900, height = 900)
fenster.bind("<MouseWheel>", Mausscroll)
z = 1
g = []
y11 = 10
y12 = 10
y13 = 10
y14 = 110
y15 = 110
y16 = 110
y17 = 210
y18 = 210
y19 = 210
en = 0
PunktzahlSp1 = 0
PunktzahlSp2 = 0
u = -1
q = 1
Buttons(10, 10, 10, 110, 110, 110, 210, 210, 210)
gitterzeichnen(100, 200, 0, 0, 20, 50, 35, 40, 20, 500, 600)
zeichenbrett.pack()
fenster.mainloop()
                

Lösung von: Kevin Kreps (Freiherr-vom-Stein Gymnasium)

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

// Erstellt die GUI
public class windows {

    // Buttonarray das die Buttons für das Spiel beinhaltet
    static JButton[] buttons = new JButton[9];

    // Panelarray das die sich färbenden Panels beinhaltet
    static JPanel[] panels = new JPanel[9];

    // String in dem gespeichert wird, welcher Spieler welche Felder belegt
    static String player1 = "";
    static String player2 = "";

    // Rundenzähler
    static int rounds = 0;

    // Ergebnissausgabe
    static JLabel whowon = new JLabel(" ");

    // Buttons und Panels werden erstellt und Panels erhalten Größe und Farbe
    static void addObjects() {

	int breite = 35;
	int laenge = 10;

	for (int i = 0; i < 9; i++) {
	    buttons[i] = new JButton("");

	    panels[i] = new JPanel(new GridBagLayout());
	    panels[i].setPreferredSize(new Dimension(breite, laenge));
	    panels[i].setMinimumSize(new Dimension(breite, laenge));
	    panels[i].setMaximumSize(new Dimension(breite, laenge));
	    panels[i].setBackground(Color.LIGHT_GRAY);
	}
    }

    // Fügt die Buttons den Panels hinzu
    static void addButtonsToPanels() {
	GridBagConstraints grid = new GridBagConstraints();
	grid.fill = GridBagConstraints.BOTH;
	grid.anchor = GridBagConstraints.CENTER;

	grid.gridx = 0;
	grid.gridy = 0;

	grid.ipadx = 80;
	grid.ipady = 80;

	// Setzt die Koordinaten
	utils.setGBCCords(grid, 0, 0);

	// Platziert die Buttons
	for (int i = 0; i < 9; i++) {
	    panels[i].add(buttons[i], grid);
	}
    }

    // Fügt den Buttons die ActionListener hinzu
    static void addActionListenerToButtons() {
	for (int i = 0; i < 9; i++) {

	    final int o = i;

	    buttons[i].addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent event) {

		    // lässt gedrücken Button verschwinden
		    buttons[o].setVisible(false);

		    // wenn spieler1 dran ist wird das Panel blau und er bekommt
		    // das Feld zugewiesen
		    if (rounds % 2 == 0) {
			panels[o].setBackground(Color.blue);
			player1 = player1 + String.valueOf(o + 1);

			// überprüft ob der Spieler durch den Zug gewonnen hat
			// und setzt, fals er gewonnen hat, die Buttons
			// unsichtbar
			if (rules.gewonnen(player1)) {
			    whowon.setText("Spieler 1 hat gewonnen(blau)");
			    setButtonsUnvisible();
			}
		    }

		    // selbes passiert hier bei Spieler2
		    else {
			panels[o].setBackground(Color.red);
			player2 = player2 + String.valueOf(o + 1);
			if (rules.gewonnen(player2)) {
			    whowon.setText("Spieler 2 hat gewonnen(rot)");
			    setButtonsUnvisible();
			}
		    }

		    // wenn niemand gewonnen hat und die runden 9 stück sind
		    // (rounds 8 da 0 mitgezählt), wird es als unentschieden
		    // gewertet
		    if (rounds == 8 && !rules.gewonnen(player1)
			    && !rules.gewonnen(player2)) {
			whowon.setText("Unentschieden");
		    }

		    // Runden werden nach jedem Zug erhöht
		    rounds++;
		}
	    });
	}
    }

    // Positioniert die Panels auf einem Panel
    static JPanel createFields() {
	GridBagConstraints grid = new GridBagConstraints();
	JPanel panel = new JPanel(new GridBagLayout());

	grid.fill = GridBagConstraints.BOTH;
	grid.anchor = GridBagConstraints.CENTER;

	grid.ipadx = 80;
	grid.ipady = 80;
	grid.insets = new Insets(3, 3, 3, 3);

	int x = 0;
	int y = 0;

	// setzt die Positionen der Panels auf dem Hauptpanel
	for (int i = 0; i < 9; i++) {

	    utils.setGBCCords(grid, x, y);
	    panel.add(panels[i], grid);

	    x++;
	    if (x == 3) {
		x = 0;
		y++;
	    }
	}
	return panel;
    }

    // setzt die Schriftgröße des Ergebnislabels und positioniert es auf einem
    // Panel
    static JPanel createText() {

	JPanel panel = new JPanel();

	whowon.setFont(whowon.getFont().deriveFont(30f));

	panel.add(whowon);
	return panel;
    }

    // Erzeugt den Resettbuttons sammt Funktion und positiniert ihn auf einem
    // Panel
    static JPanel createResett() {
	JPanel panel = new JPanel();
	JButton button = new JButton("Neustart");

	// Buttongröße
	button.setPreferredSize(new Dimension(120, 28));

	whowon.setText(" ");
	panel.add(button);

	// Funktion
	button.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent arg0) {
		resett();
	    }
	});
	return panel;
    }

    // Methode die alle Buttons unsichtbar macht.
    static void setButtonsUnvisible() {
	for (int i = 0; i < 9; i++) {
	    buttons[i].setVisible(false);
	}
    }

    // Methode die alle Werte auf Anfangszustand zurück setzt und alle Buttons
    // sichtbar macht
    static void resett() {
	whowon.setText(" ");
	player1 = "";
	player2 = "";
	rounds = 0;

	// färbt Panels grau und macht Buttons sichtbar
	for (int i = 0; i < 9; i++) {
	    panels[i].setBackground(Color.LIGHT_GRAY);
	    buttons[i].setVisible(true);
	}
    }

    // Panel der alle anderen Panels fasst
    static JPanel createCombinedPanels() {
	JPanel panel = new JPanel(new GridBagLayout());
	GridBagConstraints grid = new GridBagConstraints();

	utils.setGBCCords(grid, 0, 0);
	panel.add(createFields(), grid);

	utils.setGBCCords(grid, 0, 1);
	panel.add(createText(), grid);

	utils.setGBCCords(grid, 0, 2);
	panel.add(createResett(), grid);

	return panel;
    }

    // Erstellt das JFrame
    static JFrame createFrame() {
	// Eigenschaften werden durch Methode aus der Klasse utils gesetzt
	JFrame frame = utils.createJFrame("TicTacToe", 500, 500, false, true);

	frame.add(createCombinedPanels());
	frame.setVisible(true);

	return frame;
    }

    // Hauptmethode
    public static void main(String[] args) {
	// Oberflächenelemente werden erzeugt
	addObjects();
	addButtonsToPanels();
	addActionListenerToButtons();
	// Frame wird erstellt
	createFrame();
    }

    // utilsklasse die Hilfsmethoden bietet
    static class utils {

	// setzt die Koordinaten eines GridBagConstraintsObjekts
	public static void setGBCCords(GridBagConstraints GBCObject, int xcord,
		int ycord) {
	    GBCObject.gridx = xcord;
	    GBCObject.gridy = ycord;
	}

	// Erstellt ein JFrame mit bestimmten Eigenschaften
	public static JFrame createJFrame(final String name, final int xSize,
		final int ySize, final boolean visible,
		final boolean closeIfExit) {
	    JFrame frame = new JFrame(name);

	    frame.setSize(xSize, ySize);

	    frame.setVisible(visible);

	    if (closeIfExit) {
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    }

	    return frame;
	}
    }

    // rulesklasse in der sich die Regeln für das Spiel befinden
    static class rules {

	// Enthällt die Zahlen die die Felder darstellen
	static String[] fields = new String[] { "1", "2", "3", "4", "5", "6",
		"7", "8", "9" };

	// testet ob waagrecht gewonnen wurde
	public static boolean waagrecht(final String player) {
	    boolean won = false;
	    if (player.contains(fields[0]) && player.contains(fields[1])
		    && player.contains(fields[2]) || player.contains(fields[3])
		    && player.contains(fields[4]) && player.contains(fields[5])
		    || player.contains(fields[6]) && player.contains(fields[7])
		    && player.contains(fields[8])) {
		won = true;
	    }
	    return won;
	}

	// testet ob senkrecht gewonnen wurde
	public static boolean senkrecht(final String player) {
	    boolean won = false;
	    if (player.contains(fields[0]) && player.contains(fields[3])
		    && player.contains(fields[6]) || player.contains(fields[1])
		    && player.contains(fields[4]) && player.contains(fields[7])
		    || player.contains(fields[2]) && player.contains(fields[5])
		    && player.contains(fields[8])) {
		won = true;
	    }
	    return won;
	}

	// testet ob diagonal gewonnen wurde
	public static boolean diagonal(final String player) {
	    boolean won = false;
	    if (player.contains(fields[0]) && player.contains(fields[4])
		    && player.contains(fields[8]) || player.contains(fields[2])
		    && player.contains(fields[4]) && player.contains(fields[6])) {
		won = true;
	    }
	    return won;
	}

	// testet durch obige Methoden ob gewonnen wurde
	public static boolean gewonnen(final String player) {
	    boolean won = false;
	    if (waagrecht(player) || senkrecht(player) || diagonal(player)) {
		won = true;
	    }
	    return won;
	}
    }

}

                

Lösung von: Sebastian Littel ()

/**
 * @author philipp gressly freimann. 15. Feb. 2011.
 * CS IL10: Rekursion: Tic Tac Toe
 */

package ch.santis.tic;

import java.awt.Point;
import java.util.ArrayList;

/**
 * Feld: 3x3
 * @author Philipp Gressly (phi AT gressly DOT ch)
 */
public class TicTacToeFeld {
  public static final char PLAYER_X = 'X';
  public static final char PLAYER_O = 'O';
  public static final char NOPLAYER =  0 ;
  
  char [][] feld;
  
  public TicTacToeFeld() {
      feld = new char[3][3];
  }
  
  public char get(int zeile, int spalte) {
      return feld[zeile][spalte];
  }

  public void set(int zeile, int spalte, char player) {
      feld[zeile][spalte] = player;
  }

  public void set(Point move, char spieler) {
     set(move.x, move.y, spieler);  
  }
  
  
  public boolean isFull() {
    int belegt = 0;
    for(int zeile = 0; zeile < 3; zeile ++) {
        for(int spalte = 0; spalte < 3; spalte ++) {
            if(0 != get(zeile, spalte)) {
                belegt = belegt + 1;
            }
        }
    }
    return 9 == belegt; 
  }
  
  final static int [][][] SIEGESREIHEN =
  {
          // Zeilen
          {{0, 0}, {0, 1}, {0, 2}},
          {{1, 0}, {1, 1}, {1, 2}},
          {{2, 0}, {2, 1}, {2, 2}},
          // Spalten
          {{0, 0}, {1, 0}, {2, 0}},
          {{0, 1}, {1, 1}, {2, 1}},
          {{0, 2}, {1, 2}, {2, 2}},
          // Diagonalen
          {{0, 0}, {1, 1}, {2, 2}},
          {{2, 0}, {1, 1}, {0, 2}}
        };
  
  /**
   * isWin() liefert:
   *  - PLAYER_X, falls GewinnPosition für X
   *  - PLAYER_O, falls GewinnPosition für O
   *  - NOPLAYER, sonst
   */
  public char isWin() {
     if(isWin(PLAYER_X)) return PLAYER_X;
     if(isWin(PLAYER_O)) return PLAYER_O;
     return NOPLAYER;
  }
  
  public boolean isWin(char player) {
    for(int[][] siegesReihe : SIEGESREIHEN) {
        if(spielerSiegtAufReihe(siegesReihe, player)) {
            return true;
        }
     }
     return false;
  }
  
  boolean spielerSiegtAufReihe(int[][] reihe, char sp) {
    char p0 = feld[reihe[0][0]][reihe[0][1]];
    char p1 = feld[reihe[1][0]][reihe[1][1]];
    char p2 = feld[reihe[2][0]][reihe[2][1]];
    return p0 == sp && p1 == sp && p2 == sp;
  }
  
  @Override
  public TicTacToeFeld clone() {
    TicTacToeFeld kopie = new TicTacToeFeld();
    for(int zeile = 0; zeile < 3; zeile ++) {
      for (int spalte = 0; spalte < 3; spalte++) {
        kopie.feld[zeile][spalte] = this.feld[zeile][spalte];
      }
    }
    return kopie;
  }
  
  public ArrayList<Point> getAlleZuege() {
    ArrayList<Point> alleZuege;
    alleZuege = new ArrayList<Point>();
    for(int zeile = 0; zeile < 3; zeile ++) {
      for (int spalte = 0; spalte < 3; spalte++) {
        if(NOPLAYER == this.feld[zeile][spalte]){
            alleZuege.add(new Point(zeile, spalte));
        }
      }
    }
    return alleZuege;
  }

  Point randomMove() {
    if(isFull()) return null; // no more moves
    ArrayList<Point> moeglicheZuege;
    moeglicheZuege = getAlleZuege();
    int randomPos = (int) (Math.random()
                            * moeglicheZuege.size());
    return moeglicheZuege.get(randomPos);
  }

  /**
   * Wer ist der gegner?
   */
  char other(char spieler) {
    if(PLAYER_X == spieler) return PLAYER_O;
    if(PLAYER_O == spieler) return PLAYER_X;
    return NOPLAYER;
  }
  
  @Override
  public String toString() {
    String s =  "+-------+";
    for(int zeile = 0; zeile < 3; zeile ++) {
       s = s + "\n|";
       for(int spalte = 0; spalte < 3; spalte ++)
       {
           char v = feld[zeile][spalte];
           if(NOPLAYER != v) {
             s = s + " " + v; 
           } else {
             s = s + "  ";
           }
       }
       s = s + " |";
       if(zeile < 2) {
           s = s + "\n|-------|";
       }
    }
    s = s +  "\n+-------+\n";
    return s;
  }

} // end of class TicTacToeFeld




/**
 * @author philipp gressly freimann. 15. Feb. 2011.
 * CS IL10: Rekursion: Tic Tac Toe
 */ 

package ch.santis.tic;

import java.awt.Point;
import static ch.santis.tic.TicTacToeFeld.*;


public class TestTicTacToe {
  public static void main(String[] args) {
    new TestTicTacToe().top();
  }
  
  void top() {
    // MoveTest
    TicTacToeFeld fld = testFeld();
    TicTacToeFeld neu = fld.clone();
    neu.set(2,1, PLAYER_O);
    System.out.println(fld);
    System.out.println(neu);
    
    // bestTest
    TicTacToeKI ki = new TicTacToeKI();
    Point p;
    p = ki.bestMove(fld, PLAYER_X);
    System.out.println("best Move:" + p);
  }

/**
 * Erzeuge das Testfeld, dafür mussten wir etwas suchen:
 * Das Feld sollte nur noch drei freie Felder haben,
 * darf im 1. Zug nicht sofort beendet sein und muss alle drei
 * Ausgänge (Sieg X, Sieg O und unentschieden zulassen:
 * 
 *    XO.
 *    OOX
 *    X..
 */
  TicTacToeFeld testFeld() {
    TicTacToeFeld feld = new TicTacToeFeld();
    feld.set(0, 0, PLAYER_X);
    feld.set(0, 1, PLAYER_O); 
    feld.set(0, 2, NOPLAYER);
    feld.set(1, 0, PLAYER_O);
    feld.set(1, 1, PLAYER_O); 
    feld.set(1, 2, PLAYER_X);
    feld.set(2, 0, PLAYER_X);
    feld.set(2, 1, NOPLAYER); 
    feld.set(2, 2, NOPLAYER);
    return feld;
  }

}  // end of class TestTicTacToe



/**
 * @author philipp gressly freimann. 15. Feb. 2011.
 * CS IL10: Rekursion: Tic Tac Toe
 */

package ch.santis.tic;

import java.awt.Point;
import static ch.santis.tic.TicTacToeFeld.*;

public class TicTacToeKI {
  public Point bestMove(TicTacToeFeld feld, char spieler) {
    int bestWert  = -1;
    Point bestMove = null;
    for(Point move: feld.getAlleZuege()) {
       TicTacToeFeld tempFeld = feld.clone();
       tempFeld.set(move, spieler);
       int aktWert = bewerte(tempFeld, spieler, false);
       if(aktWert > bestWert) {
           bestWert = aktWert;
           bestMove = move;
       }
    }
    if(null == bestMove) {
        return feld.randomMove();
    }
    return bestMove;
  }

/**
 * Bewerte rekursiv ein TicTacToe-Feld.
 * @param feld
 * @param spieler    Für diesen Spieler wird
 *                   bewertet.
 * @param maximieren Es handelt sich um einen
 *                   Maximierungsschritt
 * @return Wert der Postition "feld" für den
 *         Spieler "spieler"
 */
  int bewerte(TicTacToeFeld feld, char spieler, boolean maximieren) {
    if(feld.isWin(PLAYER_X)) {
      if(PLAYER_X == spieler) {
        return  1; 
      } else {
        return -1;
      }
    }
    if(feld.isWin(PLAYER_O)) {
      if(PLAYER_O == spieler) {
        return  1; 
      } else {
        return -1;
      } 
    }
    if(feld.isFull()) {
      return 0; 
    }
    
    // Rekursionsschritt
    int bestWert;
    if(maximieren) { // Maximierungsschritt?
        bestWert = -2;
    } else {
        bestWert =  2;
    }
    for(Point move: feld.getAlleZuege()) {
      TicTacToeFeld tempFld = feld.clone();
      char zieher = maximieren ?
                    spieler    :
                    feld.other(spieler);
      tempFld.set(move, zieher);
      int aktWert = bewerte(tempFld, spieler, !maximieren);
      if(maximieren) {
          if(aktWert > bestWert) {
              bestWert = aktWert;
          }
      } else { // minimieren 
          if(aktWert < bestWert) {
              bestWert = aktWert;
          }
      }
    }
    return bestWert;
  } //bewerte
    
} // end of class TicTacToeKI



/**
 * @author philipp gressly freimann. 15. Feb. 2011.
 * CS IL10: Rekursion: Tic Tac Toe
 */ 


package ch.santis.tic.gui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

// project specific
import ch.santis.tic.TicTacToeFeld;
import static ch.santis.tic.TicTacToeFeld.*;
import ch.santis.tic.TicTacToeKI;

public class TicGui extends JFrame implements ActionListener {
    JButton[][]   buttons  = new JButton[3][3];

    TicTacToeFeld fld      = new TicTacToeFeld();
    TicTacToeKI   ki       = new TicTacToeKI();

    public static void main(String[] args) {
        new TicGui();
    }

    public TicGui(){
        super("TicTacToe");
        JPanel mp = new JPanel();
        makeButtons(mp);
        mp.setLayout(new GridLayout(3, 3));
        add(mp);
        setSize(180, 180);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    void makeButtons(JPanel mp) {
        for (int zeile = 0; zeile < 3; zeile++) {
            for (int spalte = 0; spalte < 3; spalte++) {
                JButton b = new JButton(".");
                buttons[zeile][spalte] = b;
                mp.add(b);
                b.addActionListener(this);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton src = (JButton) e.getSource();
        movePlayerThenKI(src);
        redrawAll();
    }

    private void movePlayerThenKI(JButton src) {
        for (int zeile = 0; zeile < 3; zeile++) {
            for (int spalte = 0; spalte < 3; spalte++) {
                behandleGeklicktenButton(src, zeile, spalte);
            } // end for spalte
        } // end for zeile
    } // movePlayerThenKI()

  
    private void behandleGeklicktenButton(JButton src, int zeile, int spalte) {
        // war das nicht der geklickte?
        if (buttons[zeile][spalte] != src) {
            return;
        }
        fld.set(zeile, spalte, PLAYER_O);
        if (fld.isWin(PLAYER_O)) {
            JOptionPane.showMessageDialog(this, "Mensch siegt!!");
        }
        if (!fld.isFull()) {
            Point p = ki.bestMove(fld, PLAYER_X);
            fld.set(p, PLAYER_X);
            if (fld.isWin(PLAYER_X)) {
                redrawAll();
                JOptionPane.showMessageDialog(this, "MiniMax siegt!!");
            }

        }

    } // end behandleGeklicktenButton()

    void redrawAll() {
        for (int zeile = 0; zeile < 3; zeile++) {
            for (int spalte = 0; spalte < 3; spalte++) {
                JButton b = buttons[zeile][spalte];
                if (NOPLAYER != fld.get(zeile, spalte)) {
                    b.setText("" + fld.get(zeile, spalte));
                    b.setEnabled(false);
                }
            }
        }
    } // end redrawAll
    
} // end of class TicGui



                

Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

#!/usr/bin/python3

from random import randint
from time import sleep
from tkinter import *

class game:
    def __init__(s):
        s.counter = 0
        s.brett = [['' for i in range(3)] for i in range(3)]
        s.over = False
        s.q = randint(0,1)  
        s.lastmove = ()
        s.moveZuNr = { ab : i+4 for i,ab in enumerate([(a,b) for a in range(1,4) for b in range(1,4)])}     
        s.gui = gui(s)
        s.gui.guistart()
        
    def getMove(s,move):
        s.lastmove = move
        s.brett[move[0]-1][move[1]-1] = 'X' if s.counter%2 == 0 else 'O'
        s.counter+=1
        if s.finished():
            s.gui.siegesparade(s.winner)
            return
        if  s.modus == 'K' and s.counter % 2 == s.q:
            s.ki_move()
    
    def finished(s):
        f = range(3)         
        F = [[(a,b) for a in f] for b in f]+[[(b,a) for a in f] for b in f]+[[(b,a) for a in f for b in f if a==b]]+[[(b,a) for a in f for b in f if a+b==2]]
        for a in F:
            fin = []
            for b in a:
                if s.brett[b[0]][b[1]]!='':
                    fin.append(s.brett[b[0]][b[1]])
               
                if len(fin)==3 and len(set(fin))==1: 
                    s.winner = a
                    s.over=True
                    return True
        if s.counter == 9:
            s.winner = []
            s.over = True;return True
        return False
            
    def modus(s,mode):
        s.modus = mode
        if mode == 'K':
            s.ki = ticki()
            if s.q == 0: 
                s.ki_move()
        return
    
    def ki_move(s):
        s.gui.c.unbind("<Button-1>")
        s.ki.receiveMove(s.lastmove)
        move = s.ki.calculateMove()
        s.gui.makeMove(move,s.moveZuNr[move])
        s.gui.c.bind("<Button-1>",s.gui.clicked)
                
class ticki:
    
    def __init__(s):
        s.board = [['' for i in range(3)] for i in range(3)]
        s.count = 0
        s.symb = 'O' 
        s.human = 'X'
     
    def calculateMove(s):
        if s.couldfinish(s.symb):
            move = s.couldfinish(s.symb)
        elif s.couldfinish(s.human):
            move =  s.couldfinish(s.human)
        elif s.board[0][0] == '':
            move = (1,1)
        elif s.board[0][2] == '':
            move = (1,3)
        elif s.board[2][0] == '':
            move = (3,1)
        elif s.board[2][2] == '':
            move = (3,3)
        elif s.board[1][1] == '':
            move = (2,2)
        else:
            free = [(1,2),(2,3),(2,1),(3,2)]
            for a in free:
                if s.board[a[0]][a[1]] == '':
                    move = a
                    break
        s.receiveMove(move)
        return move
    
    def couldfinish(s,who):
        f = range(3)         
        F = [[(a,b) for a in f] for b in f]+[[(b,a) for a in f] for b in f]+[[(b,a) for a in f for b in f if a==b]]+[[(b,a) for a in f for b in f if a+b==2]]
        for a in F:
            fin = []
            for b in a:
                if s.board[b[0]][b[1]] == who:
                    fin.append(b)
                    move = [i for i in a if i not in fin ]
                if len(fin) == 2 and s.board[move[0][0]][move[0][1]] == '':
                    return (move[0][0]+1,move[0][1]+1)                    
                    
        return False
            
    def receiveMove(s, move):
        if move == ():
            s.symb = 'X'
            s.human = 'O'
            return   
        s.board[move[0]-1][move[1]-1] = 'X' if s.count%2 == 0 else 'O'
        s.count+=1  
        
class gui:
    
    def __init__(s,Game):
        s.game = Game
        s.felder = {}
        s.pos = sorted([(100+100*a,100+100*b) for a in range(3)\
					for b in range(3)], key = lambda x : x[1])
    def guistart(s): 
        tk=Tk()
        s.c = Canvas(tk, width = 400, height = 400, bg = 'black')
        tk.title('Tic Tac Toe')
        s.c.bind("<Button-1>", s.clicked)
        s.c.pack()
        s.pre_gui()
        tk.mainloop()
    
    def pre_gui(s):
        s.c.create_text(100,130,anchor = 'nw',
                        text = 'Mensch vs Mensch',fill = 'white', tag = 'vsM') 
        s.c.create_text(200,250,anchor = 'nw',
                        text = 'Mensch vs KI', fill = 'white', tag = 'vsK') 
 
    def draw_board(s):
        s.c.delete('vsK','vsM')
        s.c.create_text(5, 400 , anchor = 'sw', text = 'Neues Spiel',
                        tag = 'new', fill = 'white', activefill = 'grey')
   
        ky = 50                   #x-Koordinate
        for x in range(1,4):
            kx = 50              #y-Koordinate
            for y in range(1,4):
                tem = s.c.create_polygon(kx, ky, kx+100, ky, kx+100, ky+100, kx, ky+100,
                                         fill = '' , outline = 'white', width = 2, tag = 'feld')
                
                s.felder[tem] = Feld(tem,(x,y))                         
                kx+=100
            ky+=100
    
    def clicked(s, event):
        try:
            click = s.c.find_withtag(CURRENT)[0]
            tag   = s.c.gettags(click)[0]
        except:
            return
        
        if tag[0][0] == 'v':
            s.draw_board()
            s.game.modus(tag[2])
            
        elif tag == 'new':
            s.clear_game()        
        
        elif (tag == 'feld' and s.felder[click].frei == False) or s.game.over==True:
            return  
        
        elif tag == 'feld':
            s.makeMove(s.felder[click].pos,click)
   
    def clear_game(s):
        s.game.over = False        
        for a in s.felder.values():
            a.frei = True
            s.c.itemconfig(a.nr, fill = '')
        s.c.delete('mark')
        s.game.counter = 0
        s.game.lastmove = ()
        s.game.brett = [['' for i in range(3)] for i in range(3)]
        if s.game.modus == 'K': 
            s.game.q = randint(0,1)
            s.game.ki.board = [['' for i in range(3)] for i in range(3)]
            s.game.ki.count = 0
            if s.game.q == 0:
                s.game.symb = 'X'
                s.game.human = 'O'
                s.game.ki_move()
            else:
                s.game.symb = 'O'
                s.game.human = 'X'
        
    def makeMove(s,move,nr):
        s.felder[nr].frei = False
        txt = 'X' if s.game.counter%2 == 0 else 'O'
        s.c.create_text(s.pos[nr-4][0], s.pos[nr-4][1], fill = 'white',
                        text = txt, font = 1000, tag = 'mark')
        s.c.update()
        s.game.getMove(move)  
        
    def siegesparade(s,sieger):  
        sieger = sorted([a for a in s.felder.values() if (a.pos[0]-1,a.pos[1]-1) in sieger], key = lambda x: x.frei)
        for a in sieger:
            s.c.itemconfig(a.nr,fill='blue')
            sleep(0.35)
            s.c.update()        

class Feld: 
    def __init__(s,nummer,position):
        s.nr = nummer
        s.pos = position
        s.frei = True      

game = game()
                

Lösung von: rob ert (tub)

class SpielRegeln
    {
        public int Choice { get; set; }
        public int Count { get; set; }
        public int Turn { get; set; }
        public bool CorrectInput { get; set; }
        public bool WinFlag { get; set; }
        public int Score1 { get; set; }
        public int Score2 { get; set; }
        public bool Playing { get; set; }
        public string Player1 { get; set; }
        public string Player2 { get; set; }

        public string[] pos = new string[10] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        public void Welcome()
        {
            Turn = 1;
            Console.WriteLine("Hello! This is Tic Tac Toe. If you don't know the rules then stop being an idiot.");
            Console.WriteLine("What is the name of player 1?");
            Player1 = Console.ReadLine();
            Console.WriteLine("Very good. What is the name of player 2?");
            Player2 = Console.ReadLine();
            Console.WriteLine("Okay good. {0} is O and {1} is X.", Player1, Player2);
            Console.WriteLine("{0} goes first.", Player1);
            Console.ReadLine();
            Console.Clear();
        }
        public void DrawBoard()
        {

            Console.WriteLine("   {0}  |  {1}  |  {2}   ", pos[1], pos[2], pos[3]);
            Console.WriteLine("-------------------");
            Console.WriteLine("   {0}  |  {1}  |  {2}   ", pos[4], pos[5], pos[6]);
            Console.WriteLine("-------------------");
            Console.WriteLine("   {0}  |  {1}  |  {2}   ", pos[7], pos[8], pos[9]);
        }
        public void Input()
        {

            CorrectInput = false;



            while (CorrectInput == false)
            {

                Console.WriteLine("Which position would you like to take?");
                Choice = int.Parse(Console.ReadLine());
                Count++;

                if (Choice > 0 && Choice < 10)
                {
                    CorrectInput = true;
                }
                else
                {
                    continue;
                }
            }
            CorrectInput = false;

        }
        public bool CheckWin()
        {
            if (pos[1] == "O" && pos[2] == "O" && pos[3] == "O") // Horizontal ----------------------------------------
            {
                return true;
            }
            else if (pos[4] == "O" && pos[5] == "O" && pos[6] == "O")
            {
                return true;
            }
            else if (pos[7] == "O" && pos[8] == "O" && pos[9] == "O")
            {
                return true;
            }

            else if (pos[1] == "O" && pos[5] == "O" && pos[9] == "O") // Diagonal -----------------------------------------
            {
                return true;
            }
            else if (pos[7] == "O" && pos[5] == "O" && pos[3] == "O")
            {
                return true;
            }

            else if (pos[1] == "O" && pos[4] == "O" && pos[7] == "O")// Coloumns ------------------------------------------
            {
                return true;
            }
            else if (pos[2] == "O" && pos[5] == "O" && pos[8] == "O")
            {
                return true;
            }
            else if (pos[3] == "O" && pos[6] == "O" && pos[9] == "O")
            {
                return true;
            }

            if (pos[1] == "X" && pos[2] == "X" && pos[3] == "X") // Horizontal ----------------------------------------
            {
                return true;
            }
            else if (pos[4] == "X" && pos[5] == "X" && pos[6] == "X")
            {
                return true;
            }
            else if (pos[7] == "X" && pos[8] == "X" && pos[9] == "X")
            {
                return true;
            }

            else if (pos[1] == "X" && pos[5] == "X" && pos[9] == "X") // Diagonal -----------------------------------------
            {
                return true;
            }
            else if (pos[7] == "X" && pos[5] == "X" && pos[3] == "X")
            {
                return true;
            }

            else if (pos[1] == "X" && pos[4] == "X" && pos[7] == "X") // Coloumns ------------------------------------------
            {
                return true;
            }
            else if (pos[2] == "X" && pos[5] == "X" && pos[8] == "X")
            {
                return true;
            }
            else if (pos[3] == "X" && pos[6] == "X" && pos[9] == "X")
            {
                return true;
            }
            else // No winner ----------------------------------------------
            {
                return false;
            }
        }
        public void PositionTaken()
        {                        
            if (Turn == 1)
            {
                if (pos[Choice] == "X" || pos[Choice] == "O") // Checks to see if spot is taken already --------------------
                {
                    Console.WriteLine("You can't steal positions asshole! ");
                    Console.Write("Try again.");
                    Console.ReadLine();
                    Console.Clear();

                }
                else
                {
                    pos[Choice] = "O";
                }
            }
            if (Turn == 2)
            {
                if (pos[Choice] == "O" || pos[Choice] == "X") // Checks to see if spot is taken already -------------------
                {
                    Console.WriteLine("You can't steal positions asshole! ");
                    Console.Write("Try again.");
                    Console.ReadLine();
                    Console.Clear();

                }
                else
                {
                    pos[Choice] = "X";
                }
            }
        }
        public void PlayerChange()
        {
            WinFlag = CheckWin();


            if (WinFlag == false && Count < 9)
            {
                if (Turn == 1)
                {
                    Turn = 2;
                }
                else if (Turn == 2)
                {
                    Turn = 1;
                }
                Console.Clear();
            }
        }
        public void SomeOneWon()
        {

            Score1 = 0;
            Score2 = 0;
            if (WinFlag == true) // Someone won -----------------------------
            {
                if (Turn == 1)
                {
                    Score1++;
                    Console.WriteLine("{0} wins!", Player1);
                    Console.WriteLine("What would you like to do now?");
                    Console.WriteLine("1. Play again");
                    Console.WriteLine("2. Leave");

                    while (CorrectInput == false)
                    {
                        Console.WriteLine("Enter your option: ");
                        Choice = int.Parse(Console.ReadLine());

                        if (Choice > 0 && Choice < 3)
                        {
                            CorrectInput = true;
                        }
                        else { Console.WriteLine("falsche Eingabe"); }
                    }

                    CorrectInput = false; // Reset --------------

                    switch (Choice)
                    {
                        case 1:
                            Console.Clear();
                            WinFlag = false;
                            break;
                        case 2:
                            Console.Clear();
                            Console.WriteLine("Thanks for playing!");
                            Console.ReadLine();
                            Count = 10;
                            break;
                    }
                }

                if (Turn == 2)
                {
                    Score2++;
                    Console.WriteLine("{0} wins!", Player2);
                    Console.WriteLine("What would you like to do now?");
                    Console.WriteLine("1. Play again");
                    Console.WriteLine("2. Leave");

                    while (CorrectInput == false)
                    {
                        Console.WriteLine("Enter your option: ");
                        Choice = int.Parse(Console.ReadLine());

                        if (Choice > 0 && Choice < 3)
                        {
                            CorrectInput = true;
                        }
                    }

                    CorrectInput = false; // Reset -----------------

                    switch (Choice)
                    {
                        case 1:
                            Console.Clear();
                            WinFlag = false;
                            break;
                        case 2:
                            Console.Clear();
                            Console.WriteLine("Thanks for playing!");
                            Console.ReadLine();
                            Playing = false;
                            break;
                    }
                }
            }
        }
        public void NoOneWon()
        {

            if (WinFlag == false) // No one won ---------------------------
            {
                Console.WriteLine("It's a draw!");
                Console.WriteLine("Score: {0} - {1}     {2} - {3}", Player1, Score1, Player2, Score2);
                Console.WriteLine("");
                Console.WriteLine("What would you like to do now?");
                Console.WriteLine("1. Play again");
                Console.WriteLine("2. Leave");
                Console.WriteLine("");


                while (CorrectInput == false)
                {
                    Console.WriteLine("Enter your option: ");
                    Choice = int.Parse(Console.ReadLine());
                    if (Choice > 0 && Choice < 3)
                    {
                        CorrectInput = true;
                    }

                }

                CorrectInput = false; // Reset -------------

                switch (Choice)
                {
                    case 1:
                        Console.Clear();
                        WinFlag = false;
                        break;


                    case 2:
                        Console.Clear();
                        Console.WriteLine("Thanks for playing!");
                        Console.ReadLine();
                        Count = 10;
                        break;
                }
            }
        }
        public void BoardReset()
        {

            for (int i = 1; i < 10; i++) // Resets board ------------------------
            {
                pos[i] = i.ToString();
            }
        }

    }
 ----------------------------------------------------------------------------------------- --
static void Main(string[] args)
        {
            SpielRegeln ob = new SpielRegeln();
            ob.Welcome();
            ob.DrawBoard();

            while (ob.Count <= 9)
            {

                ob.Input();
                ob.PositionTaken();
                ob.PlayerChange();
                ob.DrawBoard();

                if (ob.WinFlag == true)
                {
                    ob.SomeOneWon();
                    if (ob.Choice == 1)
                    {
                        ob.Count = 0;
                        ob.BoardReset();
                        ob.Welcome();
                        ob.DrawBoard();
                    }
                    else
                    {
                        ob.Count = 10;
                        break;
                    }
                }
                if (ob.WinFlag == false && ob.Count > 8)
                {
                    ob.NoOneWon();

                    if (ob.Choice == 1)
                    {
                        ob.Count = 0;
                        ob.BoardReset();
                        ob.Welcome();
                        ob.DrawBoard();
                    }
                    else
                    {
                        ob.Count = 10;
                        break;
                    }
                }



            }
        }

                

Lösung von: Name nicht veröffentlicht

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 6
Schwierigkeit: Schwer
Webcode: wm7t-zm5z
Autor: ()

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen