# this project is licensed under the WTFPLv2, see COPYING.txt for details

import logging
import os

from PyQt5.QtCore import QProcess

from eye.qt import Signal, Slot

__all__ = ('find_command', 'LineProcess', 'run_blocking')

LOGGER = logging.getLogger(__name__)

def find_command(cmd):
	"""Find `cmd` in `$PATH`"""
	for elem in os.getenv('PATH').split(os.pathsep):
		path = os.path.join(elem, cmd)
		if os.path.isfile(path):
			return path

class LineProcess(QProcess):
	"""Process with stdout/stderr line handling

	The process is run in background. Signals are emitted when full lines are read from stdout or stderr.
	"""

	stdout_line_read = Signal(str)

	"""Signal stdout_line_read(str)"""

	stderr_line_read = Signal(str)

	"""Signal stderr_line_read(str)"""

	def __init__(self, **kwargs):
		super().__init__(**kwargs)
		self.bufs = [b'', b'']
		self.encoding = 'utf-8'
		self.linesep = b'\n'

		self.readyReadStandardError.connect(self.on_stderr)
		self.readyReadStandardOutput.connect(self.on_stdout)
		self.stateChanged.connect(self.on_state_changed)
		self.finished.connect(self.on_finish)
		self.errorOccurred.connect(self.on_error)

	def stop(self, wait=0):
		"""Terminate process"""
		if wait and self.state() != self.NotRunning:
			self.terminate()
			self.waitForFinished(wait)
		if self.state() != self.NotRunning:
			self.kill()

	@Slot(QProcess.ProcessState)
	def on_state_changed(self, state):
		if state == self.Starting:
			cmd = [self.program()] + self.arguments()
			LOGGER.debug('starting process %r', cmd)

	def set_encoding(self, encoding):
		"""Set encoding for reading stdout/stderr"""
		self.encoding = encoding

	def _perform(self, fd, incoming, sig):
		# TODO decode before searching newline?
		self.bufs[fd] += bytes(incoming)
		while b'\n' in self.bufs[fd]:
			line, self.bufs[fd] = self.bufs[fd].split(self.linesep, 1)
			sig.emit(line.decode(self.encoding))

	@Slot()
	def on_stdout(self):
		self._perform(0, self.readAllStandardOutput(), self.stdout_line_read)

	@Slot()
	def on_stderr(self):
		self._perform(1, self.readAllStandardError(), self.stderr_line_read)

	@Slot()
	def on_error(self):
		cmd = [self.program()] + self.arguments()
		LOGGER.warning('error when running %r: %s', cmd, self.errorString())

	@Slot(int)
	def on_finish(self, ret):
		if ret != 0:
			cmd = [self.program()] + self.arguments()
			LOGGER.info('command %r exited with code %r', cmd, ret)

class ReadingProcess(QProcess):
	def __init__(self, **kwargs):
		super().__init__(**kwargs)
		self.stdin = b''
		self.buf = []

		self.started.connect(self.on_started)
		self.bytesWritten.connect(self.on_started)
		self.readyReadStandardOutput.connect(self.on_stdout)

	@Slot()
	def on_started(self, _=None):
		while True:
			written = self.write(self.stdin)
			if written < 0:
				LOGGER.warning('error writing data to stdin for command %r', self.arguments())
				return
			elif written == 0:
				break
			self.stdin = self.stdin[written:]
		if not self.stdin:
			self.closeWriteChannel()

	@Slot()
	def on_stdout(self):
		while self.bytesAvailable() > 0:
			self.buf.append(self.read(self.bytesAvailable()))

	def set_standard_input(self, data):
		self.stdin = data

	def get_buffer(self):
		return b''.join(self.buf)

def run_blocking(cmd, stdin=b'', cwd=''):
	proc = ReadingProcess()
	if stdin:
		proc.set_standard_input(stdin)
	if cwd:
		proc.setWorkingDirectory(cwd)

	proc.start(cmd[0], cmd[1:])
	proc.waitForFinished(-1)
	return proc.exitCode(), proc.get_buffer()


import pygame
import pygame_gui
from pygame_gui.core import ObjectID

pygame.init()
SIZE = WIDTH, HEIGHT = 600, 600
screen = pygame.display.set_mode(SIZE)
FPS = 60
clock = pygame.time.Clock()

class MapCreator:
    def __init__(self):
        self.arcade_font = pygame.font.Font('data/fonts/arcade-n.ttf', 10)
        self.arcade_font_small = pygame.font.Font('data/fonts/arcade-n.ttf',
                                                  8)
        self.map_edit_manager = pygame_gui.UIManager((600, 600),
                                                     'data/theme.json')

        self.text = self.arcade_font.render('Here you can create your own '
                                            'map', 1, (0, 0, 0))
        self.small_text = self.arcade_font_small.render('map name', 1,
                                                        (60, 60, 60))

        self.action = 'SET_CLEAR'

        self.create_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((460, 55), (120, 25)),
            text='Create map',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#create_button'))

        self.eraser_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((320, 50), (35, 35)),
            text='',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#eraser_button'))

        self.text_input = pygame_gui.elements.UITextEntryLine(
            relative_rect=pygame.Rect((360, 55), (90, 30)),
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#map_name_text_box'))

        self.text_input.set_text_length_limit(10)

        self.player_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((20, 50), (35, 35)),
            text='',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#player_button'))

        self.tile_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((70, 50), (35, 35)),
            text='',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#tile_button'))

        self.blue_ghost_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((120, 50), (35, 35)),
            text='',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#blue_ghost_button'))

        self.red_ghost_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((170, 50), (35, 35)),
            text='',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#red_ghost_button'))

        self.yellow_ghost_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((220, 50), (35, 35)),
            text='',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#yellow_ghost_button'))

        self.green_ghost_button = pygame_gui.elements.UIButton(
            relative_rect=pygame.Rect((270, 50), (35, 35)),
            text='',
            manager=self.map_edit_manager,
            object_id=ObjectID(class_id='@map_creator_screen',
                               object_id='#green_ghost_button'))

    def run(self):
        board = Board(30, 30, 50, 100)
        running = True
        while running:
            screen.fill(pygame.Color(175, 238, 238))
            screen.blit(self.text, (145, 10))
            screen.blit(self.small_text, (370, 46))

            events = pygame.event.get()
            for event in events:

                if event.type == pygame.QUIT:
                    running = False
                if pygame.mouse.get_pressed()[0] and board.pos_on_board(
                        pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]):
                    try:
                        board.on_click(board.get_cell(event.pos), self.action)
                    except AttributeError:
                        pass
                    else:
                        board.render(screen)
                        pygame.display.flip()
                if event.type == pygame.KEYDOWN and event.key \
                        == pygame.K_DELETE:
                    board.clear()

                elif event.type == pygame_gui.UI_BUTTON_PRESSED:

                    if event.ui_element == self.tile_button:
                        self.action = 'SET_TILE'
                    elif event.ui_element == self.eraser_button:
                        self.action = 'SET_CLEAR'
                    elif event.ui_element == self.player_button:
                        self.action = 'SET_PLAYER'
                    elif event.ui_element == self.red_ghost_button:
                        self.action = 'SET_RED'
                    elif event.ui_element == self.green_ghost_button:
                        self.action = 'SET_GREEN'
                    elif event.ui_element == self.blue_ghost_button:
                        self.action = 'SET_BLUE'
                    elif event.ui_element == self.yellow_ghost_button:
                        self.action = 'SET_YELLOW'
                    elif event.ui_element == self.create_button:
                        if self.text_input.get_text() != '' \
                                and board.enemy_list != []:

                            file_map = open(
                                'data/maps/' + self.text_input.get_text() +
                                '.txt', 'w+')
                            brd = board.board.copy()

                            while set(brd[0]) == {0}:
                                del brd[0]

                            while set(brd[-1]) == {0}:
                                del brd[-1]

                            for line in brd:
                                file_map.write(''.join(list(map(
                                    str, line))) + '\n')

                            file_map.write('\n')
                            file_map.write(';'.join(list(
                                map(lambda x: '-'.join(list(map(str, x))),
                                    board.enemy_list))))

                            file_map.close()

                self.map_edit_manager.process_events(event)

            board.render(screen)
            self.map_edit_manager.update(FPS)
            self.map_edit_manager.draw_ui(screen)
            pygame.display.flip()

class Board:
    def __init__(self, width, height, left, top):
        self.width = width
        self.height = height
        self.board = [[0] * width for _ in range(height)]
        self.enemy_list = []
        self.left = left
        self.top = top
        self.cell_size = 16

    def set_view(self, left, top, cell_size):
        self.left = left
        self.top = top
        self.cell_size = cell_size

    def clear(self):
        self.board = [[0] * self.width for _ in range(self.height)]

    def render(self, screen_to_render):
        for y in range(0, self.height):
            for x in range(0, self.width):
                if self.board[y][x] == 0:
                    pygame.draw.rect(screen_to_render,
                                     pygame.Color(255, 255, 255), (
                                         x * self.cell_size + self.left,
                                         y * self.cell_size + self.top,
                                         self.cell_size, self.cell_size), 1)
                elif self.board[y][x] == 1:
                    pygame.draw.rect(screen_to_render,
                                     pygame.Color(106, 13, 173), (
                                         x * self.cell_size + self.left,
                                         y * self.cell_size + self.top,
                                         self.cell_size, self.cell_size))
        for i in self.enemy_list:
            if i[0] == 'G' and i[-1] == 'RED':
                IMAGE = pygame.transform.scale(
                    pygame.image.load('data/red.png').convert(),
                    (self.cell_size, self.cell_size))
                rect = IMAGE.get_rect()
                rect.x, rect.y = i[1] * self.cell_size + self.left, i[
                    2] * self.cell_size + self.top
                screen_to_render.blit(IMAGE, rect)

            elif i[0] == 'G' and i[-1] == 'GREEN':
                IMAGE = pygame.transform.scale(
                    pygame.image.load('data/green.png').convert(),
                    (self.cell_size, self.cell_size))
                rect = IMAGE.get_rect()
                rect.x, rect.y = i[1] * self.cell_size + self.left, i[
                    2] * self.cell_size + self.top
                screen_to_render.blit(IMAGE, rect)

            elif i[0] == 'G' and i[-1] == 'BLUE':
                IMAGE = pygame.transform.scale(
                    pygame.image.load('data/blue.png').convert(),
                    (self.cell_size, self.cell_size))
                rect = IMAGE.get_rect()
                rect.x, rect.y = i[1] * self.cell_size + self.left, i[
                    2] * self.cell_size + self.top
                screen_to_render.blit(IMAGE, rect)

            elif i[0] == 'G' and i[-1] == 'YELLOW':
                IMAGE = pygame.transform.scale(
                    pygame.image.load('data/yellow.png').convert(),
                    (self.cell_size, self.cell_size))
                rect = IMAGE.get_rect()
                rect.x, rect.y = i[1] * self.cell_size + self.left, i[
                    2] * self.cell_size + self.top
                screen_to_render.blit(IMAGE, rect)

            elif i[0] == 'P':
                IMAGE = pygame.transform.scale(
                    pygame.image.load('data/pacman.png').convert(),
                    (self.cell_size, self.cell_size))
                rect = IMAGE.get_rect()
                rect.x, rect.y = i[1] * self.cell_size + self.left, i[
                    2] * self.cell_size + self.top
                screen_to_render.blit(IMAGE, rect)

    def get_cell(self, mouse_pos):
        x = 0
        while not (x * self.cell_size <= mouse_pos[0] - self.left <= (
                x + 1) * self.cell_size):
            x += 1
        y = 0
        while not (y * self.cell_size <= mouse_pos[1] - self.top <= (
                y + 1) * self.cell_size):
            y += 1
        return x, y

    def on_click(self, cell_coords, action):
        for i in range(len(self.enemy_list) - 1):
            if self.enemy_list[i][1] == cell_coords[0] and \
                    self.enemy_list[i][2] == cell_coords[1]:
                del self.enemy_list[i]
        if action == 'SET_TILE':
            self.board[cell_coords[1]][cell_coords[0]] = 1
        elif action == 'SET_CLEAR':
            self.board[cell_coords[1]][cell_coords[0]] = 0
        elif action == 'SET_RED':
            self.enemy_list.append(
                ['G', cell_coords[0], cell_coords[1], 'RED'])
            self.board[cell_coords[1]][cell_coords[0]] = 3
        elif action == 'SET_GREEN':
            self.enemy_list.append(
                ['G', cell_coords[0], cell_coords[1], 'GREEN'])
            self.board[cell_coords[1]][cell_coords[0]] = 3
        elif action == 'SET_BLUE':
            self.enemy_list.append(
                ['G', cell_coords[0], cell_coords[1], 'BLUE'])
            self.board[cell_coords[1]][cell_coords[0]] = 3
        elif action == 'SET_YELLOW':
            self.enemy_list.append(
                ['G', cell_coords[0], cell_coords[1], 'YELLOW'])
            self.board[cell_coords[1]][cell_coords[0]] = 3
        elif action == 'SET_PLAYER':
            self.board[cell_coords[1]][cell_coords[0]] = 3
            flag = False
            for i in self.enemy_list:
                if i[0] == 'P':
                    flag = True
            if not flag:
                self.enemy_list.append(
                    ['P', cell_coords[0], cell_coords[1]])

    def pos_on_board(self, x, y):
        if self.left <= x <= self.width * self.cell_size + self.left and \
                self.top <= y <= self.height * self.cell_size + self.top:
            return True
        return False

MapCreator().run()


from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()  # can be webdriver.PhantomJS()
browser.get('https://www.woolworths.com.au/shop/browse/specials/half-price')
#browser.get('https://www.woolworths.com.au/shop/browse/specials/half-price/bakery')
# wait for the select element to become visible
#page = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.selectedFilters-count")))
page = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.tileList-tiles")))
item_list_element = page.find_elements_by_css_selector(".shelfProductTile-content")
#36
for div_element in item_list_element:
    print(div_element)
    title = div_element.find_element_by_class_name("shelfProductTile-descriptionLink")
    print(title.text)
    try:
        priceDollars = div_element.find_element_by_class_name("price-dollars")
        priceCents = div_element.find_element_by_class_name("price-cents")
        wasPrice = div_element.find_element_by_class_name("shelfProductTile-wasPrice")
        print(priceDollars.text)
        print(priceCents.text)
        print(wasPrice.text)
    except NoSuchElementException:
        print("OUT OF STOCK")

    #select = Select(select_element)
    #for option in select.options[1:]:
    #    print(option.text)

    # browser.quit()


import discord
import requests
import logging
from discord.ext import commands

class checkproxy:
    """Cog for proxy checking"""

    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True)
    async def checkproxy(self, ctx, proxy):
        """Checks the provided proxy."""

        p = proxy
        pr = {
                    'http': p,
                    'https': p
                }
        try:
            r = requests.get('https://pgorelease.nianticlabs.com/plfe/version',
                             proxies=pr,
                             timeout=5,
                             headers={'Host': 'pgorelease.nianticlabs.com',
                                      'Connection': 'close',
                                      'Accept': '*/*',
                                      'User-Agent': 'pokemongo/0 CFNetwork/893.14.2 Darwin/17.3.0',
                                      'Accept-Language': 'en-us',
                                      'Accept-Encoding': 'br, gzip, deflate',
                                      'X-Unity-Version': '2017.1.2f1'})
            if r.status_code == 200:
                nstatus = ':white_check_mark: 200 OK, proxy is not banned.'
            if r.status_code == 403:
                nstatus = ':x: 403 Forbidden, proxy is banned.'
        except requests.exceptions.Timeout:
            nstatus = ':x: Timed out after 5 seconds.'
        except requests.exceptions.RequestException as e:
            nstatus = 'Unable to connect to the proxy, or timed out. Make sure to add https://, and the port.'
            logging.error('requestsexception: ' + str(e))

        try:
            r = requests.get('https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize&locale=en_US',
                             proxies=pr,
                             timeout=5,
                             headers={'Host': 'sso.pokemon.com',
                                      'Connection': 'close',
                                      'Accept': '*/*',
                                      'User-Agent': 'pokemongo/0 CFNetwork/893.14.2 Darwin/17.3.0',
                                      'Accept-Language': 'en-us',
                                      'Accept-Encoding': 'br, gzip, deflate',
                                      'X-Unity-Version': '2017.1.2f1'})
            if r.status_code == 200:
                pstatus = ':white_check_mark: 200 OK, proxy is not banned.'
            if r.status_code == 409:
                pstatus = ':x: 409 Conflict, proxy is banned.'
        except requests.exceptions.Timeout:
            pstatus = ':x: Timed out after 5 seconds.'
        except requests.exceptions.RequestException as e:
            pstatus = 'Unable to connect to the proxy, or timed out. Make sure to add https://, and the port.'
            logging.error('requestsexception: ' + str(e))

        await self.bot.say("""Niantic: """ + nstatus + """
PTC: """ + pstatus)

        if not ctx.message.channel.is_private:
            await self.bot.delete_message(ctx.message)

def setup(bot):
    bot.add_cog(checkproxy(bot))


import json
import pyautogui
import time
from TwitchWebsocket import TwitchWebsocket
from handler import *

# https://github.com/CubieDev/TwitchWebsocket

def presshold(key):
    set_given(num=key)

class Settings:
    def __init__(self, bot):
        try:
            # Try to load the file using json.
            # And pass the data to the MyBot class instance if this succeeds.
            with open("settings.txt", "r") as f:
                settings = f.read()
                data = json.loads(settings)
                bot.set_settings(data['Host'],
                                 data['Port'],
                                 data['Channel'],
                                 data['Nickname'],
                                 data['Authentication'])
        except ValueError:
            raise ValueError("Error in settings file.")
        except FileNotFoundError:
            # If the file is missing, create a standardised settings.txt file
            # With all parameters required.
            with open('settings.txt', 'w') as f:
                standard_dict = {
                    "Host": "irc.chat.twitch.tv",
                    "Port": 6667,
                    "Channel": "#<channel>",
                    "Nickname": "<name>",
                    "Authentication": "oauth:<auth>"
                }
                f.write(json.dumps(standard_dict, indent=4, separators=(',', ': ')))
                raise ValueError("Please fix your settings.txt file that was just generated.")

class MyBot:
    def __init__(self):
        self.host = None
        self.port = None
        self.chan = None
        self.nick = None
        self.auth = None

        # Fill previously initialised variables with data from the settings.txt file
        Settings(self)

        self.ws = TwitchWebsocket(host=self.host,
                                  port=self.port,
                                  chan=self.chan,
                                  nick=self.nick,
                                  auth=self.auth,
                                  callback=self.message_handler,
                                  capability=["membership", "tags", "commands"],
                                  live=False)
        self.ws.start_blocking()

    def set_settings(self, host, port, chan, nick, auth):
        self.host = host
        self.port = port
        self.chan = chan
        self.nick = nick
        self.auth = auth

    def message_handler(self, m):
        if m.type == "PRIVMSG":
            pass
        msg = m.message
        print(m.user, ":", msg)
        if msg == "1" or msg == "!place 1":
            presshold("1")
        if msg == "2" or msg == "!place 2":
            presshold("2")
        if msg == "3" or msg == "!place 3":
            presshold("3")
        if msg == "4" or msg == "!place 4":
            presshold("4")
        if msg == "5" or msg == "!place 5":
            presshold("5")
        if msg == "6" or msg == "!place 6":
            presshold("6")
        if msg == "7" or msg == "!place 7":
            presshold("7")
        if msg == "8" or msg == "!place 8":
            presshold("8")
        if msg == "9" or msg == "!place 9":
            presshold("9")

if __name__ == "__main__":
    MyBot()


from flask import Flask, render_template, redirect, url_for, jsonify, request
import json

webapp = Flask(__name__)

#---------------------------------------------------------
@webapp.route("/", methods=["GET"])

def indexPage():
	return render_template("base.html"), 200

#----------------------------------------------------------

@webapp.route("/user",methods=["GET"])

def getUserPage():
	return render_template("user_dashboard.html"), 200

#----------------------------------------------------------

@webapp.route('/submitmovie',methods=['POST','GET'])

def getUserMovie():
	d = request.args.to_dict()
	username = d['name']
	usermovie = d['movie']
	# if request.method == 'POST':
	# 	username = request.form['name']
	# 	usermovie = request.form['movie']
	# 	return render_template("user_movie_request.html",usermovie=usermovie,username=username)

	return render_template("user_movie_request.html",username=username,usermovie=usermovie), 200

#----------------------------------------------------------

@webapp.route('/processage',methods=['GET'])

def processUserAge():
	movie = "The Conjuring"
	age = 20
	return render_template("watchstatus.html",usermovie=movie,userage=age), 200

#----------------------------------------------------------

@webapp.route("/admin",methods=["GET"])

def getAdminPage():
	return redirect(url_for('getUserPage')), 301

#------------------------------------------------------

@webapp.route("/allusers",methods=["GET"])

def getUsers():
	users = {
	"userdata": [
	{"firstname": "John",
	"lastname": "Doe",
	"status": "user"},

	{"firstname": "Becky",
	"lastname": "Ann",
	"status": "admin"}]
	}

	with open("allusers.json","w") as file:
		json.dump(users, file, ensure_ascii=False)

	return jsonify(users), 200

@webapp.route("/search",methods=["GET"])

def searchUser():
	d = request.args.to_dict()
	username = d["name"]

	with open("allusers.json","r") as file:
		content = json.load(file)
		for item in content["userdata"]:
			if item["firstname"] == username:
				userinfo = item

		# userinfo = [item for item in content["userdata"] if item["firstname"] == d["name"]]

	return userinfo

if __name__=="__main__":
	webapp.run(port=4800,debug=True)

# from flask import Flask, render_template, request
# from flask_cors import CORS
# import pandas as pd
# import json

# app = Flask(__name__)
# CORS(app)

# #BASE HTML PAGE
# #--------------------

# @app.route('/')

# def home():
# 	return render_template("index.html", num=45), 200

# #GET A QUOTE
# #-------------
# @app.route('/getaquote',methods=['POST','GET'])

# def quote():
# 	if request.method == 'POST':
# 		with open('requests.txt','w') as f:
# 			f.write(f"'Request': {request.form}, 'Type': {type(request.form)}")
# 		print(request.form)
# 		print(type(request.form))
# 		content = request.form['myinput']
# 		return render_template("requestquote.html", content=content), 200
# 	return render_template("requestquote.html"), 200

# if request.method == 'POST':
	# 	content = request.form['movie']
	# 	return render_template("user_movie_request.html"), 201

# if __name__=="__main__":
# 	app.run(port=4400, debug=True)


import sys, pygame
from pipe import Pipe, PipeManager
from floor import Floor
from sound import Sound
from score import Score
from mon import Mon

# hàm trò chơi
pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
pygame.init()
idx = 0
# đặt size cho cửa sổ
WIN = pygame.display.set_mode((360, 640))

# set up opening
opening = pygame.image.load('image/opening .png').convert()

# set up background
bg = pygame.image.load('image/background.png').convert()

# đặt tên cửa sổ
pygame.display.set_caption("FLAPPY MON")

# xác định số frame mỗi giây
FPS = 60  # tốc dộ bình thường của game
clock = pygame.time.Clock()
# thêm ống
PIPE_SURFACE = pygame.image.load('image/column.png').convert()
PIPE_HEIGHT = [i for i in range(300, 500)]
# thêm font chữ
game_font = pygame.font.Font('Audiowide-Regular (1).ttf', 40)
# biến
game_active = True
# điểm
score = Score(WIN=WIN, game_font=game_font)
doramon = Mon()
floor = Floor(WIN=WIN)
sound = Sound()
pipe = Pipe(PIPE_SURFACE=PIPE_SURFACE, PIPE_HEIGHT=PIPE_HEIGHT)
pipe_manager = PipeManager(WIN=WIN, sound=sound, score=score, idx=idx, game_active=game_active, PIPE_HEIGHT=PIPE_HEIGHT, PIPE_SURFACE=PIPE_SURFACE)

# tạo màn hình kết thúc
game_over_surface = pygame.image.load('image/opening .png').convert_alpha()
game_over_rect = game_over_surface.get_rect(center=(180, 320))
# tạo timer
spawnpipe = pygame.USEREVENT
pygame.time.set_timer(spawnpipe, 1200)  # sau 1.2s tạo ra ống mới

def check_collision(pipes):  # check va chạm
    for pipee in pipes:
        if doramon.mon_rect.colliderect(pipee):
            sound.hit_sound.play()
            return False
    if doramon.mon_rect.top <= -100 or doramon.mon_rect.bottom >= 550:  # kiểm soát mon không bay ra ngoài cửa sổ
        sound.hit_sound.play()
        return False
    return True

def gameStart(WIN):

    WIN.blit(opening, (0, 0))

    while True:  # tạo loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                return

        pygame.display.update()
        clock.tick(FPS)

def main(game_active):

    while True:  # tạo loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and game_active: #Tạo hiệu ứng bay
                    # jump
                    doramon.set_mon_movement(-5)
                    sound.flap_sound.play()
                if event.key == pygame.K_SPACE and game_active == False: #tạo di chuyển của ống
                    game_active = True
                    pipe_manager.clear_pipe_list()
                    doramon.mon_rect.center = (100, 320)
                    doramon.set_mon_movement(0)
                    score.reset_score()
                    pipe_manager.idx = 0
            if event.type == spawnpipe: #tạo hệ thống ống
                pipe_pos = pipe.create_pipe()
                pipe_manager.add_pipe(pipe_pos)

        if game_active:
            WIN.blit(bg, (0, 0))  # thêm background
            doramon.move()
            WIN.blit(doramon.rotated_mon, doramon.mon_rect)  # thêm mon vào
            # ống
            pipe_manager.pipe_movement()
            pipe_manager.draw_pipe()
            game_active = check_collision(pipe_manager.get_pipe_list())
            # điểm
            score.display_score('main game')
            floor.move_floor()
            floor.draw_floor()
            floor.check_and_reset_floor()
        else:
            # màn hình game over
            WIN.blit(game_over_surface, game_over_rect)
            # điểm
            score.update_score()
            score.display_score('game over')
        #  thêm floor chuyển động
        #floor.move_floor()
        floor.draw_floor()
        #floor.check_and_reset_floor()

        pygame.display.update()
        clock.tick(FPS)  # để kiểm soát tốc độ của chương trình

if __name__ == '__main__':
    gameStart(WIN)
    main(game_active)