〇✕ I made a game

Motivation

When I was little, there was a time when it was my boom to play a game called tic-tac-toe with my friends in a short time. So I decided to make it this time.


Execution result

Screenshot (39) .png


Contents

Make screens and buttons

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

squares = 3

class TictacApp(ttk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.create_widgets()
        self.set_value()

    def create_widgets(self):
        for i in range(squares):
            for j in range(squares):
                button = ttk.Button(self, command=self.record(i, j))
                button.bind('<Button-1>', self.mark)
                button.grid(column=i, row=j, sticky=(N, S, E, W))

        for i in range(squares):
            self.columnconfigure(i, weight=1)
            self.rowconfigure(i, weight=1)

        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(0, weight=1)

        self.grid(column=0, row=0, sticky=(N, S, E, W))


def main():
    root = Tk()
    root.title('〇✕ Game')
    TictapApp(root)
    root.mainloop()


if __name__ == '__main__':
    main()

〇 and ✕ are displayed

def mark(self, event):
        if not event.widget['text']:
            if self.player == 1:
                event.widget['text'] = str('〇')
            else:
                event.widget['text'] = str('×')


Remember the button you pressed


def record(self, i, j):
        def x():
            if not self.field[i][j]:
                self.field[i][j] = self.player
                self.line_check()
                self.change_player()
                self.clear()
        return x

    def set_value(self):
        self.player = 1
        self.field = []
        for i in range(squares):
            self.field.append(['' for i in range(squares)])
        self.finish = 0


Judgment whether the third line is lined up

    def line_check(self):
        cross = 0
        for i in range(squares):
            horizon = 0
            vertical = 0
            for j in range(squares):
                if self.field[i][j] == self.player:
                    horizon += 1
                if self.field[j][i] == self.player:
                    vertical += 1
            if self.field[i][i] == self.player:
                cross += 1
            if horizon == 3 or vertical == 3 or cross == 3:
                self.game_end()
        if self.field[0][2] == self.field[1][1] == self.field[2][0] == self.player:
            self.game_end()

Inform the victory or defeat

   def game_end(self):
        if self.player == 1:
            messagebox.showinfo('Congrats!', 'Leading victory')
        else:
            messagebox.showinfo('Congrats!', 'Second strike victory')
        self.finish = 1

If you can't settle

    def change_player(self):
        if self.finish == 0:
            self.player = -self.player

    def clear(self):
        if self.finish == 1:
            self.create_widgets()
            self.set_value()

Source code

from tkinter import *
from tkinter import ttk
from tkinter import messagebox

squares = 3


class TictacApp(ttk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.create_widgets()
        self.set_value()

    def set_value(self):
        self.player = 1
        self.field = []
        for i in range(squares):
            self.field.append(['' for i in range(squares)])
        self.finish = 0

    def create_widgets(self):
        for i in range(squares):
            for j in range(squares):
                button = ttk.Button(self, command=self.record(i, j))
                button.bind('<Button-1>', self.mark)
                button.grid(column=i, row=j, sticky=(N, S, E, W))

        for i in range(squares):
            self.columnconfigure(i, weight=1)
            self.rowconfigure(i, weight=1)

        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(0, weight=1)

        self.grid(column=0, row=0, sticky=(N, S, E, W))

    def mark(self, event):
        if not event.widget['text']:
            if self.player == 1:
                event.widget['text'] = str('〇')
            else:
                event.widget['text'] = str('×')

    def record(self, i, j):
        def x():
            if not self.field[i][j]:
                self.field[i][j] = self.player
                self.line_check()
                self.change_player()
                self.clear()
        return x

    def change_player(self):
        if self.finish == 0:
            self.player = -self.player

    def line_check(self):
        cross = 0
        for i in range(squares):
            horizon = 0
            vertical = 0
            for j in range(squares):
                if self.field[i][j] == self.player:
                    horizon += 1
                if self.field[j][i] == self.player:
                    vertical += 1
            if self.field[i][i] == self.player:
                cross += 1
            if horizon == 3 or vertical == 3 or cross == 3:
                self.game_end()
        if self.field[0][2] == self.field[1][1] == self.field[2][0] == self.player:
            self.game_end()

    def game_end(self):
        if self.player == 1:
            messagebox.showinfo('Congrats!', 'Leading victory')
        else:
            messagebox.showinfo('Congrats!', 'Second strike victory')
        self.finish = 1

    def clear(self):
        if self.finish == 1:
            self.create_widgets()
            self.set_value()


def main():
    root = Tk()
    root.title('OX game')
    TictacApp(root)
    root.mainloop()


if __name__ == '__main__':
    main()

Impressions I made

While looking at "I tried to make GUI tic-tac-toe with Python and Tkinter" that I referred to this time, I wrote the program while checking what I was doing. 〇✕ I had a lot of trouble just making a game. Also, this time there was something I was able to refer to, but I thought it would be very difficult to make it from scratch. From now on, I decided to study so that I could make it from scratch by myself.


References

--I tried to make GUI tic-tac-toe with Python and Tkinter

https://qiita.com/TN0321/items/d0ba918eefa5d9c7e587

--The easiest Python introductory class book Fumitaka Osawa [Author]

Recommended Posts

〇✕ I made a game
I made a life game with Numpy
I made a roguelike game with Python
I made a python text
I made a discord bot
I made a bin picking game with Python
I made a Christmas tree lighting game with Python
I made a vim learning game "PacVim" with Go
I made a school festival introduction game using Ren’py
I made a falling block game with Sense HAT
I made a C ++ learning site
I made a Line-bot using Python!
I made a CUI-based translation script (2)
I made a wikipedia gacha bot
I made a fortune with Python.
I made a CUI-based translation script
Zura made like a life game
I made a daemon with Python
I made a simple typing game with tkinter in Python
I made a Numer0n battle game in Java (I also made AI)
I made a puzzle game (like) with Tkinter in Python
I made a dash docset for Holoviews
I made a payroll program in Python!
I touched "Orator" so I made a note
I made a character counter with Python
I tried playing a ○ ✕ game using TensorFlow
Beginner: I made a launcher using dictionary
I made a conversation partner like Siri
I made a script to display emoji
I made a Hex map with Python
I made a stamp generator with GAN
I made a browser automatic stamping tool.
After studying Python3, I made a Slackbot
I made a simple blackjack with Python
I made a configuration file with Python
I made a library for actuarial science
I made a WEB application with Django
I made a neuron simulator with Python
I made a game called Battle Ship using pygame and tkinter
I made a poker game server chat-holdem using websocket with python
Make a squash game
I made a stamp substitute bot with line
I made a python dictionary file for Neocomplete
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I made a spare2 cheaper algorithm for uWSGI
I made a useful tool for Digital Ocean
I made a GUI application with Python + PyQt5
I tried playing a typing game in Python
I made a Twitter fujoshi blocker with Python ①
I want to make a game with Python
I made a crazy thing called typed tuple
[Python] I made a Youtube Downloader with Tkinter.
I made a router config collection tool Config Collecor
I made a simple Bitcoin wallet with pycoin
I made a downloader for word distributed expression
I made a LINE Bot with Serverless Framework!
I made a tool to compile Hy natively
I got a sqlite3.OperationalError
I made an Ansible-installer
I made a tool to get new articles