index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
19,682,765
|
Gundlack-C-C/Pubmed_Crawler
|
refs/heads/main
|
/app_server.py
|
from flask import Flask, request, jsonify
from flask_cors import CORS
import sys
import os
import json
from werkzeug.exceptions import BadRequest, ServiceUnavailable
import logging
import argparse
import uuid
app = Flask(__name__)
CORS(app)
class IncorrectInputException(Exception):
pass
from RabbitMQ.RabbitMQConnection import RabbitMQConnection
import os
import json
exchange = os.getenv('RABBITMQ_EXCHANGE_NAME')
def sendMessage(message, routing_key, exchange=exchange):
channel = RabbitMQConnection().channel()
channel.exchange_declare(exchange=exchange, exchange_type='direct')
channel.basic_publish(
exchange=exchange,
routing_key=routing_key,
body=json.dumps(message)
)
channel.close()
class QueryServer():
@staticmethod
def validateInput(input):
try:
assert input.get('query', False) != False, '"query" missing!'
except Exception as e:
raise IncorrectInputException('Missing Field! ' + str(e)) from e
try:
assert isinstance(input['query'], list), '"query": Expected list of strings!'
except Exception as e:
raise IncorrectInputException('Invalid Format! ' + str(e)) from e
@staticmethod
def update_query(input, _id=None, mode='pubmed-query'):
_id = _id if _id else uuid.uuid4().hex
try:
#Send Query Status: NEW
sendMessage({
"id": _id,
"state": "NEW",
"query": json.dumps(input),
"state_query": json.dumps(["PENDING"] * len(input)),
"msg": "New session commited to queue.", }, routing_key=mode+'-status')
#Send Query Request
for text in input:
sendMessage({"id": _id, "text": text}, routing_key=mode)
except Exception as e:
raise ServiceUnavailable(f'RabbitMQ Service not available! Reason: {str(e)}') from e
return _id
@app.route('/status', methods=['GET'])
def status():
return jsonify({
"status": "online",
"msg": "Query Service is online!"
})
@app.route('/query', methods=['POST'])
def Commit_Query():
try:
data = json.loads(request.data)
except Exception as e:
raise BadRequest(f"Invalid Input! JSON format required! {e}") from e
QueryServer.validateInput(data)
query = data.get('query', None)
id = data.get('id', None)
mode = os.getenv('RABBITMQ_CRAWLER_PUBMED_ROUTING_KEY')
session_id = QueryServer.update_query(query, _id=id, mode=mode)
return jsonify(session_id)
if __name__ == '__main__':
LOG = "./.log/query-service.log"
# Setup Argument Parser
parser = argparse.ArgumentParser(description='Argument Parser')
parser.add_argument('--l', '--log', dest='LOGFILE', type=str, default=LOG,
help=f'path for logfile (default: {LOG})')
parser.add_argument("--production", action='store_const',
help="set to production mode", const=True, default=False)
args = parser.parse_args()
# Check if production is set
PRODUCTION = args.production
os.environ['PRODUCTION'] = str(PRODUCTION)
if not os.path.exists(os.path.abspath(os.path.dirname(args.LOGFILE))):
os.makedirs(os.path.abspath(os.path.dirname(args.LOGFILE)))
# Setup Logging
logging.basicConfig(filename=args.LOGFILE, level=logging.INFO if PRODUCTION else logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(f"Starting Server with [{args}]")
try:
# Start Server
app.run(host="0.0.0.0", debug=False, port=5001)
except Exception as e:
logging.error(e)
|
{"/crawler/spiders/pubmed.py": ["/crawler/items.py"], "/app_crawl_pubmed.py": ["/crawler/spiders/pubmed.py"], "/app_workermq.py": ["/RabbitMQ/Configuration.py"]}
|
19,682,766
|
Gundlack-C-C/Pubmed_Crawler
|
refs/heads/main
|
/crawler/pipelines.py
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exporters import JsonItemExporter
import os
class JSONPipeline(object):
@ classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
file_settings = crawler.settings.getdict("FILE_SETTINGS")
if not file_settings or 'out' not in file_settings.keys():
raise "FILE_SETTINGS missing or incomplete for JSONPipeline"
path = file_settings.get('out', './.out/pubmed_result.json')
overwrite = file_settings.get('overwrite', True)
return cls(path, overwrite)
def __init__(self, path="data_export.json", overwrite=False):
if not os.path.exists(os.path.abspath(os.path.dirname(path))):
os.makedirs(os.path.abspath(os.path.dirname(path)))
if overwrite and os.path.isfile(path):
os.remove(path)
self.file = open(path, 'wb')
self.exporter = JsonItemExporter(
self.file, encoding='utf-8', ensure_ascii=False)
self.exporter.start_exporting()
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
|
{"/crawler/spiders/pubmed.py": ["/crawler/items.py"], "/app_crawl_pubmed.py": ["/crawler/spiders/pubmed.py"], "/app_workermq.py": ["/RabbitMQ/Configuration.py"]}
|
19,682,767
|
Gundlack-C-C/Pubmed_Crawler
|
refs/heads/main
|
/app_crawl_pubmed.py
|
import os
import sys
import inspect
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import timeit
import binascii
import logging
import pickle
from crawler.spiders.pubmed import PubmedSpider
from scrapy.signalmanager import dispatcher
from scrapy import signals
from scrapy.utils.project import get_project_settings
from scrapy.crawler import CrawlerProcess
import argparse
def str2hex(text):
return binascii.hexlify(text.encode()).decode('utf-8')
if __name__ == '__main__':
try:
# Setup Argument Parser
parser = argparse.ArgumentParser(description='Argument Parser')
parser.add_argument('query', type=str, help='query to search for')
parser.add_argument('--out', type=str,
help='folder output', default="./.out")
parser.add_argument('-l', '--log', type=str,
help='Target path for logging.', default=None)
parser.add_argument(
'-c', '--cached', help='Use cached results if available - Output File already existing and not older than 5 days. Default=False', action='store_true')
parser.add_argument(
'-p', '--production', help="Enable production mode. Default=False", action='store_true')
args = parser.parse_args()
PRODUCTION = args.production
USE_CACHED = args.cached
LOG_ENABLED = not PRODUCTION
LOG_LEVEL = logging.INFO if PRODUCTION else logging.DEBUG
###################
# Setup Logging
###################
query = args.query
query_id = str2hex(query)
LOGFILE = args.log if args.log else f'./.log/{query_id}.crawler.log'
if not os.path.exists(os.path.abspath(os.path.dirname(LOGFILE))):
os.makedirs(os.path.abspath(os.path.dirname(LOGFILE)))
if os.path.isfile(LOGFILE):
os.remove(LOGFILE)
logging.basicConfig(filename=LOGFILE, level=LOG_LEVEL,
format='%(asctime)s %(levelname)-8s %(message)s')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(f"Crawler Start!")
logging.info(f"Arguments: [{args}]")
logging.info(f"Query: [{query}]")
logging.info(f"Query ID: [{query_id}]")
tic = timeit.default_timer()
###################
# Init Crawler Settings
###################
settings = get_project_settings()
settings['SPIDER_MODULES'] = ['crawler.spiders']
settings['LOG_ENABLED'] = LOG_ENABLED
settings['LOG_LEVEL'] = LOG_LEVEL
settings['RETRY_TIMES'] = 5
settings['AUTOTHROTTLE_ENABLED'] = True
settings['AUTOTHROTTLE_MAX_DELAY'] = 1.0
settings['AUTOTHROTTLE_START_DELAY'] = 0.1
settings['AUTOTHROTTLE_TARGET_CONCURRENCY'] = 3.0
# Disable/Enable scrapy logging if LOG_ENABLED
logging.getLogger('scrapy').propagate = LOG_ENABLED
###################
# Start Crawler
###################
result = []
logging.info("Start Crawling ...")
def on_item_passed(signal, sender, item, response):
result.append(dict(item))
dispatcher.connect(on_item_passed, signal=signals.item_passed)
process = CrawlerProcess(settings=settings)
process.crawl(PubmedSpider, query=query)
process.start()
dispatcher.disconnect(on_item_passed, signal=signals.item_passed)
T = timeit.default_timer() - tic
logging.info(f'{len(result)} Items found for [{query}]')
logging.info(f'Total: {round(T,2)}s p.Item: {round(T/len(result),3)}s')
logging.info("... Finish Crawling!")
###################
# Write Results
###################
FOLDEROUT = args.out
if not os.path.exists(os.path.abspath(os.path.dirname(FOLDEROUT))):
os.makedirs(os.path.abspath(os.path.dirname(FOLDEROUT)))
# Query Results
QUERYOUT = f"{FOLDEROUT}/{query_id}.query.dat"
logging.info(f"Store Query Data [{QUERYOUT}] ...")
_ids = list(set([x['_id'] for x in result]))
query_data = {
'_id': query_id,
'query': query,
'articles': _ids
}
pickle.dump(query_data, open(QUERYOUT, 'wb'))
logging.info("... Store Query Data Sucess!")
# Article Results
ARTICLEOUT = f"{FOLDEROUT}/{query_id}.article.dat"
logging.info(f"Store Article Data [{ARTICLEOUT}] ...")
article_data = {
'_id': query_id,
'query': query,
'articles': result
}
pickle.dump(article_data, open(ARTICLEOUT, 'wb'))
logging.info("... Store Article Data Sucess!")
logging.info("Crawler Success!")
except Exception as e:
###################
# Error Management
###################
logging.error("Crawler Error!")
logging.error(e)
|
{"/crawler/spiders/pubmed.py": ["/crawler/items.py"], "/app_crawl_pubmed.py": ["/crawler/spiders/pubmed.py"], "/app_workermq.py": ["/RabbitMQ/Configuration.py"]}
|
19,682,768
|
Gundlack-C-C/Pubmed_Crawler
|
refs/heads/main
|
/app_workermq.py
|
from RabbitMQ.Listener import Listener
import RabbitMQ.Configuration as Configuration
import logging
import os
import sys
import argparse
import json
import subprocess
import binascii
fire_connector = None
def str2hex(text):
return binascii.hexlify(text.encode()).decode('utf-8')
def query_request_callback(ch, method, properties, body):
logging.info(" [x] Pubmed - Query Received %r" % body.decode())
try:
request = json.loads(body)
_id = request.get('id', None)
text = request.get('text', None)
assert _id != None, "Invalid Session Status Body! Missing field 'id'"
assert text != None, "Invalid Session Status Body! Missing field 'text'"
logging.info(f"Execute Query: [{request}]")
logfile = f".log/{str2hex(text)}.crawler.log"
args = ["python3", "./app_crawl_pubmed.py", text, "--production", "-l", logfile]
process = subprocess.Popen(args)
process.wait()
logging.info(" [x] Done")
except Exception as e:
logging.error(f"Pubmed - Query Request Callback Failed! " + str(e))
if __name__ == '__main__':
LOG = "./.log/pubmed-query-worker.log"
try:
# Setup Argument Parser
parser = argparse.ArgumentParser(description='Argument Parser')
parser.add_argument('--l', '--log', dest='LOGFILE', type=str, default=LOG,
help=f'path for logfile (default: {LOG})')
parser.add_argument("--production", action='store_const',
help="set to production mode", const=True, default=False)
args = parser.parse_args()
# Check if production is set
PRODUCTION = args.production
os.environ['PRODUCTION'] = str(PRODUCTION)
if not os.path.exists(os.path.abspath(os.path.dirname(args.LOGFILE))):
os.makedirs(os.path.abspath(os.path.dirname(args.LOGFILE)))
# Setup Logging
logging.basicConfig(filename=args.LOGFILE, level=logging.INFO if PRODUCTION else logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(f"Starting Query Service with [{args}]")
routing_key = os.getenv('RABBITMQ_CRAWLER_PUBMED_ROUTING_KEY')
queue = Configuration.ROUTING[routing_key]['QUEUE_NAME']
listener_sklearn = Listener(routing_key=routing_key)
listener_sklearn.attachCallbackToQueue(queue, query_request_callback)
listener_sklearn.run()
except Exception as e:
logging.error(e)
|
{"/crawler/spiders/pubmed.py": ["/crawler/items.py"], "/app_crawl_pubmed.py": ["/crawler/spiders/pubmed.py"], "/app_workermq.py": ["/RabbitMQ/Configuration.py"]}
|
19,682,769
|
Gundlack-C-C/Pubmed_Crawler
|
refs/heads/main
|
/crawler/items.py
|
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from itemloaders.processors import Join, MapCompose, TakeFirst
from w3lib.html import remove_tags
def clearWhitespaces(str):
return " ".join(str.split())
def clearNewline(str):
return " ".join(str.split("\n"))
class Article(scrapy.Item):
_id = scrapy.Field(input_processor=MapCompose(
str.strip), output_processor=TakeFirst())
title = scrapy.Field(default="", input_processor=MapCompose(
str.strip), output_processor=TakeFirst())
short = scrapy.Field(default="", input_processor=MapCompose(
remove_tags, clearNewline, clearWhitespaces, str.strip, ), output_processor=Join())
authors = scrapy.Field(default="", input_processor=MapCompose(
str.strip), output_processor=TakeFirst())
url = scrapy.Field(input_processor=MapCompose(
str.strip), output_processor=TakeFirst())
journal = scrapy.Field(default="", input_processor=MapCompose(
str.strip), output_processor=TakeFirst())
keywords = scrapy.Field(default=[])
|
{"/crawler/spiders/pubmed.py": ["/crawler/items.py"], "/app_crawl_pubmed.py": ["/crawler/spiders/pubmed.py"], "/app_workermq.py": ["/RabbitMQ/Configuration.py"]}
|
19,682,770
|
Gundlack-C-C/Pubmed_Crawler
|
refs/heads/main
|
/crawler/spiders/pubmed.py
|
# -*- coding: utf-8 -*-
import scrapy
import json
from urllib.request import urlopen
from ..items import Article
from scrapy.loader import ItemLoader
base_url = "https://pubmed.ncbi.nlm.nih.gov"
db = 'pubmed'
def getIDs(term):
term = term.replace(' ', "%20")
url = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db={db}&term={term}&retmax=100000&sort=relevance&retmode=json'
ref_data = urlopen(url)
data_raw = ref_data.read()
data = json.loads(data_raw)
results = data['esearchresult']
return results['idlist']
def getXmlArticlesUrl(ids):
return f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id={",".join(ids)}&retmode=xml&rettype=abstract'
class PubmedPeekSpider(scrapy.Spider):
name = 'peek'
page_size = 10
max_pages = 10000/page_size
def __init__(self, query='', ** kwargs):
self.start_urls = [f'{base_url}/?term={query}']
self.query = query
super().__init__(**kwargs)
def parse(self, response):
total = 0
total_dom = response.css("div.results-amount span.value::text")
if(len(total_dom) > 0):
total = int(total_dom[0].get().replace(",", ""))
yield({"total": total, "url": response.url, "query": self.query})
class PubmedSpider(scrapy.Spider):
name = 'pubmed'
def __init__(self, query='', page_size=100, ** kwargs):
ids = getIDs(query)
ids_batched = [ids[i*page_size:(i+1)*page_size]
for i in range(0, round(len(ids)/page_size))] if len(ids) > page_size else [ids]
self.ids = ids
self.start_urls = [getXmlArticlesUrl(ids) for ids in ids_batched]
self.query = query
super().__init__(**kwargs)
def parse(self, response):
# Get all articles from response
for item in response.xpath('PubmedArticle'):
loader = ItemLoader(item=Article(), selector=item)
# Get Pubmed ID
_id = item.xpath("MedlineCitation/PMID/text()").extract_first()
loader.add_value("_id", _id)
loader.add_value("url", f'{base_url}/{_id}/')
article = item.xpath('MedlineCitation/Article')
# Get Article Content
title = article.xpath("ArticleTitle/text()").extract_first()
short = article.xpath("Abstract/AbstractText/text()").extract()
loader.add_value("title", title)
loader.add_value("short", short)
# Get Journal Info
journal = article.xpath('Journal')
journal_title = journal.xpath('Title/text()').extract_first()
journal_year = journal.xpath(
'JournalIssue/PubDate/Year/text()').extract_first()
journal_month = journal.xpath(
'JournalIssue/PubDate/Month/text()').extract_first()
loader.add_value(
"journal", f"{journal_title}, {journal_year}-{journal_month}")
yield loader.load_item()
|
{"/crawler/spiders/pubmed.py": ["/crawler/items.py"], "/app_crawl_pubmed.py": ["/crawler/spiders/pubmed.py"], "/app_workermq.py": ["/RabbitMQ/Configuration.py"]}
|
19,682,771
|
Gundlack-C-C/Pubmed_Crawler
|
refs/heads/main
|
/RabbitMQ/Configuration.py
|
import os
EXCHANGE_NAME = os.getenv("RABBITMQ_EXCHANGE_NAME")
ROUTING = {
'query-pubmed': {
'QUEUE_NAME': os.getenv("RABBITMQ_CRAWLER_PUBMED_QUEUE_INPUT")
},
'query-pubmed-status': {
'QUEUE_NAME': os.getenv("RABBITMQ_CRAWLER_STATUS_QUEUE_INPUT")
},
'query-status': {
'QUEUE_NAME': os.getenv("RABBITMQ_CRAWLER_STATUS_QUEUE_INPUT")
}
}
|
{"/crawler/spiders/pubmed.py": ["/crawler/items.py"], "/app_crawl_pubmed.py": ["/crawler/spiders/pubmed.py"], "/app_workermq.py": ["/RabbitMQ/Configuration.py"]}
|
19,723,516
|
roshanissac/LRU
|
refs/heads/main
|
/unit_test_cases.py
|
import unittest
from collections import OrderedDict
from lru import lruCache,KeyNotExistError,DuplicateKeyError,ValidSizeError
class MyTestCase(unittest.TestCase):
# Returns true if lruCache(-2) raises a ValidSizeError
def test_1(self):
with self.assertRaises(Exception):
lruCache(-2) # Passing negative value as the size of the cache
# Returns true if lruCache(0) raises a ValidSizeError
def test_2(self):
with self.assertRaises(Exception):
lruCache(0) # Passing zero value as the size of the cache
# Returns true if lruCache('skjhdf') raises a ValidSizeError
def test_3(self):
with self.assertRaises(Exception):
lruCache('skjhdf') # Passing string as the size of the cache
# Returns true if lruCache(5.67) raises a ValidSizeError
def test_4(self):
with self.assertRaises(Exception):
lruCache(5.67) # Passing float value as the size of the cache
# Returns true if it raises a DuplicateKeyError
def test_5(self):
with self.assertRaises(Exception):
cache=lruCache(2) # Setting the size
cache.put(1,1)
cache.put(1,1) # Adding again an item with the same key
# The test will pass if both dictionaries has the same elements in correct order,latest added will will go to end
def test_6(self):
cache=lruCache(2) # Setting the size
cache.put(1,1)
cache.put(2,1) # Adding second item
self.result=cache.cache
self.expected=OrderedDict([(1,1),(2,1)])
self.assertDictEqual(self.result,self.expected)
# The test will pass if both dictionaries has the same elements in correct order,recently accessed item will will go to end
def test_7(self):
cache=lruCache(2) # Setting the size
cache.put(1,1)
cache.put(2,1) # Adding second item
cache.get(1) # Accessing item with key 1
self.result=cache.cache
self.expected=OrderedDict([(2,1),(1,1)]) # key 1 will get moved to the end since it is recently used
self.assertDictEqual(self.result,self.expected)
# The test will pass if both dictionaries has the same elements in correct order,recently accessed/added item will will go to end
def test_8(self):
cache=lruCache(3) # Setting the size
cache.put(1,1)
cache.put(2,2) # Adding second item
cache.put(3,3) # Adding third item
cache.get(1) # Accessing item with key 1,so the order will be [(2,2),(3,3),(1,1)]
cache.put(4,4) # Adding fourth item ,since max size is 3 it will remove the least recently used item ie (2,2) and will add (4,4) to the end,so dict content be [(3,3),(1,1),(4,4)]
self.result=cache.cache
self.expected=OrderedDict([(3,3),(1,1),(4,4)])
self.assertDictEqual(self.result,self.expected)
# The test will pass if both dictionaries has the same elements in correct order,recently accessed item will will go to end
def test_9(self):
cache=lruCache(3) # Setting the size
cache.put(1,1)
cache.put(2,2) # Adding second item
cache.put(3,3) # Adding third item
cache.get(1) # Accessing item with key 1,so the order will be [(2,2),(3,3),(1,1)]
cache.put(4,4) # Adding fourth item ,since max size is 3 it will remove the least recently used item ie (2,2) and will add (4,4) to the end,so dict content be [(3,3),(1,1),(4,4)]
cache.delete(1) # deleting the item with key 1 ,so dic content be [(3,3),(4,4)]
self.result=cache.cache
self.expected=OrderedDict([(3,3),(4,4)])
self.assertDictEqual(self.result,self.expected)
# The test will pass if both dictionaries has the same elements in correct order,recently accessed item will will go to end
def test_10(self):
cache=lruCache(3) # Setting the size
cache.put(1,1)
cache.put(2,2) # Adding second item
cache.put(3,3) # Adding third item
cache.get(1) # Accessing item with key 1,so the order will be [(2,2),(3,3),(1,1)]
cache.put(4,4) # Adding fourth item ,since max size is 3 it will remove the least recently used item ie (2,2) and will add (4,4) to the end,so dict content be [(3,3),(1,1),(4,4)]
cache.delete(5) # Attempting to delete a key that doesnt exist is a no operation so dict remains the same [(3,3),(1,1),(4,4)]
self.result=cache.cache
self.expected=OrderedDict([(3,3),(1,1),(4,4)])
self.assertDictEqual(self.result,self.expected)
# The test will pass if both dictionaries has the same elements in correct order,recently accessed item will will go to end
def test_11(self):
cache=lruCache(3) # Setting the size
cache.put(1,1)
cache.put(2,2) # Adding second item
cache.put(3,3) # Adding third item
cache.reset() # All the elements will be cleared
self.result=cache.cache
self.expected=OrderedDict()# empty dictionary
self.assertDictEqual(self.result,self.expected)
# Trying to reset without adding any elements
def test_12(self):
cache=lruCache(3) # Setting the size
cache.reset() # Resetting
self.result=cache.cache
self.expected=OrderedDict()# empty dictionary
self.assertDictEqual(self.result,self.expected)
# Deleting without adding any elements
def test_13(self):
cache=lruCache(3) # Setting the size
cache.delete(2) # Deleting,no operation
self.result=cache.cache
self.expected=OrderedDict()# empty dictionary
self.assertDictEqual(self.result,self.expected)
# Returns true if it raises a KeyNotExistError
def test_14(self):
with self.assertRaises(Exception):
cache=lruCache(2) # Setting the size
cache.get(1)# Accessing key without Adding items
if __name__ == '__main__':
unittest.main()
|
{"/unit_test_cases.py": ["/lru.py"], "/sample.py": ["/lru.py"]}
|
19,723,517
|
roshanissac/LRU
|
refs/heads/main
|
/sample.py
|
from lru import lruCache,KeyNotExistError,DuplicateKeyError,ValidSizeError
try:
cache=lruCache(3) # Setting the size of 3.Maximum 3 items can be added.
cache.put(1,1)
print(cache.cache)
cache.put(2,2) # Adding second item
print(cache.cache)
cache.put(3,3) # Adding third item
print(cache.cache)
cache.get(1) # Accessing item with key 1,so the order will be [(2,2),(3,3),(1,1)]
print(cache.cache)
cache.put(4,4) # Adding fourth item ,since max size is 3 it will remove the least recently used item ie (2,2) and will add (4,4) to the end,so dict content be [(3,3),(1,1),(4,4)]
print(cache.cache)
cache.delete(1) # deleting the item with key 1 ,so dic content be [(3,3),(4,4)]
print(cache.cache)
cache.get(3) # Accessing item with key 3,so the order will be [(4,4),(3,3)],so element with key 3 will be most recently used and it is pushed to the end of the dictionary
print(cache.cache)
cache.put(5,5) # Adding 5th item ,it will be most recently used and pushed to the end [(4,4),(3,3),(5,5)]
print(cache.cache)
cache.reset() # Resetting the cache,All items is cleared
print(cache.cache)
except ValidSizeError:
print("Please enter a valid size")
except DuplicateKeyError:
print("Key already exists,Please enter a new key!")
except KeyNotExistError:
print("The key not exist or the cache is empty")
|
{"/unit_test_cases.py": ["/lru.py"], "/sample.py": ["/lru.py"]}
|
19,723,518
|
roshanissac/LRU
|
refs/heads/main
|
/lru.py
|
#importing OrderedDic from collections module
from collections import OrderedDict
#Classes for handling exceptions
class ValidSizeError(Exception):
pass
class DuplicateKeyError(Exception):
pass
class KeyNotExistError(Exception):
pass
#main class for the lru logic
class lruCache:
def __init__(self, size: int):
self.cache = OrderedDict() # Initializing an ordered dictionary
if isinstance(size,int) and size > 0:
self.size = size # setting the size of the cache
else:
raise ValidSizeError # raising error if invalid value for the size variable
'''get method will return the value of the key passed and it also moves that item to the end of the dictionary as it was recently used.If the key passed doesnt
exist in the dictionary it will raise KeyNotExistError exception
'''
def get(self, key):
if key not in self.cache:
raise KeyNotExistError
else:
self.cache.move_to_end(key)
return self.cache[key]
'''put method is will get the key and value to be inserted and it will move the new item to the end of the dictionary and if the size of the cache
exceeds the maximum size it will remove the least recently used item,which will be the first element of the dictionary.If we are inserting a duplicate key
then DuplicateKeyError exception is raised.
'''
def put(self, key,value):
if key not in self.cache:
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.size:
self.cache.popitem(last = False)
else:
raise DuplicateKeyError
def reset(self):
self.cache.clear()#clears the items from the dictionary
def delete(self, key):
if key not in self.cache:# No operation if the key not found
return -1
else:
self.cache.pop(key)# removes the key found
|
{"/unit_test_cases.py": ["/lru.py"], "/sample.py": ["/lru.py"]}
|
19,748,912
|
fauzaanirsyaadi/Flask-Tutorial-Series-For-Dummies-Create-TO-DO-Website
|
refs/heads/main
|
/app.py
|
from flask import Flask, render_template, request, redirect, url_for
from forms import Todo
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__,template_folder='template')
app.config['SECRET_KEY'] = 'password'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class TodoModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(256))
def __str__(self):
return f'{self.content}, {self.id}'
@app.route('/', methods=['GET', 'POST'])
def hello_world():
request_method = request.method
todo = TodoModel.query.all()
if request.method=="POST":
first_name=request.form('first_name')
return redirect(url_for('name', first_name=first_name))
return render_template('hello.html', request_method=request_method, todo=todo)
@app.route('/name/<string:first_name>')
def name(first_name):
return f'{first_name}'
@app.route('/todo', methods=['GET', 'POST'])
def todo():
todo_form = Todo()
if todo_form.validate_on_submit():
todo = TodoModel(content=todo_form.content.data)
# print(todo_form.content.data)
db.session.add(todo)
db.session.commit()
return redirect('/')
return render_template('todo.html', form=todo_form)
if __name__ == '__main__':#ketika file ini dibuka kita akan langsung ran app.py
app.run(debug=True)
|
{"/app.py": ["/forms.py"]}
|
19,748,913
|
fauzaanirsyaadi/Flask-Tutorial-Series-For-Dummies-Create-TO-DO-Website
|
refs/heads/main
|
/forms.py
|
from flask_wtf import FlaskForm
from wtforms import TextAreaField
from wtforms.validators import DataRequired
class Todo(FlaskForm):
content = TextAreaField(validators=[DataRequired()])
submit = SubmitField('Submit todo')
|
{"/app.py": ["/forms.py"]}
|
19,801,559
|
ohwani/molla
|
refs/heads/master
|
/accounts/generics.py
|
from rest_framework import mixins, generics
class ListCreateAPIView(
mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView
):
def get(self, request, *args, **kwargs):
return self.list(request)
def post(self, request, *args, **kwargs):
return self.create(request)
class RetrieveUpdateDestroyAPIView(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView
):
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.delete(request, *args, **kwargs)
|
{"/accounts/views.py": ["/accounts/serializers.py", "/accounts/models.py"], "/accounts/serializers.py": ["/accounts/models.py"], "/accounts/models.py": ["/accounts/regex.py"]}
|
19,801,560
|
ohwani/molla
|
refs/heads/master
|
/accounts/models.py
|
# from django.contrib.auth.models import AbstractUser
# class User(AbstractUser):
# pass
from django.db import models
from django.core.validators import RegexValidator
from .regex import RegEx, Message
import re
class User(models.Model):
email = models.EmailField(
validators=[RegexValidator(RegEx['email'], Message['email'])])
password = models. CharField(max_length=1000, null=True)
def __str__(self):
return self.email
class Meta:
db_table = 'users'
|
{"/accounts/views.py": ["/accounts/serializers.py", "/accounts/models.py"], "/accounts/serializers.py": ["/accounts/models.py"], "/accounts/models.py": ["/accounts/regex.py"]}
|
19,801,561
|
ohwani/molla
|
refs/heads/master
|
/accounts/views.py
|
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import generics
from .serializers import UserSerializer
from .models import User
# Create your views here.
'''viewset 이용 '''
from rest_framework import viewsets
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
'''FBV api_view decorator 이용'''
# @api_view(['GET', 'POST'])
# def userList(request):
# if request.method == 'GET':
# users = User.objects.all()
# serializer = UserSerializer(users, many=True)
# return Response(serializer.data)
# elif request.method == 'POST':
# serializer = UserSerializer(data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data)
# @api_view(['GET', 'PUT', 'DELETE'])
# def userDetail(request, pk):
# if request.method == 'GET':
# user = User.objects.get(id=pk)
# serializer = UserSerializer(user, many=False)
# return Response(serializer.data)
# elif request.method == 'PATCH':
# user = User.objects.get(id=pk)
# serializer = UserSerializer(instance=user, data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data, status=201)
# return Response(serializer.errors, status=400)
# else:
# user = User.objects.get(id=pk)
# user.delete()
# return Response(serializer.data, status=204)
'''generics.py + mixin'''
# class UserListMixins(generics.ListCreateAPIView):
# queryset = User.objects.all()
# serializer_class = UserSerializer
# class UserDetailMixins(generics.RetrieveUpdateDestroyAPIView):
# queryset = User.objects.all()
# serializer_class = UserSerializer
'''CBV apiview'''
# class UserListAPIView(APIView):
# def get(self, request):
# users = User.objects.all()
# serializer = UserSerializer(users, many=True)
# def post(self, request):
# serializer = UserSerializer(data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data)
# class UserDetailAPIView(APIView):
# def get_object(self, pk):
# return get_object_or_404(User, pk=pk)
# def get(self, request, pk, format=None):
# user = self.get_object(pk)
# serializer = USerSerializer(user)
# return Response(serializer.data)
# def put(self, request, pk):
# user = self.get_object(pk)
# serializer = UserSerializer(user, data=request.data)
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data)
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# def delete(self, request, pk):
# user = self.get_object(pk)
# user.delete()
# return Response(status=status.HTTP_204_NO_CONTENT)
|
{"/accounts/views.py": ["/accounts/serializers.py", "/accounts/models.py"], "/accounts/serializers.py": ["/accounts/models.py"], "/accounts/models.py": ["/accounts/regex.py"]}
|
19,801,562
|
ohwani/molla
|
refs/heads/master
|
/accounts/urls.py
|
from django.urls import path, include
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('viewset', views.UserViewSet)
urlpatterns = [
path('', include(router.urls)),
# path('', views.accountsOverview, name="account-overview"),
# path('user-list/', views.userList, name="user-list"),
# path('user-list/<int:pk>/', views.userDetail, name="user-detail"),
# path('user-create/', views.userCreate, name="user-create"),
# path('user-update/<int:pk>/', views.userUpdate, name="user-update"),
# path('user-delete/<int:pk>/', views.userDelete, name="user-delete"),
# path('userdetail/<int:pk>/', views.userDetail, name="user-Detail"),
# path('userlist/', views.userDetail, name="user-Detail"),
# path('user/', views.UserListMixins.as_view()),
# path('userdetail/<int:pk>/', views.UserDetailMixins.as_view()),
]
# from django.urls import path, include
# from . import views
# urlpatterns = [
# # FBV
# path('user/', views.UserListAPIView.as_view()),
# path('user/<int:pk>/',views.UserDetailAPIView.as_view()),
# ]
|
{"/accounts/views.py": ["/accounts/serializers.py", "/accounts/models.py"], "/accounts/serializers.py": ["/accounts/models.py"], "/accounts/models.py": ["/accounts/regex.py"]}
|
19,801,563
|
ohwani/molla
|
refs/heads/master
|
/accounts/serializers.py
|
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
# def validate_email(self, attrs):
# email = User.objects.filter(email=attrs)
# if email.exists():
# raise serializers.ValidationError('This email already exists')
# return attrs
def validate(self, attrs):
email = User.objects.filter(email=attrs['email'])
if email.exists():
raise serializers.ValidationError('This email already exists')
return attrs
|
{"/accounts/views.py": ["/accounts/serializers.py", "/accounts/models.py"], "/accounts/serializers.py": ["/accounts/models.py"], "/accounts/models.py": ["/accounts/regex.py"]}
|
19,810,576
|
lauutt/finanza
|
refs/heads/master
|
/createreport.py
|
from fpdf import FPDF
import datetime
class PDF(FPDF):
def header(self):
# Logo
self.image('lucicoin.png', 10, 8, 33)
# Arial bold 15
self.set_font('Arial', 'B', 15)
# Move to the right
self.cell(80)
# Title
self.cell(100, 10, 'Resume from Lucicoin', 1, 0, 'C')
# Line break
self.ln(40)
# Page footer
def footer(self):
# Position at 1.5 cm from bottom
self.set_y(-15)
# Arial italic 8
self.set_font('Arial', 'I', 8)
# Page number
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
def createpdf(stockslist):
now = datetime.datetime.now()
dt_string = now.strftime("%d%m%Y %H%M")
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
pdf.cell(0, 10, 'Resumen creado en: '+str(now), 0, 1)
for i in stockslist:
pdf.cell(0, 10, i , 0, 1)
pdf.output('hola.pdf', 'F')
|
{"/finanza.py": ["/createrp.py"]}
|
19,811,675
|
taoky/OJSandbox
|
refs/heads/master
|
/main.py
|
#!/usr/bin/env python3
import os
import sys
import sandbox
import file
import langSupport
from judge import JudgeResult
def OJRun():
lPlayers = file.listOfPlayers()
lProblems = file.listOfProblems()
for thisPlayer in lPlayers:
relaPath = file.getPlayerDirectory(thisPlayer)
if not os.path.isdir(relaPath):
print("Ignored %s: Not a directory." % thisPlayer)
continue
lSources = file.listOfPlayerSources(thisPlayer)
for thisSource in lSources:
sourceRelaPath = relaPath + thisSource
filename, fileExtension = os.path.splitext(thisSource)
if not os.path.isfile(sourceRelaPath):
print("Ignored %s: Not a file." % sourceRelaPath)
continue
elif not langSupport.langType(fileExtension.lower()):
print("Ignored %s: Unsupported file extension." % sourceRelaPath)
continue
elif not filename in lProblems:
print("Ignored %s: Cannot find Problem %s." % (sourceRelaPath, filename))
continue
config = file.loadProblemConfig(filename)
res = sandbox.safeJudge(filename, fileExtension, relaPath, config)
print('{} on {}: {}'.format(thisPlayer, config['title'], res))
def OJReset():
file.cleanupWorkspace()
if __name__ == '__main__':
if len(sys.argv) >= 2:
if sys.argv[1] == 'cleanup':
OJReset()
exit(0)
OJRun()
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,676
|
taoky/OJSandbox
|
refs/heads/master
|
/judge.py
|
class JudgeResult:
# 0: No exceptions
AC = 0
WA = 1
OK = 99
# 100: Runtime exceptions
RE = 100
TLE = 101
MLE = 102
FSE = 103
# 200: Compilation exceptions
CE = 200
FTE = 201
# 800: Internal exceptions
IE = 800
AV = 801
# 900: Miscellaneous
UNKNOWN = 999
INFO = {
AC: 'Accepted',
WA: 'Wrong answer',
OK: 'OK',
RE: 'Runtime error',
MLE: 'Memory limit exceeded',
TLE: 'Time limit exceeded',
FSE: 'File size error',
CE: 'Compile error',
FTE: 'Invalid file type',
IE: 'Internal error',
#AV: 'Access violation', don't tell this
AV: 'Runtime error',
UNKNOWN: 'Unknown error'
}
@staticmethod
def stringBase(res):
return JudgeResult.INFO.get(res, 'Unknown result')
def isOK(s):
OKcode = [JudgeResult.AC, JudgeResult.WA, JudgeResult.OK]
try:
return s.value in OKcode
except AttributeError:
return s in OKcode
def __init__(self, value, res = None):
self.value = value
self.res = res
def __str__(self):
return JudgeResult.stringBase(self.value)
class JudgeError(Exception, JudgeResult):
def __init__(self, value, res = None):
self.value = value
self.res = res
def __str__(self):
return JudgeResult.stringBase(self.value)
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,677
|
taoky/OJSandbox
|
refs/heads/master
|
/DockerJudge/web/util.py
|
import os
def removeHiddenFiles(li):
return [i for i in li if not i.startswith('.')]
# def filterDir(li):
# return [i for i in li if os.path.isdir(i)]
def getAllProblems():
return sorted(next(os.walk('/problems'))[1])
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,678
|
taoky/OJSandbox
|
refs/heads/master
|
/langSupport.py
|
import file
COMPILED = 1
INTERPRETED = 2
MIXED = 3
UNKNOWN = 0
# Just leave the classfication here in case they're needed later
langs = {
'.c': COMPILED,
'.cpp': COMPILED,
#'.py': INTERPRETED,
}
# '%i' is input file
# '%o' is output file
# '%e' is executable
compileHelper = {
'.c': ['/usr/bin/gcc', '-Wall', '-O3', '%i', '-o', '%o'],
'.cpp': ['/usr/bin/g++', '-Wall', '-O3', '%i', '-o', '%o'],
'.py': ['/bin/cp', '%i', '%o'],
'.java': ['javac', '%i', '-o', '%o']
}
executeHelper = {
'.c': ['%e'],
'.cpp': ['%e'],
'.py': ['python3', '%e'],
'.java': ['javaw', '%e']
}
dockerExe = ['sudo', file.backendExe]
# dockerHelper has a ddifferrennt format from other helpers!
dockerHelper = {
'dir': ['-c', '%'],
'src': ['-e', '%'],
'stdin': ['-i', '%'],
'stdout': ['-o', '%'],
'stderr': [], # This is not implemented yet
'timeout': ['-t', '%'],
'memory': ['-m', '%'],
'noseccomp': ['--disable-seccomp'],
'multiprocess': ['--allow-multi-process'],
'copyback': ['--copy-back', '%']
#'command': ['--exec-command', '--', '%']
}
def langType(lang):
try:
return langs[lang]
except KeyError:
return UNKNOWN
def formatHelper(helper, **args):
fdict = {}
mapper = [('%i', 'infile'), ('%o', 'outfile'), ('%e', 'exefile')]
for fkey, akey in mapper:
try:
fdict[fkey] = args[akey]
except KeyError:
pass
return [fdict.get(key, key) for key in helper]
def formatDockerHelper(command, **args):
res = dockerExe[:]
try:
while args['dir'][-1] == '/':
args['dir'] = args['dir'][:-1]
except KeyError:
pass
for key in args:
try:
arg = [i if i != '%' else str(args[key]) for i in dockerHelper[key]]
res += arg
except KeyError:
pass
if not command is None:
res += ['--exec-command', '--'] + command
return res
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,679
|
taoky/OJSandbox
|
refs/heads/master
|
/DockerJudge/judger/tasks.py
|
import subprocess
from celery import Celery
import time, random # for debug
app = Celery('tasks',broker='amqp://admin:mypass@rabbit:5672',backend='redis://redis:6379')
@app.task(name="judgeApp.judge", bind=True)
def judge(self, runProg):
self.update_state(state="JUDGING")
# cp = subprocess.run(["/judgeApp/safeJudger", "-i", "/dev/null", "-o", "/dev/null", "--", runProg], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
# return (cp.stdout.split("\n"), cp.stderr.split("\n"))
time.sleep(5)
#self.update_state(state="SUCCESS")
return {"result": "AC", "time": random.randint(1, 100), "mem": random.randint(1, 200)}
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,680
|
taoky/OJSandbox
|
refs/heads/master
|
/Players/Python-TLE/00001.py
|
# Python version of TLE
while True:
pass
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,681
|
taoky/OJSandbox
|
refs/heads/master
|
/sandbox.py
|
import os
from shutil import copy
import subprocess
import compare
import file
import langSupport
from judge import JudgeResult, JudgeError
infoFile = file.workDir
def writeResult(res, fe, reason, i):
res.append((i, reason))
if fe is None:
fe = reason
return fe
def executeProgram(command, **options):
try:
cp = subprocess.run(command, **options)
except subprocess.TimeoutExpired:
return JudgeResult(JudgeResult.TLE)
if cp.returncode != 0:
return JudgeResult(JudgeResult.RE)
return JudgeResult(JudgeResult.OK)
def executeProgramDocker(command, **options):
if not 'dir' in options:
options['dir'] = file.getRunDir()
running = langSupport.formatDockerHelper(command, **options)
pwd = os.getcwd()
cp = subprocess.run(running, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
res = cp.stdout.split('\n')
if cp.returncode != 0:
#print(cp.stderr)
res[0] = 'IE'
return JudgeResult(getattr(JudgeResult, res[0].strip()))
def plainJudge(program, codeType, infile, outfile, **config):
inRedir = file.inFileName
outRedir = file.outFileName
copy(infile, file.getRunDir() + inRedir)
#istream = open(inRedir, 'r')
#ostream = open(outRedir, 'w')
#proFileName = os.path.splitext(i[0])[0]
runHelper = langSupport.executeHelper[codeType]
running = langSupport.formatHelper(runHelper, exefile=program)
#runResult = executeProgram(running, stdin=istream, stdout=ostream, timeout=config['timeout'] / 1000.0)
#runResult = executeProgramDocker(running, src=program, stdin=inRedir, stdout=outRedir,
runResult = executeProgramDocker(None, dir=file.getRunDir(), src=program,
stdin=file.getRunDir() + inRedir, stdout=file.getRunDir() + outRedir,
timeout=config['timeout'], memory=config['ram'])
rp = runResult.value
#istream.close()
#ostream.close()
forwardResults = [JudgeResult.RE, JudgeResult.TLE, JudgeResult.MLE, JudgeResult.FSE]
if rp in forwardResults:
file.safeRemove(file.getRunDir() + inRedir)
file.safeRemove(file.getRunDir() + outRedir)
return JudgeResult(rp)
copy(file.getRunDir() + outRedir, os.getcwd())
compareMethod = compare.getCompareMethod(config["compare"])
cp = compareMethod(outfile, file.runDir + outRedir)
file.safeRemove(outRedir) # cleanup
if cp == False:
return JudgeResult(JudgeResult.WA)
return JudgeResult(JudgeResult.AC)
def judgeProcess(sourceFileName, sourceFileExt, directory, problemConfig):
# WARNING: IT IS UNSAFE NOW!
exefileName = 'out'
rsourceFileName = file.getRunDir() + exefileName
rsourceCodeName = directory + sourceFileName + sourceFileExt
results = []
try:
compileHelper = langSupport.compileHelper[sourceFileExt.lower()][:]
#compiling = langSupport.formatHelper(compileHelper, infile=rsourceCodeName, outfile=rsourceFileName)
compiling = langSupport.formatHelper(compileHelper, infile=sourceFileName+sourceFileExt, outfile=exefileName)
except KeyError as e:
return JudgeError(JudgeResult.FTE)
#cps = subprocess.run(compiling, bufsize=0, timeout=10)
cps = executeProgramDocker(compiling, dir=file.getRunDir(), src=rsourceCodeName,
stdin='/dev/null', stdout='/dev/null',
timeout=5000, memory=128, noseccomp=None, multiprocess=None, copyback=exefileName)
if not JudgeResult.isOK(cps.value):
return JudgeError(JudgeResult.CE, results)
proFiles = file.getProblemFiles(sourceFileName)
firstError = None
for i in proFiles:
infile = file.getProblemDirectory(sourceFileName) + i[0]
outfile = file.getProblemDirectory(sourceFileName) + i[1]
proFileName = os.path.splitext(infile)[0]
result = plainJudge(exefileName, sourceFileExt.lower(), infile, outfile, **problemConfig)
firstError = writeResult(results, firstError, result.value, proFileName)
if not firstError is None:
break
if firstError is None:
firstError = JudgeResult.WA
os.remove(exefileName) # remove the compiler file
return JudgeResult(firstError, results)
def safeJudge(sourceFileName, sourceFileExt, directory, problemConfig):
try:
# Forward everything
return judgeProcess(sourceFileName, sourceFileExt, directory, problemConfig)
except JudgeError as e:
# Cleanup
keys = ['exe', 'in', 'out']
for i in keys:
try:
os.remove(e.res[i])
except KeyError:
pass
return e.value, None
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,682
|
taoky/OJSandbox
|
refs/heads/master
|
/compare.py
|
#!/usr/bin/env python3
import os
import sys
import filecmp
def trim(l):
try:
while l[-1] == '':
l.pop()
except:
return []
return l
def lineCompare(file1, file2):
with open(file1, 'r') as a, open(file2, 'r') as b:
linesA, linesB = trim([l.rstrip() for l in a]), trim([l.rstrip() for l in b])
return linesA == linesB
def strictCompare(file1, file2):
return filecmp.cmp(file1, file2, shallow=False)
if __name__ == "__main__":
try:
if len(sys.argv) == 3:
if os.path.isfile(sys.argv[1]) and os.path.isfile(sys.argv[2]):
print(lineCompare(sys.argv[1], sys.argv[2]))
else:
raise ValueError('Not files')
else:
raise ValueError('Bad arguments')
except ValueError as e:
sys.exit(e)
##############################
methods = {
"strict": strictCompare,
"line": lineCompare
}
def getCompareMethod(conf):
try:
return methods[conf]
except KeyError:
raise NotImplementedError
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,683
|
taoky/OJSandbox
|
refs/heads/master
|
/DockerJudge/web/worker.py
|
import os
from celery import Celery
#env=os.environ
#CELERY_BROKER_URL=env.get('CELERY_BROKER_URL','redis://localhost:6379'),
#CELERY_RESULT_BACKEND=env.get('CELERY_RESULT_BACKEND','redis://localhost:6379')
# def make_celery(app):
# celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
# celery.conf.update(app.config)
# TaskBase = celery.Task
# class ContextTask(TaskBase):
# abstract = True
# def __call__(self, *args, **kwargs):
# with app.app_context():
# return TaskBase.__call__(self, *args, **kwargs)
# celery.Task = ContextTask
# return celery
celery = Celery('judgeApp',broker='amqp://admin:mypass@rabbit:5672',backend='redis://redis:6379',include=['judgeApp.tasks'])
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,684
|
taoky/OJSandbox
|
refs/heads/master
|
/file.py
|
import os
import subprocess as sub
import json
import shutil as sh
workDir = os.getcwd() + '/'
runDir = None
resourceDir = os.getcwd() + '/Backend/'
initExe = resourceDir + 'init.sh'
backendExe = resourceDir + 'main'
inFileName = 'in.tmp'
outFileName = 'out.tmp'
def createWorkspace():
global runDir
try:
cp = sub.run([initExe], stdout=sub.PIPE, universal_newlines=True)
except FileNotFoundError:
raise
except:
# Not implemented yet
raise
if cp.returncode != 0:
# This may be a bit confusing but just use as a wordaround
raise FileNotFoundError("Failed to create workspace")
runDir = cp.stdout.split(':')[-1].strip()
if not os.path.isdir(runDir):
raise FileNotFoundError("Failed to create workspace")
sh.copy(backendExe, runDir)
def cleanupWorkspace():
global runDir
try:
cp = sub.run([initExe, 'cleanup'], stdout=sub.PIPE, universal_newlines=True)
except FileNotFoundError:
raise
except:
# Not implemented yet
raise
if cp.returncode != 0:
# This may be a bit confusing but just use as a wordaround
raise FileNotFoundError('Failed to cleanup workspace')
def getRunDir():
global runDir
if runDir is None:
createWorkspace()
if runDir[-1] != '/':
runDir += '/'
return runDir
def safeRemove(f):
try:
os.remove(f)
return True
except FileNotFoundError:
return False
def removeHiddenFiles(li):
return [i for i in li if not i.startswith('.')]
def listOfPlayers():
return sorted(removeHiddenFiles(os.listdir("Players")))
def listOfProblems():
return sorted(removeHiddenFiles(os.listdir("Problems")))
def listOfPlayerSources(playerName):
return sorted(removeHiddenFiles(os.listdir(getPlayerDirectory(playerName))))
def getProblemDirectory(problemName):
return "Problems/" + problemName + "/"
def getPlayerDirectory(playerName):
return "Players/" + playerName + "/"
def loadProblemConfig(problemName):
with open(getProblemDirectory(problemName) + "config.json", "r") as f:
config = json.loads(f.read())
f.close()
return config
def getProblemFiles(problemName):
ins = [i for i in os.listdir(getProblemDirectory(problemName)) if os.path.splitext(i)[1] == '.in']
ins.sort()
outs = [os.path.splitext(i)[0] + ".out" for i in ins]
res = [(ins[i], outs[i]) for i in range(len(ins))]
for i in outs:
if not os.path.exists(getProblemDirectory(problemName) + i):
raise FileNotFoundError("Problem is not configured properly. {} not found.".format(getProblemDirectory(problemName) + i))
return res
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,811,685
|
taoky/OJSandbox
|
refs/heads/master
|
/DockerJudge/web/app.py
|
import os
from flask import Flask
from flask import url_for
from flask import request
from flask import render_template
from worker import celery
from util import getAllProblems
from celery.result import AsyncResult
import celery.states as states
import redis
env = os.environ
app = Flask(__name__)
r = redis.StrictRedis(host="redis", port=6379, db=0)
# app.config.update(
# CELERY_BROKER_URL="amqp://admin:mypass@rabbit:5672",
# CELERY_RESULT_BACKEND="redis://localhost:6379",
# CELERY_INCLUDE=['judgeApp.tasks']
# )
# celery = make_celery(app)
def result_parse(res):
template_result = {}
if res.state == "PENDING":
# return "Queuing..."
status = "Queuing"
elif res.state == "JUDGING":
# return "Judging..."
status = "Judging"
else:
# return str(res.result)
status = "Finished"
template_result = res.result
if not isinstance(template_result, dict):
template_result = {"result": "AC", "time": 0, "mem": 0}
return status, template_result
@app.route("/submit", methods=["POST", "GET"])
def submit():
if request.method == "GET":
return render_template("submit.html", problems=getAllProblems())
else:
param = {"problem": request.form["problem"],
"language": request.form["language"],
"code": request.form["code"]}
return task_add(param)
@app.route('/task_add/<string:param>') # for debug only
def task_add(param):
task = celery.send_task('judgeApp.judge', args=[param], kwargs={})
return "<a href='{url}'>check status of {id} </a>".format(id=task.id,
url=url_for('check_task',id=task.id,_external=True))
@app.route('/check/<string:id>')
def check_task(id):
res = celery.AsyncResult(id)
status, template_result = result_parse(res)
# template_result = {} # to the template
# if res.state == "PENDING":
# # return "Queuing..."
# status = "Queuing"
# elif res.state == "JUDGING":
# # return "Judging..."
# status = "Judging"
# else:
# # return str(res.result)
# status = "Finished"
# template_result = res.result
return render_template("check_task.html", id=id, status=status, result=template_result)
@app.route('/')
def index():
return "Flask is working now."
@app.route('/status')
def status():
records = []
for key in r.scan_iter("celery-task-meta-*"):
id = key.decode("ascii")[len("celery-task-meta-"):]
id_url = url_for('check_task', id=id, _external=True)
id_res = celery.AsyncResult(id)
status, template_result = result_parse(id_res)
if status == "Finished":
result = template_result["result"]
else:
result = ""
records.append({"id": id, "id_url": id_url, "status": status, "result": result})
return render_template("status.html", records=records)
if __name__ == '__main__':
app.run(debug=env.get('DEBUG', True),
port=int(env.get('PORT', 5001)),
host=env.get('HOST', '0.0.0.0')
)
|
{"/main.py": ["/sandbox.py", "/config.py", "/file.py", "/langSupport.py", "/debug.py", "/judge.py"], "/langSupport.py": ["/file.py", "/config.py"], "/file.py": ["/debug.py"], "/sandbox.py": ["/compare.py", "/config.py", "/file.py", "/langSupport.py", "/judge.py", "/debug.py"]}
|
19,866,909
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/handtracking.py
|
import cv2
import mediapipe as mp
import time
import numpy as np
import math
from PIL import Image
from self_made import (
handsign_judge,
time_mesure,
drowing,
img_processing,
)
class Handtracking:
def __init__(self):
super().__init__()
self.mp_drawing = mp.solutions.drawing_utils
self.mp_hands = mp.solutions.hands
# For webcam input:
self.hands = self.mp_hands.Hands(
min_detection_confidence=0.5, min_tracking_confidence=0.5)
self.cap = cv2.VideoCapture(0)
#オリジナル#########################
self.font = cv2.FONT_HERSHEY_SIMPLEX #fontのところを元のまま書くと、cv2.FONT~ の.に反応してしまう
##カメラ映像を録画 フレームレートが合わないので直さないといけない
#fourcc=cv2.VideoWriter_fourcc(*'mp4v') # 書き出すコーデック名
#out=cv2.VideoWriter('output.mp4',fourcc, 8.0, (640,480))#書き込むファイル 謎 フレームレート 縦横比?
self.ACTWIN_PXL_WIDTH=int(500) # 眼鏡に取り付けるディスプレイのウィンドウのピクセル数
self.ACTWIN_PXL_HIGHT=int(500)
self.ACTWIN_L_NAME='active window left' #ウィンドウの名前
self.ACTWIN_R_NAME='active window right'
self.LAYER_NUM = 5#レイヤーの枚数 最低5枚 LAYER_NUM-4が表示できるobjectのレイヤー数
self.PUPILLARY_DISTANCE=60.0 #瞳と瞳の距離(PD)[mm]
self.VERTEX_DISTANCE=12 #(角膜)頂点間距離{mm} 通常12mmくらい 角膜の頂点とレンズ後方の距離
self.DISPLAY_WIDTH=100 #眼鏡に取り付けるディスプレイの横幅[mm]
self.DISPLAY_HIGHT=100
self.PALM_WIDTH=70 #人差し指の付け根の中心から小指の付け根の中心までの距離[mm]
self.MAX_CAMERA_SIDE_ANGLE = math.pi/3 #カメラの横方向の画角[rad]
self.MAX_CAMERA_VERTICAL_ANGLE = math.pi/3 #カメラの縦方向の画角[rad]
if __name__=="__main__":
cv2.namedWindow(self.ACTWIN_L_NAME) # これで一つwindowが開く 特に変数に代入したりする必要はない
cv2.namedWindow(self.ACTWIN_R_NAME)
#左右のディスプレイに表示する真っ白の画像を生成
self.WHITE_IMG = np.full((self.ACTWIN_PXL_WIDTH,self.ACTWIN_PXL_HIGHT,3),255)
self.ALPHA_IMG = np.insert(self.WHITE_IMG,3,0,axis=2)
self.WHITE_IMG = np.insert(self.WHITE_IMG,3,255,axis=2)#ここ普通に最初から全要素255にした方がいい
self.IMG_LEFT_LAYER_PATH_0 = 'Image_layer/ImgLeft_0.png'
self.IMG_RIGHT_LAYER_PATH_0 = 'Image_layer/ImgRight_0.png'
cv2.imwrite(self.IMG_LEFT_LAYER_PATH_0,self.WHITE_IMG)
cv2.imwrite(self.IMG_RIGHT_LAYER_PATH_0,self.WHITE_IMG)
self.ImgLeft = cv2.imread(self.IMG_LEFT_LAYER_PATH_0,-1)#これをベースにしてレイヤーを合成する
self.ImgRight = cv2.imread(self.IMG_RIGHT_LAYER_PATH_0,-1)#これをベースにする
self.LeftLayers = [self.ImgLeft]
self.RightLayers = [self.ImgRight]
#合成するレイヤー
for layer_num in range(self.LAYER_NUM-1):
img_left_layer_path = f'Image_layer/ImgLeft_{layer_num+1}.png'
img_right_layer_path = f'Image_layer/ImgRight_{layer_num+1}.png'
cv2.imwrite(img_left_layer_path,self.ALPHA_IMG)
cv2.imwrite(img_right_layer_path,self.ALPHA_IMG)
ImgLeft = cv2.imread(img_left_layer_path,-1)#-1をつけるとアルファチャンネルも読み込める
ImgRight = cv2.imread(img_right_layer_path,-1)
self.LeftLayers.append(ImgLeft)
self.RightLayers.append(ImgRight)
#合成して表示するかどうか(初期状態)
self.wheather_merging_layer = [1]#ベースのImg_Left(もしくはRight)_layer_0は1
for layer_num in range(self.LAYER_NUM-3):
self.wheather_merging_layer.append(1)
self.wheather_merging_layer.append(0)#後ろから2番目(modeを表示するレイヤー)は初期状態では非表示
self.wheather_merging_layer.append(1)
self.ins_timeMusure = time_mesure.timeMesure()
self.ins_jesture = handsign_judge.handsignJudgeClass(self.PALM_WIDTH, (self.MAX_CAMERA_SIDE_ANGLE, self.MAX_CAMERA_VERTICAL_ANGLE), self.ins_timeMusure)#先にこっち
self.lefteye_process = img_processing.plr_trns(self.VERTEX_DISTANCE, (self.DISPLAY_WIDTH,self.DISPLAY_HIGHT) , (self.ACTWIN_PXL_WIDTH, self.ACTWIN_PXL_WIDTH), -self.PUPILLARY_DISTANCE/2)
self.righteye_process = img_processing.plr_trns(self.VERTEX_DISTANCE, (self.DISPLAY_WIDTH,self.DISPLAY_HIGHT) , (self.ACTWIN_PXL_WIDTH, self.ACTWIN_PXL_WIDTH), self.PUPILLARY_DISTANCE/2)
self.ins_drowing = drowing.drowing(self.LeftLayers, self.RightLayers, self.ins_jesture, self.lefteye_process, self.righteye_process, (self.ACTWIN_PXL_WIDTH, self.ACTWIN_PXL_WIDTH), self.wheather_merging_layer, self.ins_timeMusure)#インスタンスも引き数にできる
########################################
def run(self):#selfつけないと外から動かない
while self.cap.isOpened():
success, image = self.cap.read()
if not success:
print("Ignoring empty camera frame.")
# If loading a video, use 'break' instead of 'continue'.
continue
# Flip the image horizontally for a later selfie-view display, and convert
# the BGR image to RGB.
image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
# To improve performance, optionally mark the image as not writeable to
# pass by reference.
image.flags.writeable = False
results = self.hands.process(image)
# Draw the hand annotations on the image.
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
self.mp_drawing.draw_landmarks( #これで画像に書き込んでる cv2を使っている
image, hand_landmarks, self.mp_hands.HAND_CONNECTIONS)
#オリジナル################################
#タプルhanc_landmarks内の辞書型landmarkを取得
#辞書型を入れるにはタプル型の方が良い為 またパフォーマンスもタプル型の穂王が良い為、タプル型を使用
for idx, landmark in enumerate(hand_landmarks.landmark):
# 番号とz座標を標準出力に表示 なんでlandmark[z]じゃダメなのか後で調べる
self.ins_jesture.setting(idx,landmark.x,landmark.y,landmark.z)
#ここでprint(ins_jesture.result())などとしてins_jestureを呼び出してしまうと
# 次のdrowing_3 D viewが反応しなくなってしまうのでやらな い
self.ins_drowing.drowing_3Dview("drowing_hand")#手のひらを描画する場合は第二引き数に"drowing_hand"を
##############################################
#保存
for layer_num in range(self.LAYER_NUM):
cv2.imwrite(f'./Image_layer/ImgLeft_{layer_num}.png',self.LeftLayers[layer_num])#merge後のlayer0の保存は一週遅れる
cv2.imwrite(f'./Image_layer/ImgRight_{layer_num}.png',self.RightLayers[layer_num])
#合成 drowing内でやった方がいいかも
bg_L = Image.open(self.IMG_LEFT_LAYER_PATH_0).convert("RGBA")
bg_R = Image.open(self.IMG_RIGHT_LAYER_PATH_0).convert("RGBA")
for layer_num in range(self.LAYER_NUM-1):
if self.ins_drowing.wheather_merging_layer[layer_num+1]:#whether_mergingが9でないなら
img_L = Image.open(f'Image_layer/ImgLeft_{layer_num+1}.png').convert("RGBA")
img_R = Image.open(f'Image_layer/ImgRight_{layer_num+1}.png').convert("RGBA")
bg_L = Image.alpha_composite(bg_L,img_L)
bg_R = Image.alpha_composite(bg_R,img_R)
bg_L.save('Image_layer/ImgLeft_0.png')
bg_R.save('Image_layer/ImgRight_0.png')
#for文を使わないで、縦に羅列した方がfpsが早かった気がする
#表示
if __name__=="__main__":
Left = cv2.imread(self.IMG_LEFT_LAYER_PATH_0)#同じインスタンス名で読み込むと画像が重なってしまう
Right = cv2.imread(self.IMG_RIGHT_LAYER_PATH_0)
cv2.imshow(self.ACTWIN_L_NAME,Left)
cv2.imshow(self.ACTWIN_R_NAME,Right)
cv2.imshow('MediaPipe Hands', image)
#
if cv2.waitKey(5) & 0xFF == 27 or not __name__=="__main__":#外部から実行されていても一周で終わる
break
#最後にこれを実行
def final(self):
self.hands.close()
self.cap.release()
#out.release()#オリジナル 録画
if __name__=="__main__":
handtrackingApp = Handtracking()
handtrackingApp.run()
handtrackingApp.final()
|
{"/main.py": ["/handtracking.py"]}
|
19,866,910
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/self_made/img_processing.py
|
#画面に表示するオブジェクトを立体的に見えるように加工するモジュール
import math
class plr_trns: #polar transformation
def __init__( #x=0はカメラ映像中心,y=0はカメラ映像上辺
self,
vertex_distance,#目の頂点と表示するディスプレイの距離
display_shape,#ディスプレイの横と縦はば[mm]
window_pxl_shape,#ディスプレイのピクセル数
eye_coordinate, #眉間を0としたときの目のx座標 カメラでもok
):
self.vertex_distance = vertex_distance
self.display_width = display_shape[0]
self.display_hight = display_shape[1]
self.window_pix_width = window_pxl_shape[0]
self.window_pix_hight = window_pxl_shape[1]
self.eye_coordinate = eye_coordinate #目の高さが左右非対称の場合はyも変える必要があるので、その時はeye_coordinateをxとyのリストにする
#高さself.VERTEX_DISTANCE、底辺DISPLAY_WIDTHの二等辺三角形を
#半径self.VERTEX_DISTANCE、位相arctan{DISPLAY_WIDTH/ (self.VERTEX_DISTANCE/2) }
#の扇とする
#ディスプレイで表示できる横方向の最大角度をもとめる 単位はラジアン
self.max_display_angle_x = math.atan(self.display_width / (2*self.vertex_distance))
self.max_display_angle_y = self.max_display_angle_x * (self.window_pix_hight/self.window_pix_width)
self.slided_position_x=0.0
self.slided_position_y=0.0
self.object_coordinate_x=0.0
self.object_coordinate_y=0.0
#点の位置を3Dに見えるように移動させるメソッド
def point_processing(
self,
original_position,#リスト[x,y,z] 直交座標
):
if original_position[2] < 10:#zが目の前1cmより後方なら
return
#オブジェクトの座標を目の位置に合わせてずらす
self.slided_position_x = (
original_position[0] #原点をずらした方向と反対側に値が変わる
- self.eye_coordinate #目の位置に合わせて原点を変更
)
self.slided_position_y = original_position[1]
#画面に表示するx座標=水平方向角度 y座標=垂直方向角度 となる
self.object_coordinate_x = (
math.atan(self.slided_position_x / original_position[2]) / self.max_display_angle_x
#↑角度/表示できる最大角度 画面の端から端までを1としていくつか
* self.window_pix_width
+ self.window_pix_width/2 #原点を画面中央に
)
self.object_coordinate_y = (
#↓このままだとyが下方向になるので-1を掛ける
-math.atan(self.slided_position_y / original_position[2]) /self.max_display_angle_y
* self.window_pix_hight
+ self.window_pix_hight /2
)
return int(self.object_coordinate_x),int(self.object_coordinate_y)
#intにしないとcv2で描画できない
|
{"/main.py": ["/handtracking.py"]}
|
19,866,911
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/Object_info/semicon_01/create.py
|
#このコードではmaterialは指定できません。(20210316)
#直接objファイルを触ってmaterialの指定をしました。(20210316)
#書けるように変更してください
#Siの半導体の2*2*2の立方体の中の原子
atom_pos = [
#八隅の原子
[1.0, 1.0, 1.0],
[1.0, -1.0, 1.0],
[1.0, 1.0, -1.0],
[1.0, -1.0, -1.0],
[-1.0, 1.0, 1.0],
[-1.0, 1.0, -1.0],
[-1.0, -1.0, 1.0],
[-1.0, -1.0, -1.0],
#各面の中心の原子
[1.0, 0, 0],
[0, 1.0, 0],
[0, 0, 1.0],
[-1.0, 0, 0],
[0, -1.0, 0],
[0, 0, 1-.0],
#立方体の中の原子
[0.5, 0.5, 0.5],
[0.5, -0.5, -0.5],
[-0.5, -0.5, 0.5],
[-0.5, 0.5, -0.5],
]
import numpy as np
import math
semi_vS = []
print(math.cos(math.pi/6))
for semi in atom_pos:
semi_v = []
semi_v.append([str(semi[0]),str(semi[1] + 0.1),str(semi[2])])
for t in range(6):#真横(y軸に垂直)に見たとき、正六角形になるように
semi_v.append( [ str(semi[0]+math.cos(math.pi/6*t)*0.1), str(semi[1]+0.05), str(semi[2]+math.sin(math.pi/6*t)*0.1) ] )
for t in range(6):
semi_v.append( [ str(semi[0]+math.cos(math.pi/6*t)*0.1), str(semi[1]-0.05), str(semi[2]+math.sin(math.pi/6*t)*0.1) ] )
semi_v.append([str(semi[0]),str(semi[1]-0.1),str(semi[2])])
semi_vS.append(semi_v)
with open("./object_info/semicon_01/semicon_01.obj","w") as f:
#頂点
for wr_semi_v in semi_vS:
for v in wr_semi_v:
f.write("v ")
for v_pos in v:
f.write(v_pos)
f.write(" ")
f.write("\n")
#辺
i=0
for semi_v in semi_vS:#個数を調べるのを省略するためだけ
for j in range(5):#上の六つの三角形
f.write(f"f {i*14+1} {i*14+j+2} {i*14+j+3} \n")
f.write(f"f {i*14+1} {i*14+7} {i*14+2} \n")
#drowしたら変な形に面がついてしまったので、テスト
for j in range(5):#側面 回転方向統一しないと、ちゃんと描画できないことがある
f.write(f"f {i*14+j+2} {i*14+j+8} {i*14+j+9} {i*14+j+3}\n")
f.write(f"f {i*14+2} {i*14+8} {i*14+13} {i*14+7}\n")
for j in range(5):#下の六つの三角形
f.write(f"f {i*14+14} {i*14+j+8} {i*14+j+9} \n")
f.write(f"f {i*14+14} {i*14+8} {i*14+13}\n")
i +=1
|
{"/main.py": ["/handtracking.py"]}
|
19,866,912
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/self_made/time_mesure.py
|
import time
#指定したジェスチャーをしてからどれだけ時間が経過したか返す
class timeMesure:
def __init__(self):
super().__init__()
self.target_name=str
self.time_infos={None:{}} #{target_name:{startTime: ,rapTime: }}
#handSignTextの読み取り誤差を考慮して、違うhandsignになったあと5秒以内に同じhandsignをした場合は、タイマーをリセットせずに計測した値を返す
def targetCount(self,target_name):
#記録していないならセットして0を返す
if not (target_name in self.time_infos):
self.target_name = target_name
self.time_infos={self.target_name:{}}
self.time_infos[self.target_name]["startTime"] = time.time()
return 0.0
self.target_name = target_name
self.time_infos[self.target_name]["rapTime"] = time.time() - self.time_infos[self.target_name]["startTime"] #time.time()で現在時刻
#5秒以上経過していたらリセット
if self.time_infos[self.target_name]["rapTime"] > 5:
self.time_infos[self.target_name] = {}
self.time_infos[self.target_name]["startTime"] = time.time()
self.time_infos[self.target_name]["rapTime"] = 0.0
return self.time_infos[self.target_name]["rapTime"]
|
{"/main.py": ["/handtracking.py"]}
|
19,866,913
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/self_made/handsign_judge.py
|
import numpy as np
import math
from self_made import time_mesure
class handsignJudgeClass:
def __init__(self,palm_width,max_angle,time_mesure_ins):
self.palm_width=palm_width#手のひらの横幅
self.halfof_palm_width = palm_width / 2 #手のひらの横幅の半分
self.MHA = max_angle[0] #max_horaizontal_angle横方向の画角
self.MVA = max_angle[1] #max_vertical_angle縦方向の画角
self.tm = time_mesure_ins
self.landmarks = {}
self.landmark_x=0.0
self.landmark_y=0.0
self.landmark_z=0.0
self.palm_direction_info="a"##手のひらの裏表を判別 palm_directionで使用
self.middlefingure_vector_x=0.0
self.middlefingure_vector_y=0.0
self.middlefingure_vector_z=0.0
self.middlefingure_vector_1ofabs=0.0
self.middlefingure_vector=[]
#finger_raising
self.FingerRaising_value = 0.0
self.x_n=0.0
self.x_a=0.0
self.x_q=0.0
self.y_n=0.0
self.y_a=0.0
self.y_q=0.0
self.y_n=0.0
self.y_a=0.0
self.y_q=0.0
self.FingerRaising_info = {}
#absdis_3D
self.abdis3D_result = float()
#absdis_2D
self.abdis2D_result = float()
#palm_dipth
self.palm_dipth_info=0.0
#rect_trans
self.rectTransMagn = None
self.rectTrans_result = []
#keyboard_typing
self.fingerVec = []
#handSingText
self.handSingText_result="noSign"
self.handSingText_result_backup="noSign"
#まずこれを呼び出して設定
def setting(self,idx,landmark_x,landmark_y,landmark_z):#landmark):#
self.idx=idx
#self.landmark=landmark
self.landmark_x = -landmark_x+0.5 #カメラ映像中央をx=0とする 画面が鏡写しなので、値を反転
self.landmark_y = -(landmark_y-0.5) * self.MHA/self.MVA
#カメラ映像中央をy=0とし、縦方向角度と単位をそろえる 下向きがyだったので、反転して上向きをyに
self.landmark_z = landmark_z
this_idx_position=[self.landmark_x,self.landmark_y,self.landmark_z]
self.landmarks[self.idx] = this_idx_position #self.landmark
#手のひらの裏表を判別
def palm_direction(self):#向きdirection
if np.abs(self.landmarks[5][0]-self.landmarks[17][0]) > np.abs(self.landmarks[0][2]-self.landmarks[9][2])/3:#手のひらの縦幅(カメラ映像上)の1/3以上差があるなら
if self.landmarks[5][0]-self.landmarks[17][0] < 0:#右手で人差し指の付け根が小指の付け根より左にあるなら
self.palm_direction_info = "reverse"
else :
self.palm_direction_info = "obverse"
else:
self.palm_direction_info = "sidewayspalm"
return self.palm_direction_info
#中指の付け根のの向きを判別
def midfin_vec(self):
self.middlefingure_vector_x=self.landmarks[9][0] - self.landmarks[0][0]
self.middlefingure_vector_y=self.landmarks[9][1] - self.landmarks[0][1]
self.middlefingure_vector_z=self.landmarks[9][2] - self.landmarks[0][2]
#(1/ベクトルの絶対値)を求める
self.middlefingure_vector_1ofabs = 1 / self.abdis_3D(9,0)
#各ベクトルに(1/ベクトルの絶対値)を掛ける
self.middlefingure_vector_info = [
self.middlefingure_vector_1ofabs*self.middlefingure_vector_x,
self.middlefingure_vector_1ofabs*self.middlefingure_vector_y,
self.middlefingure_vector_1ofabs*self.middlefingure_vector_z
]
return self.middlefingure_vector_info
def FingerRaising(self):
#法線ベクトルn(x_n,y_n,z_n) の 点A(x_a,y_a,z_a) を含む面S
#任意の面上の点P(x_p,y_p,z_p) を考える
#APとnは垂直 ∴AP・n=0
#空間内の任意の点Q(x_q,y_q,z_q) を考えると AQ・n>0なら面Sよりnベクトル方向に正
for i in range(5,18,4):
self.x_n,self.y_n,self.z_n=self.midfin_vec()
self.x_a=self.landmarks[i][0]
self.x_q=self.landmarks[i+3][0]
self.y_a=self.landmarks[i][1]
self.y_q=self.landmarks[i+3][1]
self.z_a=self.landmarks[i][2]
self.z_q=self.landmarks[i+3][2]
self.FingerRaising_value = (
self.x_n*(self.x_q-self.x_a)+
self.y_n*(self.y_q-self.y_a)+
self.z_n*(self.z_q-self.z_a)
)
#キーを付け根の番号にしてFingerRaising_infoに指の曲げ伸ばしを代入
if self.FingerRaising_value - self.abdis_3D(9,0)/2 >= 0:
self.FingerRaising_info[str(i)] = 1
#手のひらの縦の長さの1/3>付け根との差>0 の範囲内なら
elif self.FingerRaising_value > 0:
self.FingerRaising_info[str(i)] = 0
else :
self.FingerRaising_info[str(i)] = -1
return self.FingerRaising_info
def abdis_3D(self,abdis3D_mknum1,abdis3D_mknum2):#absolute distance 3D 2点間のx,y,z方向の絶対値
self.abdis3D_result = math.sqrt(
((self.landmarks[abdis3D_mknum1][0] - self.landmarks[abdis3D_mknum2][0]))**2 +
((self.landmarks[abdis3D_mknum1][1] - self.landmarks[abdis3D_mknum2][1]))**2 +
((self.landmarks[abdis3D_mknum1][2] - self.landmarks[abdis3D_mknum2][2]))**2
)
return self.abdis3D_result
def abdis_2D(self,abdis2D_mknum1,abdis2D_mknum2):#absolute distance 2D 2点間のx,y方向の絶対値
self.abdis2D_result = math.sqrt(
((self.landmarks[abdis2D_mknum1][0] - self.landmarks[abdis2D_mknum2][0]))**2 +
((self.landmarks[abdis2D_mknum1][1] - self.landmarks[abdis2D_mknum2][1]))**2
)
return self.abdis2D_result
#指の関節と関節のベクトル 後でhandsignに移動
def fin_vec_equation(self,joint_num=None,step=1):#equation:方程式 joint_num:第何関節から step:何関節飛びにか
self.fin_vec_equ_result = []#返り値初期化
for fin_num in range(joint_num,21,4):#親指から
self.fingerVec =[
self.rect_trans()[fin_num][0] - self.rect_trans()[fin_num+step][0],
self.rect_trans()[fin_num][1] - self.rect_trans()[fin_num+step][1],
self.rect_trans()[fin_num][2] - self.rect_trans()[fin_num+step][2],
]
#方向ベクトル(a,b,c)において
#(x-x0)/a = (y-y0)/b = (z-z0)/c より
#bx-ay = bx0-ay0 と cy-bz = cy0-bz0 が成り立つ
#[[b,-a,0] [x, [bx0-ay0,
# [0,c,-b]] ・ y, = cy0-bz0]
# z]
self.fin_vec_equ_result.append([
[
[self.fingerVec[1],-1*self.fingerVec[0],0],
[0,self.fingerVec[2],-1*self.fingerVec[1]],
],
[
self.fingerVec[1]*self.rect_trans()[fin_num][0] - self.fingerVec[0]*self.rect_trans()[fin_num][1],
self.fingerVec[2]*self.rect_trans()[fin_num][2] - self.fingerVec[1]*self.rect_trans()[fin_num][2],
]
])
return self.fin_vec_equ_result
#手のひらの横幅から手の距離を求める
def palm_dipth(self):
self.halfof_shwplmwid = self.abdis_3D(5,17) / 2 #5は人差し指の付け根 17は小指の付け根
self.halfof_shwplmwid_angle = self.MHA * self.halfof_shwplmwid #画角×画像の横幅に対して何倍か で手のひらの幅の角度の半分が求まる
#z[mm] = 手のひらの横幅の半分[mm] / sin(手のひらの角度の半分)
self.palm_dipth_info = self.halfof_palm_width / math.sin(self.halfof_shwplmwid_angle)
return self.palm_dipth_info
#直交座標変換 rectangular coodinate transform
def rect_trans(self):
#倍率を求める
self.rectTransMagn = 2*self.halfof_palm_width / self.abdis_3D(5,17)#magnification
self.rectTrans_result = [] #初期化
#手首のz座標をpalm_dipthとし、極座標を直交座標として扱っている 後で直す
for rect_trans_num in range(0,21):
self.rectTrans_result.append( [
self.landmarks[rect_trans_num][0]*self.rectTransMagn,
self.landmarks[rect_trans_num][1]*self.rectTransMagn,
self.landmarks[rect_trans_num][2]*self.rectTransMagn + self.palm_dipth(),
] )
return self.rectTrans_result
#現在のフレームのハンドサイン名
def handsignText(self):
if self.FingerRaising() == {"5":1, "9":0, '13':-1, '17':-1}:
self.handSingText_result = "3D_tranceform"
elif self.palm_direction() == "reverse":
if self.FingerRaising() == {'5': 1, '9': -1, '13': -1, '17': -1}:
self.handSingText_result = "choice_mode_move"
elif self.FingerRaising() == {'5': 1, '9': -1, '13': -1, '17': 1}:
self.handSingText_result = "choice_mode_cleck"
elif self.FingerRaising() == {'5': 1, '9': 1, '13': 1, '17': 1}:
if (
self.handSingText_result_backup != "keyboard_wait_start" and
self.handSingText_result_backup != "keyboard_wait_01" and
self.handSingText_result_backup != "keyboard_wait_02"
):
self.handSingText_result = "keyboard_wait_start"
elif self.handSingText_result_backup == "keyboard_wait_01":
self.handSingText_result = "keyboard_wait_02"
#"keyboard_wait_start"か"keyboard_wait_01"ならそのまま
elif self.FingerRaising() == {'5': -1, '9': -1, '13': -1, '17': -1}:
if self.handSingText_result_backup == "keyboard_wait_start":
self.tm.targetCount("keyboard_wait") #time_mesureモジュールで開始時間設定
self.handSingText_result = "keyboard_wait_01"
elif self.handSingText_result_backup == "keyboard_wait_01": #さっき握ったままならそのまま
pass
elif self.handSingText_result_backup == "keyboard_wait_02":
if self.tm.targetCount("keyboard_wait") < 5: #開始時間設定から5秒以内なら
self.handSingText_result = "keyboard_open"
else:
self.handSingText_result="握りこぶし コマンドなし"
elif self.palm_direction() == "obverse":
if self.FingerRaising() == {'5': 1, '9': -1, '13': -1, '17': -1}:
if self.tm.targetCount("shortcut_1") > 2:#2秒以上経過したなら
self.handSingText_result = "shortcut_1"
else:
self.handSingText_result = "shortcut_1_wait"
if self.FingerRaising() == {'5': 1, '9': 1, '13': -1, '17': -1}:
if self.tm.targetCount("shortcut_2") > 2:
self.handSingText_result = "shortcut_2"
else:
self.handSingText_result = "shortcut_2_wait"
if self.FingerRaising() == {'5': 1, '9': 1, '13': 1, '17': -1}:
if self.tm.targetCount("shortcut_3") > 2:
self.handSingText_result = "shortcut_3"
else:
self.handSingText_result = "shortcut_3_wait"
if self.FingerRaising() == {'5': 1, '9': 1, '13': 1, '17': 1}:
if self.tm.targetCount("shortcut_4") > 2:
self.handSingText_result = "shortcut_4"
else:
self.handSingText_result = "shortcut_4_wait"
elif self.palm_direction() == "sidewayspalm":
self.handSingText_result = "sidewayspalm"
self.handSingText_result_backup = self.handSingText_result
return self.handSingText_result
|
{"/main.py": ["/handtracking.py"]}
|
19,866,914
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/Object_info/keyboard.py
|
#キーボードオブジェクトのjsonファイルを作るためだけのコード
import json
# {
# [ [[x,y,z],キーの名前], [], [], ....], 一番下の暖のキー(スペースキー)
# [ ], 下から二番目の段のキー
# [ ],
# [ ],
# [ ],
# [ ] ENTERキーなど
# }
keynames = [
["z","x","c","v","b","n","m",",",".","/"],
["a","s","d","f","g","h","j","k","l",";"],
["q","w","e","r","t","y","u","i","o","p"],
["1","2","3","4","5","6","7","8","9","0"],
]
dict_1={}
with open("Object_info/keyboard.json","w") as KEYBOARD_JSON_FILE:
KEYBOARD_BUTTON = [ [-20,5,40],[20,5,40],[20,2,0],[-20,2,0] ] #ボタンの原点はボタンの下部真ん中
KEYBOARD_SPACE = [ [-50,5,40],[50,5,40],[50,2,0],[-50,2,0] ]
#enterはキーボード原点から 見ずらいから、隣のキーと1cm空ける
KEYBOARD_ENTER = [ [260,50,245],[300,50,245],[300,7,55],[260,7,55] ]
#キーボードのボタンを描画
#1段目 今はスペースキーのみ
verList=[]
horoList=[]
keybox=[]
for i in range(0,4):
keybox.append([
KEYBOARD_SPACE[i][0],
KEYBOARD_SPACE[i][1],
KEYBOARD_SPACE[i][2]
])
horoList.append([keybox,"space"])
verList.append(horoList)
#普通のキー 2段目から5段目
for k in range(1,5):#縦方向
horoList=[]
for j in range(0,10):#横方向
keybox=[] #キーの四角
for i in range(0,4):
keybox.append( [
KEYBOARD_BUTTON[i][0]+j*50-225,
KEYBOARD_BUTTON[i][1]+k*10+4,
#z方向にはさらに手のひらの深さも足す
KEYBOARD_BUTTON[i][2]+k*50+5
] )
horoList.append( [keybox, keynames[k-1][j]] )
print([keybox, keynames[k-1][j]],"\n")
verList.append(horoList)
horoList=[]
keybox=[]
for i in range(0,4):
keybox.append([
KEYBOARD_ENTER[i][0],
KEYBOARD_ENTER[i][1],
KEYBOARD_ENTER[i][2]
])
horoList.append([keybox,"enter"])
verList.append(horoList)
dict_1["key"] = verList
json.dump(dict_1,KEYBOARD_JSON_FILE)
|
{"/main.py": ["/handtracking.py"]}
|
19,866,915
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/self_made/drowing.py
|
import cv2
import numpy as np
import json
import math
import traceback
from PIL import Image
#cv2で描画するときはアルファ値も指定しないといけないので注意
class drowing:#モードの記述や画面クリアなどで、相対座標ではなく、絶対座標から指定してしまっている imgproccesingとか使って相対座標で描けるように
FONT1 = cv2.FONT_HERSHEY_COMPLEX
FONT2 = cv2.FONT_HERSHEY_COMPLEX_SMALL
FONT_COLOR = [0,0,0,255]
CLEAR_COLOR = [255,255,255,255]
ALPHA_COLOR = [0,0,0,0]
CHOICE_COLOR = [0,255,0,255]
KEYBOARD_BASE = [ [-250,50,250],[300,50,250],[300,0,0],[-250,0,0] ]#keyboardの大きさ[mm]
KEYBOARD_BASE_COLOR = [0,0,0,255]
KEYBOARD_BUTTON_COLOR = [255,255,0,255]
NOMATERIAL_COLOR = [255,0,0,255]#オブジェクトを表示するとき、表示するmaterialが指定されていない時の色
def __init__(self,Leftlayers=None,Rightlayers=None,judgeInstance=None,imgProInstance_L=None,imgProInstance_R=None,window_pxl_shape=[[],[]],wheather_merging_layer=[],timeMesureInstance=None):
self.ImgLeft_Base = Leftlayers[0]#レイヤーのインデックスが大きいほど手前に idxとレイヤーの前後関係はhandtracking.pyの合成順で定義
self.ImgRight_Base = Rightlayers[0]
self.ImgLeft_ObjectLayers = Leftlayers[1:-3]
self.ImgRight_ObjectLayers = Rightlayers[1:-3]
self.ImgLeft_Keyboard = Leftlayers[-3]
self.ImgRight_Keyboard = Rightlayers[-3]
self.ImgLeft_Mode = Leftlayers[-2]
self.ImgRight_Mode = Rightlayers[-2]
self.ImgLeft_Hand = Leftlayers[-1]
self.ImgRight_Hand = Rightlayers[-1]
self.judge_instance = judgeInstance #handsign_judgeのインスタンス
self.imgProInstance_L = imgProInstance_L #左目のimg_processingのインスタンス
self.imgProInstance_R = imgProInstance_R #右目のimg_processingのインスタンス
self.timeMeasureInstance = timeMesureInstance#時間を測るインスタンス 間違えて呼び出すとカウントがスタートしてバグの元になるので注意
self.window_pxl_width = window_pxl_shape[0]#表示する画像の幅
self.window_pxl_hight = window_pxl_shape[1]
self.wheather_merging_layer = wheather_merging_layer #それぞれのlayerをマージするかどうか
self.palm_dipth_info = None
self.object_position_infos={} #オブジェクトの座標 手のひらの横幅を基準に考える
self.before_pro_object = [] #加工前のオブジェクトの頂点の座標のリスト
self.eyeL_ofter_pro_object = [] #加工後のオブジェクトの頂点の座標のリスト
self.eyeR_ofter_pro_object = []
self.present_HandSignText = "not"
self.HandSignText_backup = "not"
self.current_mode = []#現在有効なモード
#readOBJ
self.readOBJ_path_backup=None
self.readOBJ_result_backup={}#keyがpathの辞書
# 参考元 http://www.cloud.teu.ac.jp/public/MDF/toudouhk/blog/2015/01/15/OBJTips/
self.numVertices = 0
self.numUVs = 0
self.numNormals = 0
self.numFaces = 0
self.vertices = []
self.uvs = []
self.normals = []
self.vertexColors = []
self.faceVertIDs = []
self.uvIDs = []
self.normalIDs = []
#choiceObject
self.objectCriteriaPositions = {} #{0:[x0,y0,z0],1:[x1,y1,z1],2:[],..} Criteria=基準,目安 self.ImgRignt_objectLayersのインデックス番号と同じkey名
#↑要は 当たり判定の立方体 の中心の点
#drowing_keyboard
self.LOADED_KEYBOARD_JSON = None
self.key_position = None
self.slided_key_positions_ver = []#縦方向に区切るリスト slided_key_positionに代入するときしか使わない
self.slided_key_positions = []
#drowing_hand 関数からいじれるようにしたかったので、クラス変数ではなくインスタンス変数にした
self.hand_landmarks_color=[255,0,0,255]
#drowing_3Dview
self.COResult_ret=None
#画面クリア
def imgReset(self,layerName,resetRange="all",imgReset_whatLayer=0):
if layerName == "base":
self.imgReset_layer = [self.ImgLeft_Base,self.ImgRight_Base]
if resetRange == "all":
cv2.rectangle(self.imgReset_layer[0],(0,0),(500,500),drowing.CLEAR_COLOR,thickness=-1)
cv2.rectangle(self.imgReset_layer[1],(0,0),(500,500),drowing.CLEAR_COLOR,thickness=-1)
elif resetRange == "main":#テキストを表示しない場所
cv2.fillConvexPoly(self.imgReset_layer[0],np.array([
(0,0),(200,0),(200,50),(200,100),(500,100),(500,500),(0,500)
]),drowing.CLEAR_COLOR)
cv2.fillConvexPoly(self.imgReset_layer[1],np.array([
(0,0),(0,50),(200,50),(200,100),(500,100),(500,500),(0,500)
]),drowing.CLEAR_COLOR)
else:
if layerName == "object":
self.imgReset_layer = [self.ImgLeft_ObjectLayers[imgReset_whatLayer],self.ImgRight_ObjectLayers[imgReset_whatLayer]]
elif layerName == "mode":
self.imgReset_layer = [self.ImgLeft_Mode,self.ImgRight_Mode]
elif layerName == "hand":
self.imgReset_layer = [self.ImgLeft_Hand,self.ImgRight_Hand]
elif layerName == "keyboard":
self.imgReset_layer = [self.ImgLeft_Keyboard,self.ImgRight_Keyboard]
else:
try:
raise Exception
except:
traceback.print_exc()
print(layerName,"を受け取りました。リセットする画像が正しく指定されていません")
#baseでなければ透明で塗りつぶし
if resetRange == "all":
cv2.rectangle(self.imgReset_layer[0],(0,0),(500,500),drowing.ALPHA_COLOR,thickness=-1)
cv2.rectangle(self.imgReset_layer[1],(0,0),(500,500),drowing.ALPHA_COLOR,thickness=-1)
elif resetRange == "prehansig":
#透明の長方形で塗りつぶし
cv2.rectangle(self.imgReset_layer[0],(200,0),(500,50),drowing.ALPHA_COLOR,thickness=-1)
cv2.rectangle(self.imgReset_layer[1],(200,0),(500,50),drowing.ALPHA_COLOR,thickness=-1)
elif resetRange == "current_mode":
cv2.rectangle(self.imgReset_layer[0],(200,50),(500,100),drowing.ALPHA_COLOR,thickness=-1)
cv2.rectangle(self.imgReset_layer[1],(200,50),(500,100),drowing.ALPHA_COLOR,thickness=-1)
elif resetRange == "main":#テキストを表示しない場所
cv2.fillConvexPoly(self.imgReset_layer[0],np.array([
(0,0),(200,0),(200,50),(200,100),(500,100),(500,500),(0,500)
]),drowing.ALPHA_COLOR)
cv2.fillConvexPoly(self.imgReset_layer[1],np.array([
(0,0),(0,50),(200,50),(200,100),(500,100),(500,500),(0,500)
]),drowing.ALPHA_COLOR)
#ぐるぐる(進捗インジゲータ)をobjectlayersの一番上のレイヤーに表示
def drowProgressIndicator(self,progress=float,whatObjectLayerNum=int):#0.0<=progress<=1.0
cv2.ellipse(
self.ImgLeft_ObjectLayers[whatObjectLayerNum],
(int(self.window_pxl_width/2),int(self.window_pxl_hight/2)),
(int(self.window_pxl_width/20),int(self.window_pxl_hight/20)),
270,
0,
-int(progress*360),
[55+int(progress*200),455-int(progress*200),0,125],
5,
cv2.LINE_AA
)
cv2.ellipse(
self.ImgRight_ObjectLayers[whatObjectLayerNum],
(int(self.window_pxl_width/2),int(self.window_pxl_hight/2)),
(int(self.window_pxl_width/20),int(self.window_pxl_hight/20)),
270,
0,
-int(progress*360),
[55+int(progress*200),455-int(progress*200),0,125],
5,
cv2.LINE_AA
)
#objファイルをリストにする
def readOBJ(self,path):
#すでに読み込まれていたものであれば
if path in self.readOBJ_result_backup:#self.readOBJ_result_backup.key()と同じ意味
return self.readOBJ_result_backup[path]
self.vertices = []
self.uvs = []
self.normals = []
self.faceVertIDs = []
self.uvIDs = []
self.normalIDs = []
self.vertexColor = []
self.readOBJ_groupName = "nanashi"#groupがobjファイルに記載されていない場合は、これがkeyになる
self.mtlName = None
self.readOBJ_result_backup[path] = {}#{ path:{mtllib:materialファイル名 , groupName1:[] , groupName2:[] , .... } }
for line in open(path, "r"):
vals = line.split()
if len(vals) == 0:
continue
elif vals[0] == "v":
v = vals[1:4]
self.vertices.append(v)
if len(vals) == 7:
vc = vals[4:7]
self.vertexColors.append(vc)
self.numVertices += 1
elif vals[0] == "vt":
vt = vals[1:3]
self.uvs.append(vt)
self.numUVs += 1
elif vals[0] == "vn":
vn = vals[1:4]
self.normals.append(vn)
self.numNormals += 1
elif vals[0] == "f":
fvID = []
uvID = []
nvID = []
for f in vals[1:]:
w = f.split("/")
if self.numVertices > 0:
fvID.append(int(w[0])-1)#IDの値を一つ下げて、0から始まるようにしている
elif self.numUVs > 0:
uvID.append(int(w[1])-1)
elif self.numNormals > 0:
nvID.append(int(w[2])-1)
self.faceVertIDs.append(fvID)
self.uvIDs.append(uvID)
self.normalIDs.append(nvID)
self.numFaces += 1
elif vals[0] == "g":#グループなら
#まず古いgroupNameで辞書に登録してから
self.readOBJ_result_backup[path][self.readOBJ_groupName] =[ self.vertices, self.uvs, self.normals, self.faceVertIDs, self.uvIDs, self.normalIDs, self.vertexColors, self.mtlName ]
#key名を変える
self.readOBJ_groupName = vals[1]
#新しいkey名(group名)で辞書を作る
self.readOBJ_result_backup[path][self.readOBJ_groupName] = {}
self.vertices = []
self.uvs = []
self.normals = []
self.faceVertIDs = []
self.uvIDs = []
self.normalIDs = []
self.vertexColor = []
elif vals[0] == "usemtl":#material名なら
self.mtlName = vals[1]
elif vals[0] == "mtllib":#materialファイル名なら
self.readOBJ_result_backup[path]["mtllib"] = vals[1]
#辞書に登録しきれていない、最後のグループを辞書に登録
self.readOBJ_result_backup[path][self.readOBJ_groupName] =[ self.vertices, self.uvs, self.normals, self.faceVertIDs, self.uvIDs, self.normalIDs, self.vertexColors, self.mtlName ]
return self.readOBJ_result_backup[path]
def readMTL(self,path):
self.readMTL_materialName = "nanashi"
self.materlalInfos={self.readMTL_materialName:{}}#{material名1:{"Kd":[RGB(0.0~1.0)], "":[], ...}, material名2:{"Kd":[], ...}, ...}
for line in open(path,"r"):#このやり方でも開ける
vals = line.split()
if len(vals) == 0:
continue
if vals[0] == "Kd":#ディフューズ(拡散反射)なら
self.materlalInfos[self.readMTL_materialName]["Kd"] = vals[1:]
elif vals[0] == "newmtl":#新しいmaterialなら
self.readMTL_materialName = vals[1]#material名を変えて
self.materlalInfos[self.readMTL_materialName] = {}#新しい辞書を作成
else :#他にもいっぱいあるけど、とりあえず
continue
return self.materlalInfos
def drowing_keyboard(self):
self.palm_dipth_info = self.judge_instance.palm_dipth()#rect_trans_info[0][2]と一緒だからこれ要らないかも
self.rect_trans_info = self.judge_instance.rect_trans()
self.object_position_infos["keyboard"] = self.palm_dipth_info
cv2.putText(self.ImgLeft_Mode,str(self.object_position_infos["keyboard"]),(0,40),drowing.FONT1,1,(0,0,0),2)
cv2.putText(self.ImgRight_Mode,str(self.object_position_infos["keyboard"]),(0,40),drowing.FONT1,1,(0,0,0),2)
self.eyeL_ofter_pro_object=[]#編集後オブジェクト情報を初期化
self.eyeR_ofter_pro_object=[]
for i in range(0,4):
self.before_pro_object=[
drowing.KEYBOARD_BASE[i][0],
drowing.KEYBOARD_BASE[i][1]+self.rect_trans_info[0][1],
drowing.KEYBOARD_BASE[i][2]+self.palm_dipth_info
]
self.eyeL_ofter_pro_object.append( self.imgProInstance_L.point_processing(self.before_pro_object) )
self.eyeR_ofter_pro_object.append( self.imgProInstance_R.point_processing(self.before_pro_object) )
if (not None in self.eyeL_ofter_pro_object) and (not None in self.eyeR_ofter_pro_object):#描画距離内なら
cv2.fillConvexPoly(self.ImgLeft_Keyboard,np.array(self.eyeL_ofter_pro_object),drowing.KEYBOARD_BASE_COLOR)
cv2.fillConvexPoly(self.ImgRight_Keyboard,np.array(self.eyeR_ofter_pro_object),drowing.KEYBOARD_BASE_COLOR)
with open("Object_info/keyboard.json") as KEYBOARD_JSON:
self.LOADED_KEYBOARD_JSON = json.load(KEYBOARD_JSON) #jsonとしてロード(読み込み)する必要あり
self.key_position = self.LOADED_KEYBOARD_JSON["key"]
for horolist in self.key_position:
for keybox_and_name in horolist:
self.eyeL_ofter_pro_object=[]
self.eyeR_ofter_pro_object=[]
self.slided_key_position_keyrect=[]#keyの四隅の座標
for keybox in keybox_and_name[0]:
self.before_pro_object = [
keybox[0],
keybox[1]+math.floor(self.rect_trans_info[0][1]),
keybox[2]+math.floor(self.palm_dipth_info),
]
self.slided_key_position_keyrect.append(self.before_pro_object)
self.eyeL_ofter_pro_object.append( self.imgProInstance_L.point_processing(self.before_pro_object) )
self.eyeR_ofter_pro_object.append( self.imgProInstance_R.point_processing(self.before_pro_object) )
if (not None in self.eyeL_ofter_pro_object) and (not None in self.eyeR_ofter_pro_object):#描画距離内なら
cv2.fillConvexPoly(self.ImgLeft_Keyboard,np.array(self.eyeL_ofter_pro_object),drowing.KEYBOARD_BUTTON_COLOR)#drowing.KEYBOARD_BUTTON_COLOR)
cv2.fillConvexPoly(self.ImgRight_Keyboard,np.array(self.eyeR_ofter_pro_object),drowing.KEYBOARD_BUTTON_COLOR)
self.slided_key_positions_ver.append([self.slided_key_position_keyrect,keybox_and_name[1]])#ずらしたキーボードの座標と名前を記録
self.slided_key_positions.append(self.slided_key_positions_ver)
def keybaord_typing(self):
self.typing_mat_2 = self.judge_instance.fin_vec_equation(3)#押したかどうか判別する行列の2行目まで(指の行列)と答えを取得
#テスト用 人差し指とキーボードのベースの交点
if (
self.judge_instance.rect_trans()[(1+1)*4-2][1] < self.slided_key_positions[4][0][0][0][1] and self.judge_instance.rect_trans()[(1+1)*4][1] > self.slided_key_positions[0][0][0][2][1] and
self.judge_instance.rect_trans()[(1+1)*4-2][2] < self.slided_key_positions[4][0][0][0][2] and self.judge_instance.rect_trans()[(1+1)*4][2] > self.slided_key_positions[0][0][0][2][2] and
self.judge_instance.rect_trans()[(1+1)*4-2][0] < self.slided_key_positions[1][9][0][0][0] and self.judge_instance.rect_trans()[(1+1)*4][0] > self.slided_key_positions[1][0][0][0][0]
):
print("人差し指キーボードの範囲内には入ってる 交点は",self.judge_instance.rect_trans()[(1+1)*4-2])
else:
print("入ってない")
self.test_space_cross = (
np.round(np.matrix([
self.typing_mat_2[1][0][0],
self.typing_mat_2[1][0][1],
[0,1,0],
])**-1)*
np.matrix([
np.round([self.typing_mat_2[1][1][0],0,0]),
np.round([self.typing_mat_2[1][1][1],0,0]),
np.round([self.slided_key_positions[0][0][0][0][1],0,0]),
])
)
#↓交点を標準出力
#print(
# "人差し指の向きは",self.typing_mat_2[1][0],"\n",
# "x",self.judge_instance.rect_trans()[(1+1)*4-2][0] ,self.slided_key_positions[1][9][0][0][0], self.slided_key_positions[1][0][0][0][0],"\n",
# "y",self.judge_instance.rect_trans()[(1+1)*4-2][1] , self.slided_key_positions[4][0][0][0][1],self.slided_key_positions[0][0][0][2][1],"\n",
# "z",self.judge_instance.rect_trans()[(1+1)*4-2][2] ,self.slided_key_positions[4][0][0][0][2], self.slided_key_positions[0][0][0][2][2],"\n",
# "スペースキーの高さは",self.slided_key_positions[0][0][0][0][1],"\n"
# "スペースキーの平面との交点は\n",
# self.test_space_cross,"\n"
#)
#交点を黒で表示
cv2.circle(self.ImgLeft_Hand, self.imgProInstance_L.point_processing([
self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0]
]),30,(0,0,0,255),5)
cv2.circle(self.ImgRight_Hand, self.imgProInstance_R.point_processing([
self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0]
]),30,(0,0,0,255),5)
#人差し指の直線を緑で表示
cv2.line(
self.ImgLeft_Hand,
self.imgProInstance_L.point_processing(
self.judge_instance.rect_trans()[6]
),
self.imgProInstance_L.point_processing(
self.judge_instance.rect_trans()[8]
),
(0,255,0,255),
3
)
cv2.line(
self.ImgRight_Hand,
self.imgProInstance_R.point_processing(
self.judge_instance.rect_trans()[6]
),
self.imgProInstance_L.point_processing(
self.judge_instance.rect_trans()[8]
),
(0,255,0,255),
3
)
if (
self.imgProInstance_L.point_processing([self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0]])
):
if (
self.imgProInstance_L.point_processing([self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0]])[0] > 100 and
self.imgProInstance_L.point_processing([self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0]])[0] < 400 and
self.imgProInstance_L.point_processing([self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0]])[1] > 100 and
self.imgProInstance_L.point_processing([self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0]])[1] < 400
):
print("交点が画面の中央付近! 交点は",self.test_space_cross[0,0],self.test_space_cross[1,0],self.test_space_cross[2,0])
cv2.imwrite("test/cross_result.png",self.ImgLeft_Hand)
for i in range(0,6):#keyの行
for j in range(0,11):#keyの列
for k in range(0,5):#指
self.mat = np.matrix([
self.typing_mat_2[k][0][0],
self.typing_mat_2[k][0][1],
[0,1,0],
])
self.cross_point = np.dot(#dotも*も列数行数が一致していないと計算できないっぽい
(np.round(self.mat**-1)),
np.matrix([
np.round([self.typing_mat_2[k][1][0],0,0]),
np.round([self.typing_mat_2[k][1][1],0,0]),
np.round([self.slided_key_positions[i][j][0][0][1],0,0]),
])
)
#print("keyの値",self.slided_key_positions[i][j][0][0][2])
#print(
# "\n真偽値の判断に使う値",
# self.judge_instance.rect_trans()[(k+1)*4-2][2],
# self.slided_key_positions[i][j][0][0][2] ,
# self.cross_point[1,0],
# self.judge_instance.rect_trans()[(k+1)*4-2][1] <= self.cross_point[1,0],
# self.slided_key_positions[i][j][0][0][0] <= self.cross_point[0][0]
#)
#cross_pointの中身は [ [x 0 0],[y 0 0],[z 0 0] ]
#slided_key_position[i][j][0]は
#左奥頂点0 右奥頂点1
#左手前頂点3 右手前頂点2
#x,zはキーボードの中yは手の高さ内
if (
(self.slided_key_positions[i][j][0][0][0] <= self.cross_point[0,0] ) and (self.cross_point[0,0] <= self.slided_key_positions[i][j][0][1][0] ) and
(self.slided_key_positions[i][j][0][0][2] <= self.cross_point[2,0] ) and (self.cross_point[2,0] <= self.slided_key_positions[i][j][0][3][2] ) and
(self.judge_instance.rect_trans()[(k+1)*4-2][1] <= self.cross_point[1,0] ) and ( self.cross_point[1,0] <= self.judge_instance.rect_trans()[(k+1)*4][1] )
):
print("指",k,self.slided_key_positions[i][j][1])
else:
#print(
# #"指",k,"の位置は",self.judge_instance.rect_trans()[(k+1)*4-2],self.judge_instance.rect_trans()[(k+1)*4],
# "指",k,"key",self.slided_key_positions[i][j][1],"打ってない 交点は",self.cross_point[0,0],self.cross_point[1,0],self.cross_point[2,0]
#)
pass
#mgnification:拡大 rotation:回転 taranslation:平行移動
#mtlFolderPathはobjファイルで指定している、mtlファイルのpath whatLayerNumは何番目のレイヤーか(0~)
def drowingOBJ(self,path,whatLayerNum=0,magnification=[1,1,1],rotation=[[1,0,0],[0,1,0],[0,0,1]],translation=[0,0,0],targets=["vertex"],mtlFolderPath="./Objct_info/"):
self.drowingOBJ_ObjFile = self.readOBJ(path)
self.drowingOBJ_materialFileName = self.drowingOBJ_ObjFile["mtllib"]#materialファイル名
self.drowingOBJ_materialS = self.readMTL(mtlFolderPath+self.drowingOBJ_materialFileName)#materialファイルに書かれたmaterialのリスト
for groupName in self.drowingOBJ_ObjFile:#各グループごとに描画する
if groupName == "mtllib":#materialファイル名なら、
continue
self.obj_vertices = self.drowingOBJ_ObjFile[groupName][0]
self.vertex_num = 0#カウント用変数
self.processed_obj_vertices_position = [ {},{} ] #imgprocessing.pyで加工後の左右の画面上の頂点の座標のリスト
for obj_vertex in self.obj_vertices:
obj_vertex=[#代入後のobj_vertexを別の変数にする方が、拡張しやすいかもしれない ただ、processing.pyとobj_vertexの移動を同時にやったらマジでこんがらがるからやめた方がいい
( rotation[0][0]*float(obj_vertex[0]) + rotation[0][1]*float(obj_vertex[1]) + rotation[0][2]*float(obj_vertex[2]) )*magnification[0] +translation[0],
( rotation[1][0]*float(obj_vertex[0]) + rotation[1][1]*float(obj_vertex[1]) + rotation[1][2]*float(obj_vertex[2]) )*magnification[1] +translation[1],
( rotation[2][0]*float(obj_vertex[0]) + rotation[2][1]*float(obj_vertex[1]) + rotation[2][2]*float(obj_vertex[2]) )*magnification[2] +translation[2],
]
if self.imgProInstance_L.point_processing(obj_vertex) and self.imgProInstance_R.point_processing(obj_vertex):#この真偽値で描画範囲内か判断する方法って良くないかもしれない
self.processed_obj_vertices_position[0][self.vertex_num] = self.imgProInstance_L.point_processing(obj_vertex)
self.processed_obj_vertices_position[1][self.vertex_num] = self.imgProInstance_R.point_processing(obj_vertex)
#targetにvertexが指定されているなら、この時一緒に頂点を描く
if ("vertex" in targets) and self.processed_obj_vertices_position[0][self.vertex_num] and self.processed_obj_vertices_position[1][self.vertex_num]:
cv2.circle(self.ImgLeft_ObjectLayers[whatLayerNum], self.processed_obj_vertices_position[0][self.vertex_num] ,1,(int(obj_vertex[2]*0.5), int(255-obj_vertex[2]*0.5), int(obj_vertex[2]*0.5) ))
cv2.circle(self.ImgRight_ObjectLayers[whatLayerNum], self.processed_obj_vertices_position[1][self.vertex_num] ,1,(int(obj_vertex[2]*0.5), int(255-obj_vertex[2]*0.5), int(obj_vertex[2]*0.5) ))
self.vertex_num += 1
#面
if "surface" in targets:
obj_surfaceS = self.drowingOBJ_ObjFile[groupName][3]
if self.drowingOBJ_ObjFile[groupName][-1]:#material情報があるなら、読み込む
self.drowingOBJ_material = self.drowingOBJ_materialS[ self.drowingOBJ_ObjFile[groupName][-1] ]#この時点では "Kd":[0.51~,0.44~,0.31~]
self.drowingOBJ_material = [int( float(self.drowingOBJ_material["Kd"][0]) *255),int( float(self.drowingOBJ_material["Kd"][1]) *255),int( float(self.drowingOBJ_material["Kd"][2]) *255),255]#アルファチャンネルを読みとれるのであれば、Aを変えた方がいい
else:#ないなら、NOMATERIAL_COLORにする
self.drowingOBJ_material = drowing.NOMATERIAL_COLOR
for obj_surface_vertices_IDs in obj_surfaceS:
self.drowingOBJ_processed_CurrentSurfaceVerticesPositions_L = []
self.drowingOBJ_processed_CurrentSurfaceVerticesPositions_R = []
#全ての頂点が描画範囲内なら
if set(obj_surface_vertices_IDs) <= set(list( self.processed_obj_vertices_position[0].keys() )):#ディスプレイ上の座標をsetに変換するのはfor文の外に出した方がいいかも 遅いから
for current_surface_vertices_ID in obj_surface_vertices_IDs:
#ディスプレイ上の座標をリストに格納
self.drowingOBJ_processed_CurrentSurfaceVerticesPositions_L.append( self.processed_obj_vertices_position[0][current_surface_vertices_ID] )
self.drowingOBJ_processed_CurrentSurfaceVerticesPositions_R.append( self.processed_obj_vertices_position[1][current_surface_vertices_ID] )
cv2.fillConvexPoly(
self.ImgLeft_ObjectLayers[whatLayerNum],
np.array(self.drowingOBJ_processed_CurrentSurfaceVerticesPositions_L),
self.drowingOBJ_material#ここのaの値をいい感じに調整して、面が重なると色が濃くなるようにしてもいいかも
)
cv2.fillConvexPoly(
self.ImgRight_ObjectLayers[whatLayerNum],
np.array(self.drowingOBJ_processed_CurrentSurfaceVerticesPositions_R),
self.drowingOBJ_material
)
#positionとobjectを照合してpositionと一致するself.objectLayersのインデックス番号を返す 戻り値の1番目は一致するものがあったかどうか
def choiceObject(self,position=list,hitRange=50):
for objectLayerNum in self.objectCriteriaPositions:
if (
abs(self.objectCriteriaPositions[objectLayerNum][0] - position[0]) < hitRange and
abs(self.objectCriteriaPositions[objectLayerNum][1] - position[1]) < hitRange and
abs(self.objectCriteriaPositions[objectLayerNum][2] - position[2]) < hitRange
):
return True,objectLayerNum
return None,None
#手を書く 現時点では点のみ
def drowing_hand_landmarks(self):
self.eyeL_ofter_pro_object=[]
self.eyeR_ofter_pro_object=[]
for transd_lndmrk in self.judge_instance.rect_trans():
if self.imgProInstance_L.point_processing(transd_lndmrk) and self.imgProInstance_R.point_processing(transd_lndmrk):#描画距離内なら
cv2.circle(self.ImgLeft_Hand, self.imgProInstance_L.point_processing(transd_lndmrk) ,3,self.hand_landmarks_color,2)
cv2.circle(self.ImgRight_Hand, self.imgProInstance_R.point_processing(transd_lndmrk) ,3,self.hand_landmarks_color,2)
#メインの関数 ここでは「各関数の呼び出し」と「関数を作るほどではない処理」のみ行う
def drowing_3Dview(self,mode=None):
self.present_HandSignText=self.judge_instance.handsignText()#present=現在の
self.imgReset("base","all")
if mode == "drowing_hand":
self.imgReset("hand","all")
self.drowing_hand_landmarks()
if self.HandSignText_backup != self.present_HandSignText: #1つ前のself.present_HandSignTextと違うなら modeレイヤーを上書き
self.imgReset("mode","prehansig")
self.HandSignText_backup = self.present_HandSignText
cv2.putText(self.ImgLeft_Mode,self.present_HandSignText,(200,40),drowing.FONT1,1,drowing.FONT_COLOR,2)
cv2.putText(self.ImgRight_Mode,self.present_HandSignText,(200,40),drowing.FONT1,1,drowing.FONT_COLOR,2)
if self.present_HandSignText == "keyboard_open":
if not "keyboard" in self.current_mode:
self.imgReset("mode","current_mode")
self.current_mode.append("keyboard")
self.drowing_keyboard()
cv2.putText(self.ImgLeft_Mode,str(self.current_mode),(200,80),drowing.FONT2,1,drowing.FONT_COLOR,2)
cv2.putText(self.ImgRight_Mode,str(self.current_mode),(200,80),drowing.FONT2,1,drowing.FONT_COLOR,2)
if (
"keyboard" in self.current_mode and#keyboardが存在して keyboardのspacekeyの座標より上下10cm,手前10cmから一番奥のキーまで、zkeyの左から/keyの右まで なら
self.judge_instance.rect_trans()[0][1] < self.slided_key_positions[0][0][0][0][1]+100 and self.judge_instance.rect_trans()[0][1] > self.slided_key_positions[0][0][0][0][1]-100 and
self.judge_instance.rect_trans()[0][2] < self.slided_key_positions[4][0][0][0][2] and self.judge_instance.rect_trans()[0][2] > self.slided_key_positions[0][0][0][0][2]-100 and
self.judge_instance.rect_trans()[0][0] < self.slided_key_positions[1][9][0][0][0] and self.judge_instance.rect_trans()[0][0] > self.slided_key_positions[1][0][0][0][0]
):
self.hand_landmarks_color=[0,0,255,255]#手の色を変える
self.keybaord_typing()
else:
self.hand_landmarks_color=[255,0,0,255]
#self.drowProgressIndicatorの引き数whatLayerNum と self.drowingOBJの引き数whatLayerNum と self.objectCriteriaPositionsのキー をここでは0としているが、将来的には自動で空いているlayerを指定するようにしたい
if self.present_HandSignText == "shortcut_4_wait":
self.drowProgressIndicator( self.timeMeasureInstance.targetCount("shortcut_4")/2, whatObjectLayerNum=0 )
elif self.present_HandSignText == "shortcut_4":
if not "3Dobject" in self.current_mode:
self.imgReset("object")
self.drowingOBJ("./Object_info/semicon_01/semicon_01.obj", 0, magnification=[100,100,100],translation=self.judge_instance.rect_trans()[5],targets=["surface"],mtlFolderPath="./Object_info/semicon_01/")
self.objectCriteriaPositions[0]=self.judge_instance.rect_trans()[5]
self.imgReset("mode")
self.current_mode.append("3Dobject")
cv2.putText(self.ImgLeft_Mode,str(self.current_mode),(200,80),drowing.FONT2,1,drowing.FONT_COLOR,2)
cv2.putText(self.ImgRight_Mode,str(self.current_mode),(200,80),drowing.FONT2,1,drowing.FONT_COLOR,2)
elif self.present_HandSignText == "3D_tranceform":
#フレミングの法則の形にlandmardを線でつなぐ オブジェクトを表示しているときだけ線でつないだ方がいいかも
cv2.line(
self.ImgLeft_Hand,
self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[4]),
self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[5]),
drowing.CHOICE_COLOR,
3,
)
cv2.line(
self.ImgLeft_Hand,
self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[8]),
self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[5]),
drowing.CHOICE_COLOR,
3,
)
cv2.line(
self.ImgLeft_Hand,
self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[12]),
self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[5]),
drowing.CHOICE_COLOR,
3,
)
cv2.line(
self.ImgRight_Hand,
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[4]),
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[5]),
drowing.CHOICE_COLOR,
3,
)
cv2.line(
self.ImgRight_Hand,
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[8]),
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[5]),
drowing.CHOICE_COLOR,
3,
)
cv2.line(
self.ImgRight_Hand,
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[12]),
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[5]),
drowing.CHOICE_COLOR,
3,
)
if ("3Dobject" in self.current_mode) and self.COResult_ret:#オブジェクトを表示しており、選択しているオブジェクトがあるなら
self.imgReset("object")
self.imgReset("mode")
self.current_mode.append("3Dobject")
self.objectCriteriaPositions[self.COResult_num]=self.judge_instance.rect_trans()[5]
#選択したobjectを変えるように
self.drowingOBJ(
path="./Object_info/semicon_01/semicon_01.obj",
whatLayerNum=self.choiced_objectLayerNum,
magnification=[100,100,100],
rotation=[ [0,-self.judge_instance.midfin_vec()[2],self.judge_instance.midfin_vec()[1] ],[ self.judge_instance.midfin_vec()[2],0,-self.judge_instance.midfin_vec()[0] ],[ -self.judge_instance.midfin_vec()[1],self.judge_instance.midfin_vec()[0],0 ] ],
translation=self.judge_instance.rect_trans()[5],#人差し指の付け根を基準にして表示
targets=["vertex","surface"],
mtlFolderPath="./Object_info/semicon_01/",
)
cv2.putText(self.ImgLeft_Mode,str(self.current_mode),(200,80),drowing.FONT2,1,drowing.FONT_COLOR,2)
cv2.putText(self.ImgRight_Mode,str(self.current_mode),(200,80),drowing.FONT2,1,drowing.FONT_COLOR,2)
elif self.present_HandSignText == "choice_mode_move" or self.present_HandSignText == "choice_mode_cleck":
cv2.circle(self.ImgLeft_Hand,self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[8]),10,drowing.CHOICE_COLOR,3)
cv2.circle(self.ImgRight_Hand,self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[8]),10,drowing.CHOICE_COLOR,3)
if self.present_HandSignText == "choice_mode_cleck":
cv2.circle(self.ImgLeft_Hand,self.imgProInstance_L.point_processing(self.judge_instance.rect_trans()[8]),20,drowing.CHOICE_COLOR,4)
cv2.circle(self.ImgRight_Hand,self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[8]),20,drowing.CHOICE_COLOR,4)
if (#右目の画面の設定のところに人差し指があるなら
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[8])[0] > self.window_pxl_width-100 and
self.imgProInstance_R.point_processing(self.judge_instance.rect_trans()[8])[1] < 100
):
if self.wheather_merging_layer[-2] == 0:#Modeレイヤーをマージするかどうかを変更
self.wheather_merging_layer[-2] = 1
elif self.wheather_merging_layer[-2] == 1:
self.wheather_merging_layer[-2] = 0
else:
self.COResult_ret,self.COResult_num=self.choiceObject(self.judge_instance.rect_trans()[8],100)
if self.COResult_ret:#人差し指の位置が各オブジェクトの基準点と一致する(誤差±50mm)か調べる
self.choiced_objectLayerNum = self.COResult_num
cv2.circle(self.ImgRight_Hand,self.imgProInstance_R.point_processing(self.objectCriteriaPositions[self.COResult_num]),30,[0,0,255,255],2)
cv2.circle(self.ImgLeft_Hand,self.imgProInstance_L.point_processing(self.objectCriteriaPositions[self.COResult_num]),30,[0,0,255,255],2)
else:#一致するものがなければNoneを代入しなおし
self.choiced_objectLayerNum = None
elif self.present_HandSignText == "sidewayspalm" and ("keyboard" in self.current_mode):
self.current_mode.pop(self.current_mode.index("keyboard"))#current_modeからkeyboardを削除
self.imgReset("keyboard","all")
|
{"/main.py": ["/handtracking.py"]}
|
19,866,916
|
nagi900/SmartGlass202101
|
refs/heads/main
|
/main.py
|
from kivy.config import Config
Config.set('graphics', 'width', '640')#デフォルトでは800×600になっている
Config.set('graphics', 'height', '480')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.lang import Builder#これ何?
from kivy.uix.screenmanager import ScreenManager, Screen#, FadeTransition#画面遷移のやつ
from kivy.properties import StringProperty ,ObjectProperty
from kivy.core.text import LabelBase,DEFAULT_FONT#日本語を使えるようにする
from kivy.resources import resource_add_path #多分画像表示のパス取得用のやつ
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.graphics import Rectangle
import os
import glob
import random
import threading
import time
import handtracking
#resource_add_path("./fonts")#デフォルトのフォントを変更
#LabelBase.register(DEFAULT_FONT,"mplus-2c-regular.ttf") #日本語
#resource_add_path("./Image_layer")
class StartScreen(Screen):
pass
class SmartGlassWidget(Screen):#WidgetとScreenの違いは?
image_L_src = StringProperty("")#これは必ずクラス変数として書かないとself.image_L_srcが読み込めない なんで?
image_R_src = StringProperty("")
def __init__(self, **kwargs):
super(SmartGlassWidget,self).__init__(**kwargs)
self.image_L_src = "./Image_layer/ImgLeft_0.png"
self.image_R_src = "./Image_layer/ImgRight_0.png"
self.handtrackingApp=handtracking.Handtracking()
def update(self,dt):
self.handtrackingApp.run()
self.ids.image_L.reload() #kvファイルでid:としていれば、pyファイルからは何もせずにself.idsから呼び出していい
self.ids.image_R.reload()
def StartbuttonClicked(self):
Clock.schedule_interval(self.update,0.01)
pass
class ScreenManagement(ScreenManager):
pass
class MainApp(App):
def __init__(self,**kwargs):
super(MainApp,self).__init__(**kwargs)
self.title = "SmartGlass"
def build(self):
return Builder.load_file("main.kv")
if __name__ == "__main__":
MainApp().run()
|
{"/main.py": ["/handtracking.py"]}
|
19,876,909
|
evgeniilobzaev/EnzymeClassification
|
refs/heads/master
|
/LSTM2.0.py
|
#!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class LSTMClassifier(nn.Module):
def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size):
super(LSTMClassifier, self).__init__()
self.hidden_dim = hidden_dim
self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim)
self.hidden2tag = nn.Linear(hidden_dim, tagset_size)
def forward(self, sequence):
embeds = self.word_embeddings(sequence)
lstm_out, _ = self.lstm(embeds.view(len(sequence), 1, -1))
tag_space = self.hidden2tag(lstm_out.view(len(sequence), -1))
tag_scores = F.log_softmax(tag_space, dim=1)
return tag_scores
model = LSTMTClassifier(EMBEDDING_DIM, HIDDEN_DIM, len(w2i), len(i2w))
loss_function = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(), lr = 0.001)
with torch.no_grad():
inputs = prepare_sequence(training_data[0][0], w2i)
tag_scores = model(inputs)
print(tag_scores)
for epoch in range(3):
for sentence, tags in training_data:
model.zero_grad()
sentence_in = prepare_sequence(sentence, w2i)
targets = prepare_sequence(tags, i2w)
tag_scores = model(sentence_in)
loss = loss_function(tag_scores, targets)
loss.backward()
optimizer.step()
with torch.no_grad():
inputs = prepare_sequence(training_data[0][0], w2i)
tag_scores = model(inputs)
print(tag_scores)
|
{"/EnzymeDataset.py": ["/LSTM.py"]}
|
19,876,910
|
evgeniilobzaev/EnzymeClassification
|
refs/heads/master
|
/EnzymeDataset.py
|
#!/usr/bin/env python3
import LSTM
import torch
from torch.utils.data import Dataset
from Bio import SeqIO
from collections import defaultdict
amino_acids = ['A','R','N','D','C','Q','E','G','H','I','L','K','M','F','P','S','T','W','Y','V']
special_tokens = ['<pad>', '<unk>', '<sos>', '<eos>']
def default_w2i_i2w():
w2i = dict() #maps word i.e amino acids into index
i2w = dict() #maps index into word i.e amino acids
amino_acids = ['A','R','N','D','C','Q','E','G','H','I','L','K','M','F','P','S','T','W','Y','V'] #Vocabulary of the 20 amino acids
special_tokens = ['<pad>', '<unk>', '<sos>', '<eos>']
for w in amino_acids:
i2w[len(w2i)] = w
w2i[w] = len(w2i)
for st in special_tokens:
i2w[len(w2i)] = st
w2i[st] = len(w2i)
return w2i, i2w
class ProteinSequencesDataset(Dataset):
def __init__(self, fasta_file, w2i, i2w, device, max_seq_length=500, one_hot=True):
super().__init__()
self.device = device
self.max_seq_length = max_seq_length + 1
self.one_hot = one_hot
self.w2i = w2i
self.i2w = i2w
self.data = self.__construct_data(fasta_file)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def __sym2num_conversion(self, input_, target_):
input_num = torch.tensor(
[self.w2i.get(element, self.w2i['<unk>']) for element in input_],
dtype=torch.long,
device=self.device
)
target_num = torch.tensor(
[self.w2i.get(element, self.w2i['<unk>']) for element in target_],
dtype=torch.long,
device=self.device
)
return input_num,target_num
def __sym2one_hot_conversion(self,input_,target_):
input_num = torch.zeros((len(input_),len(amino_acids)+len(special_tokens)),
dtype = torch.long,
device = self.device
)
for i, element in enumerate(input_):
input_num[i][self.w2i[element]] = 1
target_num = torch.tensor(
[self.w2i.get(element, self.w2i['<unk>']) for element in target_],
dtype = torch.long,
device = self.device
)
return input_num,target_num
def __construct_data(self,fasta_file):
data = defaultdict(dict)
records = [record for record in SeqIO.parse(fasta_file, "fasta") if self.__passed_filter(record) == True]
for i, record in enumerate(records):
# get reference id
reference_ = record.id
# convert to a list
sequence = list(record.seq)
sequence_plus_sos = ['<sos>'] + sequence
# obtain input and target as character arrays
input_ = sequence_plus_sos[:self.max_seq_length]
target_ = sequence[:self.max_seq_length - 1] + ['<eos>']
assert len(input_) == len(target_), "Length mismatch"
len_ = len(input_)
# cast to tensor
len_ = torch.tensor(len_,
dtype=torch.long,
device=self.device
)
# need to append <pad> tokens if necessary
input_.extend(['<pad>'] * (self.max_seq_length - len_))
target_.extend(['<pad>'] * (self.max_seq_length - len_))
# need to convert into numerical format
if self.one_hot:
input_, target_ = self.__sym2one_hot_conversion(input_, target_)
else:
input_, target_ = self.__sym2num_conversion(input_, target_)
data[i]["input"] = input_
data[i]["target"] = target_
data[i]["length"] = len_
data[i]["reference"] = reference_
return data
def __passed_filter(self, record):
set_amino_acids = set(self.w2i.keys())
unique_set_of_amino_acids_in_ID = set(list(str(record.seq)))
set_diff = unique_set_of_amino_acids_in_ID - set_amino_acids
if len(set_diff) == 0:
return True
else:
return False
if __name__ == '__main__':
torch.set_printoptions(profile="full")
w2i,i2w=default_w2i_i2w()
dataset = ProteinSequencesDataset("fasta_file",w2i,i2w,torch.device('cuda' if torch.cuda.is_available() else 'cpu'))
data = dataset.data
print(dataset.data[0]["input"])
LSTM.LSTMClassifier(input_size, hidden_size, num_layers, num_classes)
|
{"/EnzymeDataset.py": ["/LSTM.py"]}
|
19,876,911
|
evgeniilobzaev/EnzymeClassification
|
refs/heads/master
|
/LSTM.py
|
#!/usr/bin/env python3
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
#set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#Hyperparameters
input_size = 500
sequence_length = 500
num_layers = 2
hidden_size = 100
num_classes = 2
learning_rate = 0.001
batch_size = 100
num_epochs = 2
#create LSTM neural network
class LSTMClassifier(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(LSTMClassifier, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first = True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
out, _ = self.lstm(x,(h0,c0))
out = self.fc(out[:,-1,:])
return out
# load data
train_dataset = datasets.MNIST(root = 'dataset/', train = True, transform = transforms.ToTensor(), download = True)
test_dataset = datasets.MNIST(root = 'dataset/', train = False, transform = transforms.ToTensor(), download = True)
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)
#Initialise Network
model = LSTMClassifier(input_size, hidden_size, num_layers, num_classes).to(device)
#loss and optimiser
criterion = nn.CrossEntropyLoss()
optimiser = torch.optim.Adam(model.parameters(), lr = learning_rate)
#Train Network
for epoch in range(num_epochs):
for batch_idx, (data, targets) in enumerate(train_loader):
data = data.to(device = device)
targets = targets.to(device = device)
data = data.reshape(data.shape[0],-1)
#Forward
scores = model(data)
loss - criterion(scores, targets)
#backward
optimizer.zero_grad()
loss.backward()
#gradient descent or adam step
optimizer.step()
#check accuracy on training and test
def check_accuracy(loader, model):
if loader.dataset.train:
print("Checking accuracy on training data")
else:
print("Checking accuracy on test data")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device = device)
y = y.to(device = device)
x = x.reshape(x.shape[0], -1)
scores - model(x)
_, prediction = scores.max(1)
num_correct += (prediction == y).sum()
num_samples += prediction.size(0)
print(f'Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}')
model.train()
check_accuracy(train_loader, model)
check_accuracy(test_loader. model)
|
{"/EnzymeDataset.py": ["/LSTM.py"]}
|
19,885,643
|
git45016683/jobjobjobSpider
|
refs/heads/master
|
/job/pipelines.py
|
'''
Author: your name
Date: 2021-04-23 11:16:10
LastEditTime: 2021-04-25 16:37:59
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \job\job\pipelines.py
'''
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import sqlite3
# title = ""
# pay = ""
# place = ""
# edu_v = ''
# experience = ''
# company = ""
class JobPipeline(object):
def open_spider(self, spider):
self.con = sqlite3.connect('jobdb.s3db')
self.cu = self.con.cursor()
def process_item(self, item, spider):
self.cu.execute('SELECT count(*) FROM job WHERE url = ?', [item['url']])
already_exist = self.cu.fetchall()
# print(already_exist[0][0])
if (already_exist[0][0] == 0):
insert_sql = 'insert into job (title, pay, place, edu_v, experience, company, url, job_info) values ("{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}")'.format(item['title'], item['pay'], item['place'], item['edu_v'], item['experience'], item['company'], item['url'], item['job_info'])
print(insert_sql)
self.cu.execute(insert_sql)
self.con.commit()
else:
print('this job already in the database')
return item
def spider_close(self, spider):
self.con.close()
|
{"/job/spiders/jobSpider.py": ["/job/items.py"], "/job/spiders/liepinSpider.py": ["/job/items.py"]}
|
19,885,644
|
git45016683/jobjobjobSpider
|
refs/heads/master
|
/job/spiders/liepinSpider.py
|
'''
Author: your name
Date: 2021-04-25 11:40:59
LastEditTime: 2021-04-25 17:00:58
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \job\job\spiders\liepinSpider.py
'''
import scrapy
from job.items import JobItem
class LiepinspiderSpider(scrapy.Spider):
name = 'liepinSpider'
allowed_domains = ['www.liepin.com']
url_1 = 'https://www.liepin.com/zhaopin/?flushckid=1&compkind=&dqs=050020&pubTime=&pageSize=40&salary=20%2450&compTag=&sortFlag=15&compIds=&subIndustry=&industryType=industry_02&jobKind=&industries=050&compscale=&key=%E6%8A%80%E6%9C%AF%E7%AE%A1%E7%90%86&siTag=G-I_JtdsLVjIcDtYV31HIw%7EnBIcYTf8hlCPB-Kl8hs1Zw&d_sfrom=search_fp&d_ckId=6a9549e52f5598efa031eb0bd7ccfa77&d_curPage=0&d_pageSize=40&d_headId=cae87a9ba362c94c1fc09f6725e7094a',
url_2 = 'https://www.liepin.com/zhaopin/?flushckid=1&compkind=&dqs=050020&pubTime=&pageSize=40&salary=20%2450&compTag=&sortFlag=15&compIds=&subIndustry=&industryType=industry_02&jobKind=&industries=060&compscale=&key=%E6%8A%80%E6%9C%AF%E7%AE%A1%E7%90%86&siTag=G-I_JtdsLVjIcDtYV31HIw%7Ey6QKoq-pesOpSo5mI1ngtA&d_sfrom=search_fp&d_ckId=6a27dc50b0e6d6f1d5af4ad15ee7814f&d_curPage=0&d_pageSize=40&d_headId=cae87a9ba362c94c1fc09f6725e7094a',
url_3 = 'https://www.liepin.com/zhaopin/?flushckid=1&compkind=&dqs=050020&pubTime=&pageSize=40&salary=20%2450&compTag=&sortFlag=15&compIds=&subIndustry=&industryType=industry_06&jobKind=&industries=350&compscale=&key=%E6%8A%80%E6%9C%AF%E7%AE%A1%E7%90%86&siTag=G-I_JtdsLVjIcDtYV31HIw%7EOfCBNH25qC8jynqx_BVJtg&d_sfrom=search_fp&d_ckId=3a1ede5a86f32c6a8683cc8ecad3d904&d_curPage=0&d_pageSize=40&d_headId=cae87a9ba362c94c1fc09f6725e7094a',
url_4 = 'https://www.liepin.com/zhaopin/?flushckid=1&compkind=&dqs=050020&pubTime=&pageSize=40&salary=20%2450&compTag=&sortFlag=15&compIds=&subIndustry=&industryType=industry_06&jobKind=&industries=340&compscale=&key=%E6%8A%80%E6%9C%AF%E7%AE%A1%E7%90%86&siTag=G-I_JtdsLVjIcDtYV31HIw%7EswvzFarIYWI0ZnsB_cTJhA&d_sfrom=search_fp&d_ckId=676ce3325ec3dbf039d7964cfcd5cfc4&d_curPage=0&d_pageSize=40&d_headId=cae87a9ba362c94c1fc09f6725e7094a',
url_5 = 'https://www.liepin.com/zhaopin/?flushckid=1&compkind=&dqs=050020&pubTime=&pageSize=40&salary=20%2450&compTag=&sortFlag=15&compIds=&subIndustry=&industryType=industry_02&jobKind=&industries=020&compscale=&key=%E6%8A%80%E6%9C%AF%E7%AE%A1%E7%90%86&siTag=G-I_JtdsLVjIcDtYV31HIw%7Ei5ddw4NCmqIqkENsWj_Xiw&d_sfrom=search_fp&d_ckId=c4c50977068d0160994419e4622cb635&d_curPage=0&d_pageSize=40&d_headId=cae87a9ba362c94c1fc09f6725e7094a'
start_urls = [''.join(url_2)]
def parse(self, response):
print(response)
domain = 'www.liepin.com'
job_list = response.xpath('//*[@class="sojob-result "]/ul/li')
print(job_list)
for li in job_list:
# print(li)
jobItem = JobItem()
title = ""
pay = ""
place = ""
edu_v = ''
experience = ''
company = ""
url = ""
# 职位名称
title = li.xpath('./div/div[1]/h3/a/text()').extract()[0].strip()
# print(title)
# 职位待遇
pay = li.xpath('./div/div[1]/p/span[1]/text()').extract()[0]
# print(pay)
# 职位工作地点
place = li.xpath('./div/div[1]/p/a/text()').extract()[0]
# print(place)
# 工作学历要求
edu_v = li.xpath('./div/div[1]/p/span[2]/text()').extract()[0]
# print(edu_v)
# 工作经验要求
experience = li.xpath('./div/div[1]/p/span[3]/text()').extract()[0]
# print(experience)
# 公司
company = li.xpath('./div/div[2]/p[1]/a/text()').extract()[0]
# print(company)
# # 详情链接-参数
# data_pro = li.xpath('./div/div[1]/h3/a/@data-promid').extract()[0]
# print(data_pro)
# 详情链接
detail_url = li.xpath('./div/div[1]/h3/a/@href').extract()[0]
# print(detail_url)
if(detail_url.startswith('/')):
detail_url = domain + detail_url
if('://' not in detail_url):
detail_url = 'https://' + detail_url
url = detail_url
print(title + " | " + pay + " | " + place + " | " + experience + " | " + edu_v + " | " + company + " | " + url)
jobItem['title'] = title
jobItem['pay'] = pay
jobItem['place'] = place
jobItem['experience'] = experience
jobItem['edu_v'] = edu_v
jobItem['company'] = company
jobItem['url'] = url
yield scrapy.Request(detail_url, callback=self.parse_detail, meta={"item":jobItem})
def parse_detail(self, response):
item = response.meta['item']
# print(response.url)
if ('/a' in response.url):
job_info = response.xpath('//*[@class="job-main job-description main-message"]/div[1]//text()').extract()
else:
# job_info = response.xpath('//*[@class="content content-word"]//text()').extract()
job_info = response.xpath('//*[@class="job-item main-message job-description"]/div[1]//text()').extract()
job_info = ''.join(job_info).strip()
job_info = job_info
item['job_info'] = job_info
print(job_info)
print('------------------------------------------------------------------------------------')
# yield item
|
{"/job/spiders/jobSpider.py": ["/job/items.py"], "/job/spiders/liepinSpider.py": ["/job/items.py"]}
|
20,005,114
|
dokyeongK/yolo-v2_pytorch
|
refs/heads/master
|
/model/yolo_darknet.py
|
import torch
from torch import nn
from model import darknet19
import numpy as np
class ReorgLayer(nn.Module):
def __init__(self, stride=2):
super(ReorgLayer, self).__init__()
self.stride = stride
def forward(self, x):
B, C, H, W = x.data.size()
ws = self.stride
hs = self.stride
x = x.view(B, C, int(H / hs), hs, int(W / ws), ws).transpose(3, 4).contiguous()
x = x.view(B, C, int(H / hs * W / ws), hs * ws).transpose(2, 3).contiguous()
x = x.view(B, C, hs * ws, int(H / hs), int(W / ws)).transpose(1, 2).contiguous()
x = x.view(B, hs * ws * C, int(H / hs), int(W / ws))
return x
class YOLOV2(nn.Module):
def __init__(self, num_classes=80, darknet = None,
anchors=[(1.3221, 1.73145), (3.19275, 4.00944), (5.05587, 8.09892), (9.47112, 4.84053),
(11.2364, 10.0071)], ):
super(YOLOV2, self).__init__()
self.anchors = anchors
self.num_classes = num_classes
# self.backbone_input = darknet.input_conv
# self.backbone_layer1 = darknet.layer1
# self.backbone_layer2 = darknet.layer2
# self.backbone_layer3 = darknet.layer3
# self.backbone_layer4 = darknet.layer4
self.backbone_conv1 = nn.Sequential(darknet.input_conv, darknet.layer1,
darknet.layer2, darknet.layer3, darknet.layer4)
self.backbone_resconv = darknet.layer5
self.yolo_conv1 = nn.Sequential(
nn.Sequential(
nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(1024),
nn.LeakyReLU(0.1, inplace=True),),
nn.Sequential(
nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(1024),
nn.LeakyReLU(0.1, inplace=True), ),
)
self.yolo_conv2 = nn.Sequential(
nn.Conv2d(in_channels=512, out_channels=64, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(64),
nn.LeakyReLU(0.1, inplace=True),
)
self.yolo_conv3 = nn.Sequential(
nn.Conv2d(in_channels=1280, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(1024),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(1024, (5 + self.num_classes) * len(anchors), kernel_size=1)
)
self.reorg = ReorgLayer()
def forward(self, x):
x = self.backbone_conv1(x)
s = self.reorg(self.yolo_conv2(x))
x = self.backbone_resconv(x)
x = self.yolo_conv1(x)
x = torch.cat([s, x], dim=1)
x = self.yolo_conv3(x)
return x
def init_weight(self, modules):
for m in modules:
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='leaky_relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
if __name__ == '__main__':
darknet = darknet19.DarkNet19(num_classes=20)
model = YOLOV2(darknet=darknet).cuda()
model.load_weight(model, 'yolo-voc.weights')
print(model)
image = torch.randn([1, 3, 416, 416]).cuda()
print(model(image).size())
|
{"/train_darknet.py": ["/dataset/voc_dataset.py", "/dataset/coco_dataset.py", "/model/yolo_darknet.py"]}
|
20,005,115
|
dokyeongK/yolo-v2_pytorch
|
refs/heads/master
|
/train_darknet.py
|
import argparse
import visdom
from dataset.voc_dataset import VOC_Dataset
from dataset.coco_dataset import COCO_Dataset
from torch.utils.data import DataLoader
import torch.optim as optim
from loss import Yolo_Loss
import os
from torch.optim.lr_scheduler import StepLR
import time
from model import darknet19
from model.yolo_darknet import YOLOV2
from utils import *
def train(epoch, vis, train_loader, model, criterion, optimizer, scheduler, save_path, save_file_name):
print('Training of epoch [{}]'.format(epoch))
tic = time.time()
model.train()
for idx, datas in enumerate(train_loader):
images = datas[0]
boxes = datas[1]
labels = datas[2]
images = images.cuda() # B 3 416 416
boxes = [b.cuda() for b in boxes] # images boxes info len : batch
labels = [l.cuda() for l in labels] # images class info len : batch
preds = model(images) # B 125 13 13
preds = preds.permute(0, 2, 3, 1) # B 13 13 125
loss, losses = criterion(preds, boxes, labels) # boxes, labels : gt
optimizer.zero_grad()
loss.backward()
optimizer.step()
toc = time.time() - tic
for param_group in optimizer.param_groups:
lr = param_group['lr']
# for each steps
if idx % 100 == 0:
print('Epoch: [{0}]\t'
'Step: [{1}/{2}]\t'
'xy_Loss: {xy:.4f}\t'
'wh_Loss: {wh:.4f}\t'
'conf_Loss: {conf:.4f}\t'
'no_conf_Loss: {noconf:.4f}\t'
'class_Loss: {cls:.4f}\t'
'Learning rate: {lr:.7f} s \t'
'Time : {time:.4f}\t'
.format(epoch, idx, len(train_loader),
xy=losses[0].item(),
wh=losses[1].item(),
conf=losses[2].item(),
noconf=losses[3].item(),
cls=losses[4].item(),
lr=lr,
time=toc))
if vis is not None:
vis.line(X=torch.ones((1, 6)).cpu() * idx + epoch * train_loader.__len__(), # step
Y=torch.Tensor([loss, losses[0], losses[1], losses[2], losses[3], losses[4]]).unsqueeze(
0).cpu(),
win='train_loss',
update='append',
opts=dict(xlabel='step',
ylabel='Loss',
title='training loss',
legend=['Total Loss', 'xy_loss', 'wh_loss', 'conf_loss', 'no_conf_loss',
'cls_loss']))
if not os.path.exists(save_path):
os.mkdir(save_path)
if scheduler is not None:
checkpoint = {'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict()}
else:
checkpoint = {'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict()}
torch.save(checkpoint, os.path.join(save_path, save_file_name) + '.{}.pth.tar'.format(epoch))
def main():
# ================================
# Setting Argumentation
# ================================
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=200)
parser.add_argument('--lr', type=float, default=1e-6)
parser.add_argument('--batch_size', type=int, default=16)
parser.add_argument('--num_workers', type=int, default=0)
parser.add_argument('--num_classes', type=int, default=20)
parser.add_argument('--backbone_pretrain', type=bool, default=True)
parser.add_argument('--model_pretrain', type=bool, default=False)
parser.add_argument('--save_file_name', type=str, default='yolo_v2_training')
parser.add_argument('--conf_thres', type=float, default=0.01)
parser.add_argument('--save_path', type=str, default='./saves')
parser.add_argument('--start_epoch', type=int, default=0)
parser.add_argument('--use_visdom', type=bool, default=True)
parser.add_argument('--dataset_type', type=str, default='voc', help='which dataset you want to use VOC or COCO')
opts = parser.parse_args()
print(opts)
print("Use Visdom : ", opts.use_visdom)
if opts.use_visdom :
vis = visdom.Visdom()
# ================================
# Data Loader (root type)
# [VOC]
# Train : /VOCDevkit/TRAIN/VOC2007/JPEGImages & /VOCDevkit/TRAIN/VOC2007/Annotations
# Test : /VOCDevkit/TEST/VOC2007/JPEGImages & /VOCDevkit/TEST/VOC2007/Annotations
# [COCO]
# Train : /COCO/images/train2017 & /COCO/annotations/instances_train2017.json
# Test : /COCO/images/val2017 & /COCO/annotations/instances_val2017.json
# ================================
data_root = '/mnt/mydisk/hdisk/dataset/VOCdevkit'
if opts.dataset_type == 'voc':
train_set = VOC_Dataset(root=data_root, mode='TRAIN')
test_set = VOC_Dataset(root=data_root, mode='TEST')
elif opts.dataset_type == 'coco':
train_set = COCO_Dataset(root=data_root, mode='TRAIN')
test_set = COCO_Dataset(root=data_root, mode='TEST')
train_loader = DataLoader(dataset=train_set,
batch_size=opts.batch_size,
collate_fn=train_set.collate_fn,
shuffle=True,
pin_memory=True,
num_workers=opts.num_workers)
darknet = darknet19.DarkNet19(num_classes=opts.num_classes)
model = YOLOV2(darknet=darknet).cuda()
if opts.backbone_pretrain :
backbone_weights_file_root = 'yolo-voc.weights'
print(" Darknet19 (used pre-train weights) : ", backbone_weights_file_root)
weights_loader = WeightLoader()
weights_loader.load(darknet, backbone_weights_file_root, backbone=True)
if opts.model_pretrain:
# load-weights (include backbone) / .weights file
model_weights_file_root = 'yolo-voc.weights'
print(" YOLOv2 (used pre-train weights) : ", model_weights_file_root)
weights_loader = WeightLoader()
weights_loader.load(model, model_weights_file_root, backbone=False)
# ================================
# Setting Loss
# ================================
criterion = Yolo_Loss(num_classes=opts.num_classes)
# ================================
# Setting Optimizer
# ================================
optimizer = optim.SGD(params=model.parameters(),
lr=opts.lr,
momentum=0.9,
weight_decay=5e-4)
# ================================
# Setting Scheduler
# ================================
scheduler = StepLR(optimizer=optimizer, step_size=100, gamma=0.1)
# ================================
# Setting Loss
# ================================
if opts.start_epoch != 0:
checkpoint = torch.load(os.path.join(opts.save_path, opts.save_file_name) + '.{}.pth.tar'
.format(opts.start_epoch - 1)) # train
model.load_state_dict(checkpoint['model_state_dict']) # load model state dict
optimizer.load_state_dict(checkpoint['optimizer_state_dict']) # load optim state dict
if scheduler is not None:
scheduler.load_state_dict(checkpoint['scheduler_state_dict']) # load sched state dict
print('\nLoaded checkpoint from epoch %d.\n' % (int(opts.start_epoch) - 1))
else:
print('\nNo check point to resume.. train from scratch.\n')
# ================================
# Training
# ================================
for epoch in range(opts.start_epoch, opts.epochs):
train(epoch=epoch,
vis=vis,
train_loader=train_loader,
model=model,
criterion=criterion,
optimizer=optimizer,
scheduler=scheduler,
save_path=opts.save_path,
save_file_name=opts.save_file_name)
if scheduler is not None:
scheduler.step()
if __name__ == '__main__':
main()
|
{"/train_darknet.py": ["/dataset/voc_dataset.py", "/dataset/coco_dataset.py", "/model/yolo_darknet.py"]}
|
20,005,116
|
dokyeongK/yolo-v2_pytorch
|
refs/heads/master
|
/model/darknet19.py
|
from torch import nn
import torch
import numpy as np
class DarkNet19(nn.Module):
def __init__(self, num_classes=80, num_bboxes=2):
super(DarkNet19, self).__init__()
self.num_bboxes = num_bboxes
self.num_classes = num_classes
# 6개의 layer.
# [32]
self.input_conv = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(32),
nn.LeakyReLU(0.1, inplace=True)
)
# [Maxpool, 64]
self.layer1 = nn.Sequential(
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.LeakyReLU(0.1, inplace=True)
)
# [Maxpool, 128, 64, 128]
self.layer2 = nn.Sequential(
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(128),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=128, out_channels=64, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(64),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(128),
nn.LeakyReLU(0.1, inplace=True)
)
# [Maxpool, 256, 128, 256]
self.layer3 = nn.Sequential(
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=256, out_channels=128, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(128),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.LeakyReLU(0.1, inplace=True)
)
# [Maxpool, 512, 256, 512, 256, 512]
self.layer4 = nn.Sequential(
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=512, out_channels=256, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(256),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=512, out_channels=256, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(256),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.1, inplace=True)
)
# [Maxpool, 1024, 512, 1024, 512, 1024]
self.layer5 = nn.Sequential(
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(1024),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=1024, out_channels=512, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(1024),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=1024, out_channels=512, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.1, inplace=True),
nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(1024),
nn.LeakyReLU(0.1, inplace=True)
)
# [Classifier > 1024, 1000]
self.classifier = nn.Sequential(
nn.Conv2d(in_channels=1024, out_channels=1000, kernel_size=1, stride=1, padding=0),
nn.BatchNorm2d(1000),
nn.LeakyReLU(0.1, inplace=True),
nn.AdaptiveAvgPool2d(1)
)
self.softmax = nn.Softmax(dim=1)
self.init_weight(self.input_conv)
self.init_weight(self.layer1)
self.init_weight(self.layer2)
self.init_weight(self.layer3)
self.init_weight(self.layer4)
self.init_weight(self.layer5)
# self.init_weight(self.classifier)
def forward(self, x):
x = self.input_conv(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.layer5(x) # [3, 1024, 13, 13]
x = self.classifier(x)
x = self.softmax(x)
return x
def init_weight(self, modules):
for m in modules:
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='leaky_relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def load_conv_bn(self, conv_model, bn_model):
num_w = conv_model.weight.numel()
num_b = bn_model.bias.numel()
bn_model.bias.data.copy_(
torch.reshape(torch.from_numpy(self.buf[self.start:self.start + num_b]), bn_model.bias.size()))
self.start = self.start + num_b
bn_model.weight.data.copy_(
torch.reshape(torch.from_numpy(self.buf[self.start:self.start + num_b]), bn_model.bias.size()))
self.start = self.start + num_b
bn_model.running_mean.copy_(
torch.reshape(torch.from_numpy(self.buf[self.start:self.start + num_b]), bn_model.bias.size()))
self.start = self.start + num_b
bn_model.running_var.copy_(
torch.reshape(torch.from_numpy(self.buf[self.start:self.start + num_b]), bn_model.bias.size()))
self.start = self.start + num_b
conv_model.weight.data.copy_(
torch.reshape(torch.from_numpy(self.buf[self.start:self.start + num_w]), conv_model.weight.size()))
self.start = self.start + num_w
def load_conv(self, conv_model):
num_w = conv_model.weight.numel()
num_b = conv_model.bias.numel()
conv_model.bias.data.copy_(
torch.reshape(torch.from_numpy(self.buf[self.start:self.start + num_b]), conv_model.bias.size()))
self.start = self.start + num_b
conv_model.weight.data.copy_(
torch.reshape(torch.from_numpy(self.buf[self.start:self.start + num_w]), conv_model.weight.size()))
self.start = self.start + num_w
def dfs(self, m):
children = list(m.children())
for i, c in enumerate(children):
if isinstance(c, torch.nn.Sequential):
self.dfs(c)
elif isinstance(c, torch.nn.Conv2d):
if c.bias is not None:
self.load_conv(c)
else:
self.load_conv_bn(c, children[i + 1])
def load_weight(self, model, weights_file):
self.start = 0
fp = open(weights_file, 'rb')
self.buf = np.fromfile(fp, dtype=np.float32)
fp.close()
self.dfs(model)
# if __name__ == '__main__':
# model = DarkNet19(num_classes=3).cuda()
# model.load_weight(model, weights_file='yolo-voc.weights')
# print(model)
# image = torch.randn([3, 3, 416, 416]).cuda()
# print(model(image).size())
|
{"/train_darknet.py": ["/dataset/voc_dataset.py", "/dataset/coco_dataset.py", "/model/yolo_darknet.py"]}
|
20,005,117
|
dokyeongK/yolo-v2_pytorch
|
refs/heads/master
|
/dataset/voc_dataset.py
|
from torch.utils.data import Dataset
import os
import glob
from PIL import Image
import torch
import numpy as np
from xml.etree.ElementTree import parse
import transform
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
class VOC_Dataset(Dataset):
def __init__(self, root='/mnt/mydisk/hdisk/dataset/VOCdevkit', mode='TRAIN', year = 'VOC2007'):
super(VOC_Dataset, self).__init__()
root = os.path.join(root, mode, year)
# VOC data image, annotation list 불러오기
self.img_list = sorted(glob.glob(os.path.join(root, 'JPEGImages/*.jpg')))
self.anno_list = sorted(glob.glob(os.path.join(root, 'Annotations/*.xml')))
self.class_names = ('aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse',
'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
self.class_dict = {class_name: i for i, class_name in enumerate(self.class_names)}
self.class_dict_inv = {i: class_name for i, class_name in enumerate(self.class_names)}
self.img_size = 416
self.mode = mode
def __len__(self):
return len(self.img_list)
def __getitem__(self, idx):
visualize = False
img = Image.open(self.img_list[idx]).convert('RGB')
# is_difficult : 0 pr 1
boxes, labels, is_difficult = self.parse_voc(self.anno_list[idx])
# load img name for string
img_name = os.path.basename(self.anno_list[idx]).split('.')[0]
# image name -> ascii
img_name_to_ascii = [ord(c) for c in img_name]
img_width, img_height = float(img.size[0]), float(img.size[1])
# convert to tensor
boxes = torch.FloatTensor(boxes)
labels = torch.LongTensor(labels)
difficulties = torch.ByteTensor(is_difficult) # (n_objects)
img_name = torch.FloatTensor([img_name_to_ascii])
additional_info = torch.FloatTensor([img_width, img_height])
image, boxes, labels, difficulties = transform.transform_voc(img, boxes, labels, difficulties, self.mode)
if visualize:
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
# tensor to img
img_vis = np.array(image.permute(1, 2, 0), np.float32) # C, W, H
img_vis *= std
img_vis += mean
img_vis = np.clip(img_vis, 0, 1)
plt.figure('img')
plt.imshow(img_vis)
print('num objects : {}'.format(len(boxes)))
for i in range(len(boxes)):
print(boxes[i], labels[i])
plt.gca().add_patch(Rectangle((boxes[i][0] * self.img_size, boxes[i][1] * self.img_size),
boxes[i][2] * self.img_size - boxes[i][0] * self.img_size,
boxes[i][3] * self.img_size - boxes[i][1] * self.img_size,
linewidth=1, edgecolor='r', facecolor='none'))
plt.text(boxes[i][0] * self.img_size - 10, boxes[i][1] * self.img_size - 10,
str(self.class_dict_inv[labels[i].item()]),
bbox=dict(boxstyle='round4', color='grey'))
plt.show()
if self.mode == "TEST":
return image, boxes, labels, difficulties, img_name, additional_info # for evaluations
return image, boxes, labels, difficulties
def collate_fn(self, batch):
images = list()
boxes = list()
labels = list()
img_name = list()
difficulties = list()
if self.mode == "TEST":
additional_info = list()
for b in batch:
images.append(b[0])
boxes.append(b[1])
labels.append(b[2])
difficulties.append(b[3])
if self.mode == "TEST":
img_name.append(b[4])
additional_info.append(b[5])
images = torch.stack(images, dim=0)
if self.mode == "TEST":
return images, boxes, labels, difficulties, img_name, additional_info
return images, boxes, labels, difficulties
def parse_voc(self, xml_file_path):
tree = parse(xml_file_path)
root = tree.getroot()
boxes = []
labels = []
is_difficult = []
# -------------------------------------------------------------------------------------------------------------------------------------
for obj in root.iter("object"):
# <name>
name = obj.find('./name')
# <name> -> 소문자로
class_name = name.text.lower().strip()
# class name -> label (ex, chair -> 8)
labels.append(self.class_dict[class_name])
# stop to bbox tag
bbox = obj.find('./bndbox')
x_min = bbox.find('./xmin')
y_min = bbox.find('./ymin')
x_max = bbox.find('./xmax')
y_max = bbox.find('./ymax')
# from str to int # 왜 1을 빼지? question 1
x_min = float(x_min.text) - 1
y_min = float(y_min.text) - 1
x_max = float(x_max.text) - 1
y_max = float(y_max.text) - 1
boxes.append([x_min, y_min, x_max, y_max])
# is_difficult
is_difficult_str = obj.find('difficult').text
is_difficult.append(int(is_difficult_str) if is_difficult_str else 0)
return (np.array(boxes, dtype=np.float32),
np.array(labels, dtype=np.int64),
np.array(is_difficult, dtype=np.uint8))
# if __name__ == '__main__':
# train_dataset = VOC_Dataset(root='/mnt/mydisk/hdisk/dataset/VOCdevkit', mode='TRAIN', year='VOC2007')
# train_loader = torch.utils.data.DataLoader(train_dataset,
# batch_size=1,
# collate_fn=train_dataset.collate_fn,
# shuffle=False,
# num_workers=0,
# pin_memory=True)
#
# for i, (images, boxes, labels, _) in enumerate(train_loader):
# images = images.cuda()
# boxes = [b.cuda() for b in boxes]
# labels = [l.cuda() for l in labels]
#
# print("end")
|
{"/train_darknet.py": ["/dataset/voc_dataset.py", "/dataset/coco_dataset.py", "/model/yolo_darknet.py"]}
|
20,005,118
|
dokyeongK/yolo-v2_pytorch
|
refs/heads/master
|
/dataset/coco_dataset.py
|
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from pycocotools.coco import COCO
from transform import transform_COCO
from PIL import Image
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.patches import Rectangle
class COCO_Dataset(Dataset):
"""Coco dataset."""
def __init__(self, root_dir='/mnt/mydisk/hdisk/dataset/COCO', set_name='val2017', mode='TRAIN'):
"""
Args:
root_dir (string): COCO directory.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
'''
data path is as follos:
root -- images -- train2017
| |- val2017
| (|- test2017)
|
-- anotations -- instances_train2017.json
|- instances_val2017.json * minival
(|- image_info_test2017.json)
(|- image_info_test-dev2017.json)
'''
super().__init__()
self.root_dir = root_dir
self.set_name = set_name
self.coco = COCO(os.path.join(self.root_dir, 'annotations', 'instances_' + self.set_name + '.json'))
whole_image_ids = self.coco.getImgIds() # original length of train2017 is 118287
self.image_ids = []
# to remove not annotated image idx
self.no_anno_list = []
for idx in whole_image_ids:
annotations_ids = self.coco.getAnnIds(imgIds=idx, iscrowd=False)
if len(annotations_ids) == 0:
self.no_anno_list.append(idx)
else:
self.image_ids.append(idx)
# after removing not annotated image, the length of train2017 is 117359
# in https://github.com/cocodataset/cocoapi/issues/76 1021 not annotated images exist
# so 118287 - 117266 = 1021
self.load_classes()
self.mode = mode
def load_classes(self):
# load class names (name -> label)
categories = self.coco.loadCats(self.coco.getCatIds())
categories.sort(key=lambda x: x['id'])
self.classes = {}
self.coco_labels = {}
self.coco_labels_inverse = {}
for c in categories:
self.coco_labels[len(self.classes)] = c['id']
self.coco_labels_inverse[c['id']] = len(self.classes)
self.classes[c['name']] = len(self.classes)
# also load the reverse (label -> name)
self.labels = {}
for key, value in self.classes.items():
self.labels[value] = key
def __len__(self):
return len(self.image_ids)
def __getitem__(self, idx):
visualize = False
image, (w, h) = self.load_image(idx)
annotation = self.load_annotations(idx)
boxes = torch.FloatTensor(annotation[:, :4])
labels = torch.LongTensor(annotation[:, 4])
if labels.nelement() == 0: # no labeled img exists.
visualize = True
# data augmentation
image, boxes, labels = transform_COCO(image, boxes, labels, self.mode)
if visualize:
# ----------------- visualization -----------------
resized_img_size = 416
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
# tensor to img
img_vis = np.array(image.permute(1, 2, 0), np.float32) # C, W, H
img_vis *= std
img_vis += mean
img_vis = np.clip(img_vis, 0, 1)
plt.figure('input')
plt.imshow(img_vis)
for i in range(len(boxes)):
print(boxes[i], labels[i])
plt.gca().add_patch(Rectangle((boxes[i][0] * resized_img_size, boxes[i][1] * resized_img_size),
boxes[i][2] * resized_img_size - boxes[i][0] * resized_img_size,
boxes[i][3] * resized_img_size - boxes[i][1] * resized_img_size,
linewidth=1, edgecolor='r', facecolor='none'))
plt.text(boxes[i][0] * resized_img_size - 5, boxes[i][1] * resized_img_size - 5,
str(self.labels[labels[i].item()]),
bbox=dict(boxstyle='round4', color='grey'))
plt.show()
return image, boxes, labels
def load_image(self, image_index):
image_info = self.coco.loadImgs(self.image_ids[image_index])[0]
path = os.path.join(self.root_dir, 'images', self.set_name, image_info['file_name'])
image = Image.open(path).convert('RGB')
return image, (image_info['width'], image_info['height'])
def load_annotations(self, image_index):
# get ground truth annotations
annotations_ids = self.coco.getAnnIds(imgIds=self.image_ids[image_index], iscrowd=False)
annotations = np.zeros((0, 5))
# some images appear to miss annotations (like image with id 257034)
if len(annotations_ids) == 0:
return annotations
# parse annotations
coco_annotations = self.coco.loadAnns(annotations_ids)
for idx, a in enumerate(coco_annotations):
# some annotations have basically no width / height, skip them
if a['bbox'][2] < 1 or a['bbox'][3] < 1:
continue
annotation = np.zeros((1, 5))
annotation[0, :4] = a['bbox']
annotation[0, 4] = self.coco_label_to_label(a['category_id'])
annotations = np.append(annotations, annotation, axis=0)
# transform from [x, y, w, h] to [x1, y1, x2, y2]
annotations[:, 2] = annotations[:, 0] + annotations[:, 2]
annotations[:, 3] = annotations[:, 1] + annotations[:, 3]
return annotations
def coco_label_to_label(self, coco_label):
return self.coco_labels_inverse[coco_label]
def label_to_coco_label(self, label):
return self.coco_labels[label]
def image_aspect_ratio(self, image_index):
image = self.coco.loadImgs(self.image_ids[image_index])[0]
return float(image['width']) / float(image['height'])
def num_classes(self):
return 80
def collate_fn(self, batch):
"""
:param batch: an iterable of N sets from __getitem__()
:return: a tensor of images, lists of varying-size tensors of bounding boxes, labels, difficulties, img_name and
additional_info
"""
images = list()
boxes = list()
labels = list()
for b in batch:
images.append(b[0])
boxes.append(b[1])
labels.append(b[2])
images = torch.stack(images, dim=0)
return images, boxes, labels
if __name__ == '__main__':
train_set = COCO_Dataset()
train_loader = DataLoader(train_set,
batch_size=1,
collate_fn=train_set.collate_fn,
shuffle=False,
num_workers=0,
pin_memory=True)
for i, (images, boxes, labels) in enumerate(train_loader):
images = images.cuda()
boxes = [b.cuda() for b in boxes]
labels = [l.cuda() for l in labels]
|
{"/train_darknet.py": ["/dataset/voc_dataset.py", "/dataset/coco_dataset.py", "/model/yolo_darknet.py"]}
|
20,094,335
|
jiyuha/C45
|
refs/heads/main
|
/viztree.py
|
from graphviz import Digraph
def viztree(leaf_list, root):
leaf_id = list(map(lambda x: [x.id, x.branchAttribute, x.parent, x.classes, x.decision], leaf_list))
dot = Digraph(comment='Visualization', format='svg')
for i in leaf_id:
if sum(i[4]) > 0:
bar = 'slategray1;' + str(i[4][0] / sum(i[4])) + ':mistyrose;' + str(i[4][1] / sum(i[4]))
else:
bar = 'slategray1;0.5:mistyrose;0.5'
if i[1] is None:
if i[4][0] >= i[4][1]:
decision = 'True'
label = 'True:' + str(i[4][0]) + ' / ' + 'False:' + str(i[4][1]) + '\n'
dot.node(i[0], "<"+label+"<font color='blue'><br/>"+decision+"<br/></font>>",fontcolor='antiquewhite4',color='antiquewhite4', fontname='Arial')
'<<FONT COLOR="RED" POINT-SIZE="24.0" FACE="ambrosia">line4</FONT> and then more stuff>'
print()
else:
decision = 'False'
label = 'True:' + str(i[4][0]) + ' / ' + 'False:' + str(i[4][1]) + '\n'
dot.node(i[0], "<"+label+"<font color='red'><br/>"+decision+"<br/></font>>",fontcolor='antiquewhite4',color='antiquewhite4', fontname='Arial')
else:
dot.node(i[0], i[1] + '\n[True:' + str(i[4][0]) + ' / False:' + str(i[4][1]) + ']',
color='antiquewhite4',shape='box', fontname='Arial', style='striped', fillcolor=bar, fontcolor='antiquewhite4')
if i[2] is '1':
dot.edge(i[2], i[0], i[3], fontname='Arial', arrowhead='normal',color='antiquewhite4')
else:
dot.edge(i[2].id, i[0], i[3], fontname='Arial', arrowhead='normal',color='antiquewhite4')
# ===========================================================
root_bar = 'slategray1;' + str(root.decision[0] / sum(root.decision)) + ':mistyrose;' + str(
root.decision[1] / sum(root.decision))
dot.node('1', root.branchAttribute + '\n[True:' + str(root.decision[0]) + ' / False:' + str(root.decision[1]) + ']',
color='antiquewhite4', shape='box', fontname='Arial', style='striped', fillcolor=root_bar,
fontcolor='antiquewhite4')
print(dot.source) # doctest: +NORMALIZE_WHITESPACE
dot.render('test-output/Visualization.gv', view=True)
|
{"/MAPSC45.py": ["/Training.py", "/data_load.py"], "/Training.py": ["/data_load.py"], "/main.py": ["/MAPSC45.py", "/data_load.py", "/viztree.py"]}
|
20,094,336
|
jiyuha/C45
|
refs/heads/main
|
/MAPSC45.py
|
import numpy as np
import pandas as pd
import Training
from data_load import DT
import time
import pickle
def data_split(data, _portion: float):
target_unique = data['Decision'].unique()
data_0 = data[data['Decision'] == target_unique[0]]
data_1 = data[data['Decision'] == target_unique[1]]
sample_data_0 = int(len(data_0) * _portion)
sample_data_1 = int(len(data_1) * _portion)
train_data_0 = data_0.take(np.random.permutation(len(data_0))[:(1 - sample_data_0)])
train_data_1 = data_1.take(np.random.permutation(len(data_1))[:(1 - sample_data_1)])
train_data = pd.concat([train_data_0, train_data_1], axis=0)
test_data_0 = data_0.take(np.random.permutation(len(data_0))[:sample_data_0])
test_data_1 = data_1.take(np.random.permutation(len(data_1))[:sample_data_1])
test_data = pd.concat([test_data_0, test_data_1], axis=0)
return train_data, test_data
def createTree(train_data, test_data, attribute, config, filename, max_depth=7):
start_time = time.time()
result_leaf, leaf_list, root = Training.buildDecisionTree(train_data, attribute, config, max_depth=max_depth)
print("\n=================================")
print('Creating Tree : ', time.time() - start_time)
print("=================================")
result = [i for i in result_leaf]
rule_decision = []
for i in result:
rule_decision.append([i.rule, max(list(map(lambda x: x.Decision, i.dataset)),
key=list(map(lambda x: x.Decision, i.dataset)).count)])
# ===========================================================
tree = DT()
tree.leaf = leaf_list
tree.root = root
tree.rule_decision = rule_decision
with open('tree/'+filename + '_'+str(max_depth)+'.p', 'wb') as file: # james.p 파일을 바이너리 쓰기 모드(wb)로 열기
pickle.dump(tree, file)
return tree
def evaluate(test_data):
TP, FN, FP, TN = 0, 0, 0, 0
for i in test_data:
if (i.Decision == 'good') and (i.predict == 'good'):
TP += 1
elif (i.Decision == 'good') and (i.predict == 'bad'):
FN += 1
elif (i.Decision == 'bad') and (i.predict == 'good'):
FP += 1
else:
TN += 1
return TP, FN, FP, TN
def preprocessingData(train_data_value, test_data_value):
decision = set(map(lambda x: x[-1], train_data_value))
for _index, _decision in enumerate(decision):
for _data in train_data_value:
if _data[-1] == _decision:
_data[-1] = _index
for _data in test_data_value:
if _data[-1] == _decision:
_data[-1] = _index
return train_data_value, test_data_value
|
{"/MAPSC45.py": ["/Training.py", "/data_load.py"], "/Training.py": ["/data_load.py"], "/main.py": ["/MAPSC45.py", "/data_load.py", "/viztree.py"]}
|
20,094,337
|
jiyuha/C45
|
refs/heads/main
|
/data_load.py
|
from tqdm import tqdm
from colorama import Style, Fore
from time import sleep
class Data(object):
def __init__(self, keys, values):
for (key, value) in zip(keys, values):
self.__dict__[key] = value
self.id = 0
self.winner = ''
self.usedCategorical = []
self.predict = None
class Attribute:
def __init__(self):
self.name = None
self.type = None
class Leaf:
def __init__(self):
self.rule = ''
self.dataset = []
self.terminateBuilding = False
self.branch = 0
self.parent = None
self.id = None
self.branchAttribute = None
self.classes = None
self.decision = []
self.predict = None
class DT:
def __init__(self):
self.leaf = list
self.root = None
self.test_data = None
self.rule_decision = list
def fit(self):
self.root.dataset = self.test_data
decisions = list(set(list(map(lambda x: x.Decision, self.test_data))))
num_of_decisions = []
for i in decisions:
num_of_decisions.append(list(map(lambda x: x.Decision, self.root.dataset)).count(i))
self.root.decision = num_of_decisions
for _leaf in tqdm(self.leaf, desc=Fore.GREEN + Style.BRIGHT + "Fitting : ", mininterval=0.1):
#for _leaf in self.leaf:
_leaf.dataset = []
for obj in _leaf.parent.dataset:
if eval(_leaf.rule):
obj.predict = _leaf.predict
_leaf.dataset.append(obj)
sleep(0.1)
num_of_decisions = []
for i in decisions:
num_of_decisions.append(list(map(lambda x: x.Decision, _leaf.dataset)).count(i))
_leaf.decision = num_of_decisions
def attribute_set(attribute, data):
# attribute 의 데이터 타입(범주형 or 연속형)을 판단
if len(set(map(lambda x: x.__getattribute__(attribute.name), data))) <= 5:
attribute.type = 'Categorical'
for _data in data:
setattr(_data,attribute.name,str(_data.__getattribute__(attribute.name)))
else:
attribute.type = 'Continuous'
|
{"/MAPSC45.py": ["/Training.py", "/data_load.py"], "/Training.py": ["/data_load.py"], "/main.py": ["/MAPSC45.py", "/data_load.py", "/viztree.py"]}
|
20,094,338
|
jiyuha/C45
|
refs/heads/main
|
/Training.py
|
import math
import numpy as np
import data_load
from time import sleep
from tqdm import tqdm
from colorama import Style, Fore
def buildDecisionTree(data, attribute, config, max_depth=3):
winner_attribute, data = findGains(data, attribute,
config) # branch 에 쓰일 attribute 선택 / instance 에서 연속형 변수들 범주형으로 변함
if winner_attribute.type is 'Continuous':
classes = list(set(map(lambda x: x.winner, data)))
else:
classes = list(set(map(lambda x: x.__getattribute__(winner_attribute.name), data)))
# =========================================
root = data_load.Leaf()
root.id = '1'
root.branchAttribute = winner_attribute.name
leaf_list = [] # 모든 leaf
result_leaf = [] # terminateBuilding 이 True 인 leaf
decisions = list(set(list(map(lambda x: x.Decision, data))))
# =========================================
for _leaf, _index in tqdm(enumerate(range(len(classes))), desc=Fore.GREEN + Style.BRIGHT + "Creating Root... ", mininterval=0.1):
#for _leaf, _index in enumerate(range(len(classes))):
_leaf = data_load.Leaf()
if winner_attribute.type is 'Continuous':
_leaf.rule += 'obj.' + str(winner_attribute.name) + ' ' + str(classes[_index])
processed_data = list(filter(lambda x: x.winner == classes[_index], data))
else:
_leaf.rule += 'obj.' + str(winner_attribute.name) + ' == ' + "'" + str(classes[_index]) + "'"
processed_data = list(
filter(lambda x: x.__getattribute__(winner_attribute.name) == classes[_index], data))
_leaf.parent = root
_leaf.id = '1' + str(_index)
_leaf.classes = classes[_index]
# =========================================
_leaf.dataset = processed_data # parent leaf 의 데이터 에서 child leaf 로 branch 된 데이터만 가져감
num_of_decisions = []
for i in decisions:
num_of_decisions.append(list(map(lambda x: x.Decision, _leaf.dataset)).count(i))
_leaf.decision = num_of_decisions
for i in _leaf.dataset:
data.remove(i)
# =========================================
if winner_attribute.type is 'Categorical': # 이번 branch 에 쓰인 attribute 가 범주형이면 그 attribute 는 삭제
for i in _leaf.dataset:
i.usedCategorical.append(winner_attribute.name)
delattr(i, winner_attribute.name)
# =========================================
# branch 중지 조건
if len(set(map(lambda x: x.Decision, _leaf.dataset))) == 1:
_leaf.terminateBuilding = True
result_leaf.append(_leaf) # branch 중지 시, result_leaf 에 넣어야 함
# =========================================
_leaf.branch += 1
_leaf.predict = decisions[num_of_decisions.index(max(num_of_decisions))]
leaf_list.append(_leaf) # 모든 leaf 는 leaf_list 에 들어감
sleep(0.1)
# =========================================
depth = 2
while len(set(filter(lambda x: x.terminateBuilding is False, leaf_list))) >= 1:
for _leaf in tqdm(list(
filter(lambda x: x.terminateBuilding is False, leaf_list)), desc=Fore.GREEN + Style.BRIGHT + "Creating Tree...(Depth = " +
str(depth) + ')', mininterval=0.1): # 이제부터 _leaf 는 parent leaf 로 생각하면 됩니다.
#for _leaf in list(
# filter(lambda x: x.terminateBuilding is False, leaf_list)):
# =========================================
winner_attribute, _leaf.dataset = findGains(_leaf.dataset, attribute, config)
_leaf.branchAttribute = winner_attribute.name
if winner_attribute.type is 'Continuous':
classes = list(set(map(lambda x: x.winner, _leaf.dataset)))
else:
classes = list(set(map(lambda x: x.__getattribute__(winner_attribute.name), _leaf.dataset)))
# =========================================
for _child_leaf, _index in enumerate(range(len(classes))):
_child_leaf = data_load.Leaf()
_child_leaf.branch = _leaf.branch + 1
_child_leaf.rule = _leaf.rule + ' and ' # parent leaf 의 rule 을 그대로 이어 적기 위해 가져옴
_child_leaf.classes = classes[_index]
if winner_attribute.type is 'Continuous':
_child_leaf.rule += 'obj.' + str(winner_attribute.name) + str(classes[_index])
processed_data = list(filter(lambda x: x.winner == classes[_index], _leaf.dataset))
else:
_child_leaf.rule += 'obj.' + str(winner_attribute.name) + ' == ' + "'" + str(classes[_index]) + "'"
processed_data = list(
filter(lambda x: x.__getattribute__(winner_attribute.name) == classes[_index], _leaf.dataset))
_child_leaf.parent = _leaf
_child_leaf.id = _child_leaf.parent.id + str(_index)
# =========================================
_child_leaf.dataset = processed_data
num_of_decisions = []
for i in decisions:
num_of_decisions.append(list(map(lambda x: x.Decision, _child_leaf.dataset)).count(i))
_child_leaf.decision = num_of_decisions
for i in _child_leaf.dataset:
_leaf.dataset.remove(i)
# =========================================
if winner_attribute.type is 'Categorical':
for i in _child_leaf.dataset:
i.usedCategorical.append(winner_attribute.name)
delattr(i, winner_attribute.name)
# =========================================
# branch 중지 조건
if not _child_leaf.terminateBuilding:
# 1. dataset 의 Decision 종류가 1개일 경우
if len(set(map(lambda x: x.Decision, _child_leaf.dataset))) == 1:
_child_leaf.terminateBuilding = True
result_leaf.append(_child_leaf)
# 2. max depth = 3
if _child_leaf.branch >= max_depth - 1:
_child_leaf.terminateBuilding = True
result_leaf.append(_child_leaf)
# 3.
"""
if min(_child_leaf.decision) / max(_child_leaf.decision) <= 0.1:
_child_leaf.terminateBuilding = True
result_leaf.append(_child_leaf)
# 4.
if len(_child_leaf.dataset) < 10:
_child_leaf.terminateBuilding = True
result_leaf.append(_child_leaf)
"""
# 5.
# =========================================
_child_leaf.predict = decisions[num_of_decisions.index(max(num_of_decisions))]
leaf_list.append(_child_leaf)
_leaf.terminateBuilding = True # branch 를 마친 parent leaf 는 branch 중지 해야함
sleep(0.1)
# =========================================
depth += 1
return result_leaf, leaf_list, root
def findGains(data, attribute, config):
gains = []
algorithm = config['algorithm']
entropy = calculateEntropy(data, config)
attribute = list(filter(lambda x: x.name not in data[0].usedCategorical, attribute))
for _index in range(len(attribute) - 1):
if attribute[_index].type is 'Continuous':
data = processContinuousFeatures(data, attribute[_index], entropy, config)
classes = set(map(lambda x: x.winner, data))
else:
classes = set(map(lambda x: x.__getattribute__(attribute[_index].name), data))
# =========================================
splitinfo = 0
if algorithm == 'ID3' or algorithm == 'C4.5':
gain = entropy
else:
gain = 0
for j in range(0, len(classes)):
current_class = list(classes)[j]
if attribute[_index].type is 'Continuous':
subdataset = list(filter(lambda x: x.winner == current_class, data))
else:
subdataset = list(filter(lambda x: x.__getattribute__(attribute[_index].name) == current_class, data))
subset_instances = len(subdataset)
class_probability = subset_instances / len(data)
if algorithm == 'ID3' or algorithm == 'C4.5':
subset_entropy = calculateEntropy(subdataset, config)
gain = gain - class_probability * subset_entropy
if algorithm == 'C4.5':
splitinfo = splitinfo - class_probability * math.log(class_probability, 2)
if algorithm == 'C4.5':
if splitinfo == 0:
splitinfo = 100 # this can be if data set consists of 2 rows and current column consists of 1 class. still decision can be made (decisions for these 2 rows same). set splitinfo to very large value to make gain ratio very small. in this way, we won't find this column as the most dominant one.
gain = gain / splitinfo
gains.append(gain)
winner_index = 0
if algorithm == "ID3":
winner_index = gains.index(max(gains))
elif algorithm == "C4.5":
winner_index = gains.index(max(gains))
winner_attribute = attribute[winner_index]
if winner_attribute.type is 'Continuous':
data = processContinuousFeatures(data, winner_attribute, entropy, config)
return winner_attribute, data
def calculateEntropy(data, config):
instances = len(data)
decisions = list(set(list(map(lambda x: x.Decision, data))))
entropy = 0
for i in decisions:
num_of_decisions = list(map(lambda x: x.Decision, data)).count(i)
class_probability = num_of_decisions / instances
entropy = entropy - class_probability * math.log(class_probability, 2)
return entropy
def processContinuousFeatures(data, attribute, entropy, config):
algorithm = config['algorithm']
if len(set(map(lambda x: x.__getattribute__(attribute.name), data))) <= 20:
unique_values = np.array(sorted(set(map(lambda x: x.__getattribute__(attribute.name), data))))
else:
unique_values = []
data_min = np.array(list(map(lambda x: x.__getattribute__(attribute.name), data))).min()
data_max = np.array(list(map(lambda x: x.__getattribute__(attribute.name), data))).max()
scales = list(range(7))
for scale in scales:
unique_values.append(data_min + ((data_max - data_min) / (len(scales) - 1) * scale))
subset_gainratios = []
subset_gains = []
if len(unique_values) == 1:
winner_threshold = unique_values[0]
for i in data:
if i.__getattribute__(attribute.name) <= winner_threshold:
i.winner = "<=" + str(winner_threshold)
else:
i.winner = ">" + str(winner_threshold)
return data
for i in range(0, len(unique_values) - 1):
threshold = unique_values[i]
subset1 = list(filter(lambda x: x.__getattribute__(attribute.name) <= threshold, data))
subset2 = list(filter(lambda x: x.__getattribute__(attribute.name) > threshold, data))
subset1_rows = len(subset1)
subset2_rows = len(subset2)
total_instances = len(data)
subset1_probability = subset1_rows / total_instances
subset2_probability = subset2_rows / total_instances
threshold_gain = 0
if algorithm == 'ID3' or algorithm == 'C4.5':
threshold_gain = entropy - subset1_probability * calculateEntropy(subset1,
config) - subset2_probability * calculateEntropy(
subset2, config)
subset_gains.append(threshold_gain)
if algorithm == 'C4.5': # C4.5 also need gain in the block above. That's why, instead of else if we used direct if condition here
#threshold_splitinfo = -subset1_probability * math.log(subset1_probability,2) - subset2_probability * math.log(subset2_probability, 2)
#gainratio = threshold_gain / threshold_splitinfo
threshold_splitinfo = math.log(len(subset1)) - subset1_probability * math.log(len(subset1) * subset1_probability, 2) + math.log(len(subset2)) - subset2_probability * math.log(len(subset2) * subset2_probability, 2)
gainratio = threshold_gain/(1+threshold_splitinfo)
if gainratio is None:
print(1)
subset_gainratios.append(gainratio)
winner_one = 0
if algorithm == "C4.5":
if len(subset_gainratios) == 0:
print(1)
winner_one = subset_gainratios.index(max(subset_gainratios))
elif algorithm == "ID3": # actually, ID3 does not support for continuous features but we can still do it
winner_one = subset_gains.index(max(subset_gains))
winner_threshold = unique_values[winner_one]
for i in data:
if i.__getattribute__(attribute.name) <= winner_threshold:
i.winner = "<=" + str(round(winner_threshold, 3))
else:
i.winner = ">" + str(round(winner_threshold, 3))
return data
|
{"/MAPSC45.py": ["/Training.py", "/data_load.py"], "/Training.py": ["/data_load.py"], "/main.py": ["/MAPSC45.py", "/data_load.py", "/viztree.py"]}
|
20,094,339
|
jiyuha/C45
|
refs/heads/main
|
/main.py
|
import pandas as pd
import MAPSC45 as mc
import data_load
import time
from viztree import viztree
import pickle
import os
if __name__ == '__main__':
total_time = time.time()
start_time = time.time()
filename = 'wine'
df = pd.read_csv("dataset/"+filename+".csv")
train_data, test_data = mc.data_split(df, 0.3)
print(time.time() - start_time)
attribute_name = [i.replace(' ', '') for i in df]
# ===========================================================
#train_data_value, test_data_value = mc.preprocessingData(train_data.to_numpy(), test_data.to_numpy())
#train_data_value = train_data.to_numpy()
test_data_value = test_data.to_numpy()
train_data_value = df.to_numpy()
#test_data_value = df.to_numpy()
# ===========================================================
train_data = [data_load.Data(attribute_name, train_data_value[i])
for i in range(train_data_value.shape[0])] # train_data 의 모든 instance 들을 Data 클래스의 객체로 넣어줌
for i in range(len(train_data)):
train_data[i].id = i # returnToOriginData 에 쓰기 위해 instance 마다 id를 부여
test_data = [data_load.Data(attribute_name, test_data_value[i]) for i in
range(test_data_value.shape[0])] # test_data 의 모든 instance 들을 Data 클래스의 객체로 넣어줌
for i in range(len(test_data)):
test_data[i].id = i # returnToOriginData 에 쓰기 위해 instance 마다 id를 부여
# ===========================================================
# 데이터의 모든 attribute 를 Attribute 클래스의 객체로 넣어줌
attribute = []
for _name in attribute_name:
_name = data_load.Attribute()
attribute.append(_name)
for _index in range(len(attribute)):
attribute[_index].name = attribute_name[_index]
data_load.attribute_set(attribute[_index], train_data)
data_load.attribute_set(attribute[_index], test_data)
# ===========================================================
print(time.time() - start_time)
config = {'algorithm': 'C4.5'}
start_time = time.time()
max_depth = 7
if not os.path.exists('tree/'+filename+'_' + str(max_depth) + '.p'):
tree = mc.createTree(train_data, test_data, attribute, config, filename, max_depth=max_depth)
else:
with open('tree/'+filename+'_' + str(max_depth) + '.p', 'rb') as file:
tree = pickle.load(file)
print("=================================")
print('Creating time : ', time.time() - start_time)
tree.test_data = test_data
# ===========================================================
start_time = time.time()
tree.fit()
print("=================================")
print('Fitting time : ', time.time() - start_time)
# ===========================================================
start_time = time.time()
viztree(tree.leaf, tree.root) # Test set tree
print("=================================")
print('Visualizing : ', time.time() - start_time)
# ===========================================================
start_time = time.time()
TP, FN, FP, TN = mc.evaluate(tree.test_data)
print('Evaluate time : ', time.time() - start_time)
# ===========================================================
print('\nAccuracy : ', ((TP + TN)/len(test_data)) * 100, '%')
if (TP + FP) > 0:
print('Precision : ', (TP / (TP + FP)) * 100, '%')
if (TP + FN) > 0:
print('Recall : ', (TP / (TP + FN)) * 100, '%')
if ((TP + FP) > 0) and ((TP + FN) > 0):
print('F1 Score : ', ((2 * (TP / (TP + FP)) * (TP / (TP + FN))) / ((TP / (TP + FP)) + (TP / (TP + FN)))) * 100, '%')
print('\n\nTotal time : ', time.time() - total_time)
|
{"/MAPSC45.py": ["/Training.py", "/data_load.py"], "/Training.py": ["/data_load.py"], "/main.py": ["/MAPSC45.py", "/data_load.py", "/viztree.py"]}
|
20,189,115
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/ItemList.py
|
from collections import namedtuple
import logging
import random
from BaseClasses import Region, RegionType, Shop, ShopType, Location
from Bosses import place_bosses
from Dungeons import get_dungeon_item_pool
from EntranceShuffle import connect_entrance
from Fill import FillError, fill_restrictive
from Items import ItemFactory
import source.classes.constants as CONST
#This file sets the item pools for various modes. Timed modes and triforce hunt are enforced first, and then extra items are specified per mode to fill in the remaining space.
#Some basic items that various modes require are placed here, including pendants and crystals. Medallion requirements for the two relevant entrances are also decided.
alwaysitems = ['Bombos', 'Book of Mudora', 'Cane of Somaria', 'Ether', 'Fire Rod', 'Flippers', 'Ocarina', 'Hammer', 'Hookshot', 'Ice Rod', 'Lamp',
'Cape', 'Magic Powder', 'Mushroom', 'Pegasus Boots', 'Quake', 'Shovel', 'Bug Catching Net', 'Cane of Byrna', 'Blue Boomerang', 'Red Boomerang']
progressivegloves = ['Progressive Glove'] * 2
basicgloves = ['Power Glove', 'Titans Mitts']
normalbottles = ['Bottle', 'Bottle (Red Potion)', 'Bottle (Green Potion)', 'Bottle (Blue Potion)', 'Bottle (Fairy)', 'Bottle (Bee)', 'Bottle (Good Bee)']
hardbottles = ['Bottle', 'Bottle (Red Potion)', 'Bottle (Green Potion)', 'Bottle (Blue Potion)', 'Bottle (Bee)', 'Bottle (Good Bee)']
normalbaseitems = (['Magic Upgrade (1/2)', 'Single Arrow', 'Sanctuary Heart Container', 'Arrows (10)', 'Bombs (10)'] +
['Rupees (300)'] * 4 + ['Boss Heart Container'] * 10 + ['Piece of Heart'] * 24)
normalfirst15extra = ['Rupees (100)', 'Rupees (300)', 'Rupees (50)'] + ['Arrows (10)'] * 6 + ['Bombs (3)'] * 6
normalsecond15extra = ['Bombs (3)'] * 10 + ['Rupees (50)'] * 2 + ['Arrows (10)'] * 2 + ['Rupee (1)']
normalthird10extra = ['Rupees (50)'] * 4 + ['Rupees (20)'] * 3 + ['Arrows (10)', 'Rupee (1)', 'Rupees (5)']
normalfourth5extra = ['Arrows (10)'] * 2 + ['Rupees (20)'] * 2 + ['Rupees (5)']
normalfinal25extra = ['Rupees (20)'] * 23 + ['Rupees (5)'] * 2
Difficulty = namedtuple('Difficulty',
['baseitems', 'bottles', 'bottle_count', 'same_bottle', 'progressiveshield',
'basicshield', 'progressivearmor', 'basicarmor', 'swordless',
'progressivesword', 'basicsword', 'basicbow', 'timedohko', 'timedother',
'triforcehunt', 'triforce_pieces_required', 'retro',
'extras', 'progressive_sword_limit', 'progressive_shield_limit',
'progressive_armor_limit', 'progressive_bottle_limit',
'progressive_bow_limit', 'heart_piece_limit', 'boss_heart_container_limit'])
total_items_to_place = 153
difficulties = {
'normal': Difficulty(
baseitems = normalbaseitems,
bottles = normalbottles,
bottle_count = 4,
same_bottle = False,
progressiveshield = ['Progressive Shield'] * 3,
basicshield = ['Blue Shield', 'Red Shield', 'Mirror Shield'],
progressivearmor = ['Progressive Armor'] * 2,
basicarmor = ['Blue Mail', 'Red Mail'],
swordless = ['Rupees (20)'] * 4,
progressivesword = ['Progressive Sword'] * 4,
basicsword = ['Fighter Sword', 'Master Sword', 'Tempered Sword', 'Golden Sword'],
basicbow = ['Bow', 'Silver Arrows'],
timedohko = ['Green Clock'] * 25,
timedother = ['Green Clock'] * 20 + ['Blue Clock'] * 10 + ['Red Clock'] * 10,
triforcehunt = ['Triforce Piece'] * 30,
triforce_pieces_required = 20,
retro = ['Small Key (Universal)'] * 18 + ['Rupees (20)'] * 10,
extras = [normalfirst15extra, normalsecond15extra, normalthird10extra, normalfourth5extra, normalfinal25extra],
progressive_sword_limit = 4,
progressive_shield_limit = 3,
progressive_armor_limit = 2,
progressive_bow_limit = 2,
progressive_bottle_limit = 4,
boss_heart_container_limit = 255,
heart_piece_limit = 255,
),
'hard': Difficulty(
baseitems = normalbaseitems,
bottles = hardbottles,
bottle_count = 4,
same_bottle = False,
progressiveshield = ['Progressive Shield'] * 3,
basicshield = ['Blue Shield', 'Red Shield', 'Red Shield'],
progressivearmor = ['Progressive Armor'] * 2,
basicarmor = ['Progressive Armor'] * 2, # neither will count
swordless = ['Rupees (20)'] * 4,
progressivesword = ['Progressive Sword'] * 4,
basicsword = ['Fighter Sword', 'Master Sword', 'Master Sword', 'Tempered Sword'],
basicbow = ['Bow'] * 2,
timedohko = ['Green Clock'] * 25,
timedother = ['Green Clock'] * 20 + ['Blue Clock'] * 10 + ['Red Clock'] * 10,
triforcehunt = ['Triforce Piece'] * 30,
triforce_pieces_required = 20,
retro = ['Small Key (Universal)'] * 13 + ['Rupees (5)'] * 15,
extras = [normalfirst15extra, normalsecond15extra, normalthird10extra, normalfourth5extra, normalfinal25extra],
progressive_sword_limit = 3,
progressive_shield_limit = 2,
progressive_armor_limit = 0,
progressive_bow_limit = 1,
progressive_bottle_limit = 4,
boss_heart_container_limit = 6,
heart_piece_limit = 16,
),
'expert': Difficulty(
baseitems = normalbaseitems,
bottles = hardbottles,
bottle_count = 4,
same_bottle = False,
progressiveshield = ['Progressive Shield'] * 3,
basicshield = ['Progressive Shield'] * 3, #only the first one will upgrade, making this equivalent to two blue shields
progressivearmor = ['Progressive Armor'] * 2, # neither will count
basicarmor = ['Progressive Armor'] * 2, # neither will count
swordless = ['Rupees (20)'] * 4,
progressivesword = ['Progressive Sword'] * 4,
basicsword = ['Fighter Sword', 'Fighter Sword', 'Master Sword', 'Master Sword'],
basicbow = ['Bow'] * 2,
timedohko = ['Green Clock'] * 20 + ['Red Clock'] * 5,
timedother = ['Green Clock'] * 20 + ['Blue Clock'] * 10 + ['Red Clock'] * 10,
triforcehunt = ['Triforce Piece'] * 30,
triforce_pieces_required = 20,
retro = ['Small Key (Universal)'] * 13 + ['Rupees (5)'] * 15,
extras = [normalfirst15extra, normalsecond15extra, normalthird10extra, normalfourth5extra, normalfinal25extra],
progressive_sword_limit = 2,
progressive_shield_limit = 1,
progressive_armor_limit = 0,
progressive_bow_limit = 1,
progressive_bottle_limit = 4,
boss_heart_container_limit = 2,
heart_piece_limit = 8,
),
}
# Translate between Mike's label array and YAML/JSON keys
def get_custom_array_key(item):
label_switcher = {
"silverarrow": "silversupgrade",
"blueboomerang": "boomerang",
"redboomerang": "redmerang",
"ocarina": "flute",
"bugcatchingnet": "bugnet",
"bookofmudora": "book",
"pegasusboots": "boots",
"titansmitts": "titansmitt",
"pieceofheart": "heartpiece",
"bossheartcontainer": "heartcontainer",
"sanctuaryheartcontainer": "sancheart",
"mastersword": "sword2",
"temperedsword": "sword3",
"goldensword": "sword4",
"blueshield": "shield1",
"redshield": "shield2",
"mirrorshield": "shield3",
"bluemail": "mail2",
"redmail": "mail3",
"progressivearmor": "progressivemail",
"splus12": "halfmagic",
"splus14": "quartermagic",
"singlearrow": "arrow1",
"singlebomb": "bomb1",
"triforcepiece": "triforcepieces"
}
key = item.lower()
trans = {
" ": "",
'(': "",
'/': "",
')': "",
'+': "",
"magic": "",
"caneof": "",
"upgrade": "splus",
"arrows": "arrow",
"arrowplus": "arrowsplus",
"bombs": "bomb",
"bombplus": "bombsplus",
"rupees": "rupee"
}
for check in trans:
repl = trans[check]
key = key.replace(check,repl)
if key in label_switcher:
key = label_switcher.get(key)
return key
def generate_itempool(world, player):
if (world.difficulty[player] not in ['normal', 'hard', 'expert'] or world.goal[player] not in ['ganon', 'pedestal', 'dungeons', 'triforcehunt', 'crystals']
or world.mode[player] not in ['open', 'standard', 'inverted'] or world.timer not in ['none', 'display', 'timed', 'timed-ohko', 'ohko', 'timed-countdown'] or world.progressive not in ['on', 'off', 'random']):
raise NotImplementedError('Not supported yet')
if world.timer in ['ohko', 'timed-ohko']:
world.can_take_damage = False
if world.goal[player] in ['pedestal', 'triforcehunt']:
world.push_item(world.get_location('Ganon', player), ItemFactory('Nothing', player), False)
else:
world.push_item(world.get_location('Ganon', player), ItemFactory('Triforce', player), False)
if world.goal[player] in ['triforcehunt']:
region = world.get_region('Light World',player)
loc = Location(player, "Murahdahla", parent=region)
loc.access_rule = lambda state: state.item_count('Triforce Piece', player) + state.item_count('Power Star', player) >= state.world.treasure_hunt_count[player]
region.locations.append(loc)
world.dynamic_locations.append(loc)
world.clear_location_cache()
world.push_item(loc, ItemFactory('Triforce', player), False)
loc.event = True
loc.locked = True
world.get_location('Ganon', player).event = True
world.get_location('Ganon', player).locked = True
world.push_item(world.get_location('Agahnim 1', player), ItemFactory('Beat Agahnim 1', player), False)
world.get_location('Agahnim 1', player).event = True
world.get_location('Agahnim 1', player).locked = True
world.push_item(world.get_location('Agahnim 2', player), ItemFactory('Beat Agahnim 2', player), False)
world.get_location('Agahnim 2', player).event = True
world.get_location('Agahnim 2', player).locked = True
world.push_item(world.get_location('Dark Blacksmith Ruins', player), ItemFactory('Pick Up Purple Chest', player), False)
world.get_location('Dark Blacksmith Ruins', player).event = True
world.get_location('Dark Blacksmith Ruins', player).locked = True
world.push_item(world.get_location('Frog', player), ItemFactory('Get Frog', player), False)
world.get_location('Frog', player).event = True
world.get_location('Frog', player).locked = True
world.push_item(world.get_location('Missing Smith', player), ItemFactory('Return Smith', player), False)
world.get_location('Missing Smith', player).event = True
world.get_location('Missing Smith', player).locked = True
world.push_item(world.get_location('Floodgate', player), ItemFactory('Open Floodgate', player), False)
world.get_location('Floodgate', player).event = True
world.get_location('Floodgate', player).locked = True
world.push_item(world.get_location('Trench 1 Switch', player), ItemFactory('Trench 1 Filled', player), False)
world.get_location('Trench 1 Switch', player).event = True
world.get_location('Trench 1 Switch', player).locked = True
world.push_item(world.get_location('Trench 2 Switch', player), ItemFactory('Trench 2 Filled', player), False)
world.get_location('Trench 2 Switch', player).event = True
world.get_location('Trench 2 Switch', player).locked = True
world.push_item(world.get_location('Swamp Drain', player), ItemFactory('Drained Swamp', player), False)
world.get_location('Swamp Drain', player).event = True
world.get_location('Swamp Drain', player).locked = True
world.push_item(world.get_location('Attic Cracked Floor', player), ItemFactory('Shining Light', player), False)
world.get_location('Attic Cracked Floor', player).event = True
world.get_location('Attic Cracked Floor', player).locked = True
world.push_item(world.get_location('Suspicious Maiden', player), ItemFactory('Maiden Rescued', player), False)
world.get_location('Suspicious Maiden', player).event = True
world.get_location('Suspicious Maiden', player).locked = True
world.push_item(world.get_location('Revealing Light', player), ItemFactory('Maiden Unmasked', player), False)
world.get_location('Revealing Light', player).event = True
world.get_location('Revealing Light', player).locked = True
world.push_item(world.get_location('Ice Block Drop', player), ItemFactory('Convenient Block', player), False)
world.get_location('Ice Block Drop', player).event = True
world.get_location('Ice Block Drop', player).locked = True
if world.mode[player] == 'standard':
world.push_item(world.get_location('Zelda Pickup', player), ItemFactory('Zelda Herself', player), False)
world.get_location('Zelda Pickup', player).event = True
world.get_location('Zelda Pickup', player).locked = True
world.push_item(world.get_location('Zelda Drop Off', player), ItemFactory('Zelda Delivered', player), False)
world.get_location('Zelda Drop Off', player).event = True
world.get_location('Zelda Drop Off', player).locked = True
# set up item pool
if world.custom:
(pool, placed_items, precollected_items, clock_mode, treasure_hunt_count, treasure_hunt_icon, lamps_needed_for_dark_rooms) = make_custom_item_pool(world.progressive, world.shuffle[player], world.difficulty[player], world.timer, world.goal[player], world.mode[player], world.swords[player], world.retro[player], world.customitemarray)
world.rupoor_cost = min(world.customitemarray[player]["rupoorcost"], 9999)
else:
(pool, placed_items, precollected_items, clock_mode, treasure_hunt_count, treasure_hunt_icon, lamps_needed_for_dark_rooms) = get_pool_core(world.progressive, world.shuffle[player], world.difficulty[player], world.timer, world.goal[player], world.mode[player], world.swords[player], world.retro[player], world.doorShuffle[player])
if player in world.pool_adjustment.keys():
amt = world.pool_adjustment[player]
if amt < 0:
for _ in range(amt, 0):
pool.remove('Rupees (20)')
elif amt > 0:
for _ in range(0, amt):
pool.append('Rupees (20)')
for item in precollected_items:
world.push_precollected(ItemFactory(item, player))
if world.mode[player] == 'standard' and not world.state.has_blunt_weapon(player):
if "Link's Uncle" not in placed_items:
found_sword = False
found_bow = False
possible_weapons = []
for item in pool:
if item in ['Progressive Sword', 'Fighter Sword', 'Master Sword', 'Tempered Sword', 'Golden Sword']:
if not found_sword and world.swords[player] != 'swordless':
found_sword = True
possible_weapons.append(item)
if item in ['Progressive Bow', 'Bow'] and not found_bow:
found_bow = True
possible_weapons.append(item)
if item in ['Hammer', 'Fire Rod', 'Cane of Somaria', 'Cane of Byrna']:
if item not in possible_weapons:
possible_weapons.append(item)
if item in ['Bombs (10)']:
if item not in possible_weapons and world.doorShuffle[player] != 'crossed':
possible_weapons.append(item)
starting_weapon = random.choice(possible_weapons)
placed_items["Link's Uncle"] = starting_weapon
pool.remove(starting_weapon)
if placed_items["Link's Uncle"] in ['Bow', 'Progressive Bow', 'Bombs (10)', 'Cane of Somaria', 'Cane of Byrna'] and world.enemy_health[player] not in ['default', 'easy']:
world.escape_assist[player].append('bombs')
for (location, item) in placed_items.items():
world.push_item(world.get_location(location, player), ItemFactory(item, player), False)
world.get_location(location, player).event = True
world.get_location(location, player).locked = True
items = ItemFactory(pool, player)
world.lamps_needed_for_dark_rooms = lamps_needed_for_dark_rooms
if clock_mode is not None:
world.clock_mode = clock_mode
if treasure_hunt_count is not None:
world.treasure_hunt_count[player] = treasure_hunt_count
if treasure_hunt_icon is not None:
world.treasure_hunt_icon[player] = treasure_hunt_icon
world.itempool.extend([item for item in get_dungeon_item_pool(world) if item.player == player
and ((item.smallkey and world.keyshuffle[player])
or (item.bigkey and world.bigkeyshuffle[player])
or (item.map and world.mapshuffle[player])
or (item.compass and world.compassshuffle[player]))])
# logic has some branches where having 4 hearts is one possible requirement (of several alternatives)
# rather than making all hearts/heart pieces progression items (which slows down generation considerably)
# We mark one random heart container as an advancement item (or 4 heart pieces in expert mode)
if world.difficulty[player] in ['normal', 'hard'] and not (world.custom and world.customitemarray[player]["heartcontainer"] == 0):
[item for item in items if item.name == 'Boss Heart Container'][0].advancement = True
elif world.difficulty[player] in ['expert'] and not (world.custom and world.customitemarray[player]["heartpiece"] < 4):
adv_heart_pieces = [item for item in items if item.name == 'Piece of Heart'][0:4]
for hp in adv_heart_pieces:
hp.advancement = True
beeweights = {0: {None: 100},
1: {None: 75, 'trap': 25},
2: {None: 40, 'trap': 40, 'bee': 20},
3: {'trap': 50, 'bee': 50},
4: {'trap': 100}}
def beemizer(item):
if world.beemizer[item.player] and not item.advancement and not item.priority and not item.type:
choice = random.choices(list(beeweights[world.beemizer[item.player]].keys()), weights=list(beeweights[world.beemizer[item.player]].values()))[0]
return item if not choice else ItemFactory("Bee Trap", player) if choice == 'trap' else ItemFactory("Bee", player)
return item
world.itempool += [beemizer(item) for item in items]
# shuffle medallions
mm_medallion = ['Ether', 'Quake', 'Bombos'][random.randint(0, 2)]
tr_medallion = ['Ether', 'Quake', 'Bombos'][random.randint(0, 2)]
world.required_medallions[player] = (mm_medallion, tr_medallion)
place_bosses(world, player)
set_up_shops(world, player)
if world.retro[player]:
set_up_take_anys(world, player)
create_dynamic_shop_locations(world, player)
take_any_locations = [
'Snitch Lady (East)', 'Snitch Lady (West)', 'Bush Covered House', 'Light World Bomb Hut',
'Fortune Teller (Light)', 'Lake Hylia Fortune Teller', 'Lumberjack House', 'Bonk Fairy (Light)',
'Bonk Fairy (Dark)', 'Lake Hylia Healer Fairy', 'Swamp Healer Fairy', 'Desert Healer Fairy',
'Dark Lake Hylia Healer Fairy', 'Dark Lake Hylia Ledge Healer Fairy', 'Dark Desert Healer Fairy',
'Dark Death Mountain Healer Fairy', 'Long Fairy Cave', 'Good Bee Cave', '20 Rupee Cave',
'Kakariko Gamble Game', '50 Rupee Cave', 'Lost Woods Gamble', 'Hookshot Fairy',
'Palace of Darkness Hint', 'East Dark World Hint', 'Archery Game', 'Dark Lake Hylia Ledge Hint',
'Dark Lake Hylia Ledge Spike Cave', 'Fortune Teller (Dark)', 'Dark Sanctuary Hint', 'Dark Desert Hint']
def set_up_take_anys(world, player):
if world.mode[player] == 'inverted' and 'Dark Sanctuary Hint' in take_any_locations:
take_any_locations.remove('Dark Sanctuary Hint')
regions = random.sample(take_any_locations, 5)
old_man_take_any = Region("Old Man Sword Cave", RegionType.Cave, 'the sword cave', player)
world.regions.append(old_man_take_any)
world.dynamic_regions.append(old_man_take_any)
reg = regions.pop()
entrance = world.get_region(reg, player).entrances[0]
connect_entrance(world, entrance, old_man_take_any, player)
entrance.target = 0x58
old_man_take_any.shop = Shop(old_man_take_any, 0x0112, ShopType.TakeAny, 0xE2, True, True)
world.shops.append(old_man_take_any.shop)
swords = [item for item in world.itempool if item.type == 'Sword' and item.player == player]
if swords:
sword = random.choice(swords)
world.itempool.remove(sword)
world.itempool.append(ItemFactory('Rupees (20)', player))
old_man_take_any.shop.add_inventory(0, sword.name, 0, 0, create_location=True)
else:
old_man_take_any.shop.add_inventory(0, 'Rupees (300)', 0, 0)
for num in range(4):
take_any = Region("Take-Any #{}".format(num+1), RegionType.Cave, 'a cave of choice', player)
world.regions.append(take_any)
world.dynamic_regions.append(take_any)
target, room_id = random.choice([(0x58, 0x0112), (0x60, 0x010F), (0x46, 0x011F)])
reg = regions.pop()
entrance = world.get_region(reg, player).entrances[0]
connect_entrance(world, entrance, take_any, player)
entrance.target = target
take_any.shop = Shop(take_any, room_id, ShopType.TakeAny, 0xE3, True, True)
world.shops.append(take_any.shop)
take_any.shop.add_inventory(0, 'Blue Potion', 0, 0)
take_any.shop.add_inventory(1, 'Boss Heart Container', 0, 0)
world.initialize_regions()
def create_dynamic_shop_locations(world, player):
for shop in world.shops:
if shop.region.player == player:
for i, item in enumerate(shop.inventory):
if item is None:
continue
if item['create_location']:
loc = Location(player, "{} Item {}".format(shop.region.name, i+1), parent=shop.region)
shop.region.locations.append(loc)
world.dynamic_locations.append(loc)
world.clear_location_cache()
world.push_item(loc, ItemFactory(item['item'], player), False)
loc.event = True
loc.locked = True
def fill_prizes(world, attempts=15):
all_state = world.get_all_state(keys=True)
for player in range(1, world.players + 1):
crystals = ItemFactory(['Red Pendant', 'Blue Pendant', 'Green Pendant', 'Crystal 1', 'Crystal 2', 'Crystal 3', 'Crystal 4', 'Crystal 7', 'Crystal 5', 'Crystal 6'], player)
crystal_locations = [world.get_location('Turtle Rock - Prize', player), world.get_location('Eastern Palace - Prize', player), world.get_location('Desert Palace - Prize', player), world.get_location('Tower of Hera - Prize', player), world.get_location('Palace of Darkness - Prize', player),
world.get_location('Thieves\' Town - Prize', player), world.get_location('Skull Woods - Prize', player), world.get_location('Swamp Palace - Prize', player), world.get_location('Ice Palace - Prize', player),
world.get_location('Misery Mire - Prize', player)]
placed_prizes = [loc.item.name for loc in crystal_locations if loc.item is not None]
unplaced_prizes = [crystal for crystal in crystals if crystal.name not in placed_prizes]
empty_crystal_locations = [loc for loc in crystal_locations if loc.item is None]
for attempt in range(attempts):
try:
prizepool = list(unplaced_prizes)
prize_locs = list(empty_crystal_locations)
random.shuffle(prizepool)
random.shuffle(prize_locs)
fill_restrictive(world, all_state, prize_locs, prizepool, single_player_placement=True)
except FillError as e:
logging.getLogger('').info("Failed to place dungeon prizes (%s). Will retry %s more times", e, attempts - attempt - 1)
for location in empty_crystal_locations:
location.item = None
continue
break
else:
raise FillError('Unable to place dungeon prizes')
def set_up_shops(world, player):
# TODO: move hard+ mode changes for sheilds here, utilizing the new shops
if world.retro[player]:
rss = world.get_region('Red Shield Shop', player).shop
if not rss.locked:
rss.custom = True
rss.add_inventory(2, 'Single Arrow', 80)
for shop in random.sample([s for s in world.shops if not s.locked and s.region.player == player], 5):
shop.custom = True
shop.locked = True
shop.add_inventory(0, 'Single Arrow', 80)
shop.add_inventory(1, 'Small Key (Universal)', 100)
shop.add_inventory(2, 'Bombs (10)', 50)
rss.locked = True
def get_pool_core(progressive, shuffle, difficulty, timer, goal, mode, swords, retro, door_shuffle):
pool = []
placed_items = {}
precollected_items = []
clock_mode = None
treasure_hunt_count = None
treasure_hunt_icon = None
pool.extend(alwaysitems)
def place_item(loc, item):
assert loc not in placed_items
placed_items[loc] = item
def want_progressives():
return random.choice([True, False]) if progressive == 'random' else progressive == 'on'
if want_progressives():
pool.extend(progressivegloves)
else:
pool.extend(basicgloves)
lamps_needed_for_dark_rooms = 1
# insanity shuffle doesn't have fake LW/DW logic so for now guaranteed Mirror and Moon Pearl at the start
if shuffle == 'insanity_legacy':
place_item('Link\'s House', 'Magic Mirror')
place_item('Sanctuary', 'Moon Pearl')
else:
pool.extend(['Magic Mirror', 'Moon Pearl'])
if timer == 'display':
clock_mode = 'stopwatch'
elif timer == 'ohko':
clock_mode = 'ohko'
diff = difficulties[difficulty]
pool.extend(diff.baseitems)
# expert+ difficulties produce the same contents for
# all bottles, since only one bottle is available
if diff.same_bottle:
thisbottle = random.choice(diff.bottles)
for _ in range(diff.bottle_count):
if not diff.same_bottle:
thisbottle = random.choice(diff.bottles)
pool.append(thisbottle)
if want_progressives():
pool.extend(diff.progressiveshield)
else:
pool.extend(diff.basicshield)
if want_progressives():
pool.extend(diff.progressivearmor)
else:
pool.extend(diff.basicarmor)
if want_progressives():
pool.extend(['Progressive Bow'] * 2)
elif swords != 'swordless':
pool.extend(diff.basicbow)
else:
pool.extend(['Bow', 'Silver Arrows'])
if swords == 'swordless':
pool.extend(diff.swordless)
elif swords == 'vanilla':
swords_to_use = diff.progressivesword.copy() if want_progressives() else diff.basicsword.copy()
random.shuffle(swords_to_use)
place_item('Link\'s Uncle', swords_to_use.pop())
place_item('Blacksmith', swords_to_use.pop())
place_item('Pyramid Fairy - Left', swords_to_use.pop())
if goal != 'pedestal':
place_item('Master Sword Pedestal', swords_to_use.pop())
else:
place_item('Master Sword Pedestal', 'Triforce')
else:
pool.extend(diff.progressivesword if want_progressives() else diff.basicsword)
if swords == 'assured':
if want_progressives():
precollected_items.append('Progressive Sword')
pool.remove('Progressive Sword')
else:
precollected_items.append('Fighter Sword')
pool.remove('Fighter Sword')
pool.extend(['Rupees (50)'])
extraitems = total_items_to_place - len(pool) - len(placed_items)
if timer in ['timed', 'timed-countdown']:
pool.extend(diff.timedother)
extraitems -= len(diff.timedother)
clock_mode = 'stopwatch' if timer == 'timed' else 'countdown'
elif timer == 'timed-ohko':
pool.extend(diff.timedohko)
extraitems -= len(diff.timedohko)
clock_mode = 'countdown-ohko'
if goal == 'triforcehunt':
pool.extend(diff.triforcehunt)
extraitems -= len(diff.triforcehunt)
treasure_hunt_count = diff.triforce_pieces_required
treasure_hunt_icon = 'Triforce Piece'
for extra in diff.extras:
if extraitems > 0:
pool.extend(extra)
extraitems -= len(extra)
if goal == 'pedestal' and swords != 'vanilla':
place_item('Master Sword Pedestal', 'Triforce')
if retro:
pool = [item.replace('Single Arrow','Rupees (5)') for item in pool]
pool = [item.replace('Arrows (10)','Rupees (5)') for item in pool]
pool = [item.replace('Arrow Upgrade (+5)','Rupees (5)') for item in pool]
pool = [item.replace('Arrow Upgrade (+10)','Rupees (5)') for item in pool]
pool.extend(diff.retro)
if mode == 'standard':
if door_shuffle == 'vanilla':
key_location = random.choice(['Secret Passage', 'Hyrule Castle - Boomerang Chest', 'Hyrule Castle - Map Chest', 'Hyrule Castle - Zelda\'s Chest', 'Sewers - Dark Cross'])
place_item(key_location, 'Small Key (Universal)')
else:
pool.extend(['Small Key (Universal)'])
else:
pool.extend(['Small Key (Universal)'])
return (pool, placed_items, precollected_items, clock_mode, treasure_hunt_count, treasure_hunt_icon, lamps_needed_for_dark_rooms)
def make_custom_item_pool(progressive, shuffle, difficulty, timer, goal, mode, swords, retro, customitemarray):
if isinstance(customitemarray,dict) and 1 in customitemarray:
customitemarray = customitemarray[1]
pool = []
placed_items = {}
precollected_items = []
clock_mode = None
treasure_hunt_count = None
treasure_hunt_icon = None
def place_item(loc, item):
assert loc not in placed_items
placed_items[loc] = item
# Correct for insanely oversized item counts and take initial steps to handle undersized pools.
# Bow to Silver Arrows Upgrade, including Generic Keys & Rupoors
for x in [*range(0, 66 + 1), 68, 69]:
key = CONST.CUSTOMITEMS[x]
if customitemarray[key] > total_items_to_place:
customitemarray[key] = total_items_to_place
# Triforce
if customitemarray["triforce"] > total_items_to_place:
customitemarray["triforce"] = total_items_to_place
itemtotal = 0
# Bow to Silver Arrows Upgrade, including Generic Keys & Rupoors
for x in [*range(0, 66 + 1), 68, 69]:
key = CONST.CUSTOMITEMS[x]
itemtotal = itemtotal + customitemarray[key]
# Triforce
itemtotal = itemtotal + customitemarray["triforce"]
# Generic Keys
itemtotal = itemtotal + customitemarray["generickeys"]
customitems = [
"Bow", "Silver Arrows", "Blue Boomerang", "Red Boomerang", "Hookshot", "Mushroom", "Magic Powder", "Fire Rod", "Ice Rod", "Bombos", "Ether", "Quake", "Lamp", "Hammer", "Shovel", "Ocarina", "Bug Catching Net", "Book of Mudora", "Cane of Somaria", "Cane of Byrna", "Cape", "Pegasus Boots", "Power Glove", "Titans Mitts", "Progressive Glove", "Flippers", "Piece of Heart", "Boss Heart Container", "Sanctuary Heart Container", "Master Sword", "Tempered Sword", "Golden Sword", "Blue Shield", "Red Shield", "Mirror Shield", "Progressive Shield", "Blue Mail", "Red Mail", "Progressive Armor", "Magic Upgrade (1/2)", "Magic Upgrade (1/4)", "Bomb Upgrade (+5)", "Bomb Upgrade (+10)", "Arrow Upgrade (+5)", "Arrow Upgrade (+10)", "Single Arrow", "Arrows (10)", "Single Bomb", "Bombs (3)", "Rupee (1)", "Rupees (5)", "Rupees (20)", "Rupees (50)", "Rupees (100)", "Rupees (300)", "Rupoor", "Blue Clock", "Green Clock", "Red Clock", "Progressive Bow", "Bombs (10)", "Triforce Piece", "Triforce"
]
for customitem in customitems:
pool.extend([customitem] * customitemarray[get_custom_array_key(customitem)])
diff = difficulties[difficulty]
lamps_needed_for_dark_rooms = 1
# expert+ difficulties produce the same contents for
# all bottles, since only one bottle is available
if diff.same_bottle:
thisbottle = random.choice(diff.bottles)
for _ in range(customitemarray["bottle"]):
if not diff.same_bottle:
thisbottle = random.choice(diff.bottles)
pool.append(thisbottle)
if customitemarray["triforcepieces"] > 0 or customitemarray["triforcepiecesgoal"] > 0:
treasure_hunt_count = max(min(customitemarray["triforcepiecesgoal"], 99), 1) #To display, count must be between 1 and 99.
treasure_hunt_icon = 'Triforce Piece'
# Ensure game is always possible to complete here, force sufficient pieces if the player is unwilling.
if (customitemarray["triforcepieces"] < treasure_hunt_count) and (goal == 'triforcehunt') and (customitemarray["triforce"] == 0):
extrapieces = treasure_hunt_count - customitemarray["triforcepieces"]
pool.extend(['Triforce Piece'] * extrapieces)
itemtotal = itemtotal + extrapieces
if timer in ['display', 'timed', 'timed-countdown']:
clock_mode = 'countdown' if timer == 'timed-countdown' else 'stopwatch'
elif timer == 'timed-ohko':
clock_mode = 'countdown-ohko'
elif timer == 'ohko':
clock_mode = 'ohko'
if goal == 'pedestal':
place_item('Master Sword Pedestal', 'Triforce')
itemtotal = itemtotal + 1
if mode == 'standard':
if retro:
key_location = random.choice(['Secret Passage', 'Hyrule Castle - Boomerang Chest', 'Hyrule Castle - Map Chest', 'Hyrule Castle - Zelda\'s Chest', 'Sewers - Dark Cross'])
place_item(key_location, 'Small Key (Universal)')
pool.extend(['Small Key (Universal)'] * max((customitemarray["generickeys"] - 1), 0))
else:
pool.extend(['Small Key (Universal)'] * customitemarray["generickeys"])
else:
pool.extend(['Small Key (Universal)'] * customitemarray["generickeys"])
pool.extend(['Fighter Sword'] * customitemarray["sword1"])
pool.extend(['Progressive Sword'] * customitemarray["progressivesword"])
if shuffle == 'insanity_legacy':
place_item('Link\'s House', 'Magic Mirror')
place_item('Sanctuary', 'Moon Pearl')
pool.extend(['Magic Mirror'] * max((customitemarray["mirror"] -1 ), 0))
pool.extend(['Moon Pearl'] * max((customitemarray["pearl"] - 1), 0))
else:
pool.extend(['Magic Mirror'] * customitemarray["mirror"])
pool.extend(['Moon Pearl'] * customitemarray["pearl"])
if retro:
itemtotal = itemtotal - 28 # Corrects for small keys not being in item pool in Retro Mode
if itemtotal < total_items_to_place:
nothings = total_items_to_place - itemtotal
# print("Placing " + str(nothings) + " Nothings")
pool.extend(['Nothing'] * nothings)
return (pool, placed_items, precollected_items, clock_mode, treasure_hunt_count, treasure_hunt_icon, lamps_needed_for_dark_rooms)
# A quick test to ensure all combinations generate the correct amount of items.
def test():
for difficulty in ['normal', 'hard', 'expert']:
for goal in ['ganon', 'triforcehunt', 'pedestal']:
for timer in ['none', 'display', 'timed', 'timed-ohko', 'ohko', 'timed-countdown']:
for mode in ['open', 'standard', 'inverted', 'retro']:
for swords in ['random', 'assured', 'swordless', 'vanilla']:
for progressive in ['on', 'off']:
for shuffle in ['full', 'insanity_legacy']:
for retro in [True, False]:
for door_shuffle in ['basic', 'crossed', 'vanilla']:
out = get_pool_core(progressive, shuffle, difficulty, timer, goal, mode, swords, retro, door_shuffle)
count = len(out[0]) + len(out[1])
correct_count = total_items_to_place
if goal == 'pedestal' and swords != 'vanilla':
# pedestal goals generate one extra item
correct_count += 1
if retro:
correct_count += 28
try:
assert count == correct_count, "expected {0} items but found {1} items for {2}".format(correct_count, count, (progressive, shuffle, difficulty, timer, goal, mode, swords, retro))
except AssertionError as e:
print(e)
if __name__ == '__main__':
test()
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,116
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/AdjusterMain.py
|
import os
import time
import logging
from Utils import output_path
from Rom import LocalRom, apply_rom_settings
def adjust(args):
start = time.process_time()
logger = logging.getLogger('')
logger.info('Patching ROM.')
outfilebase = os.path.basename(args.rom)[:-4] + '_adjusted'
if os.stat(args.rom).st_size in (0x200000, 0x400000) and os.path.splitext(args.rom)[-1].lower() == '.sfc':
rom = LocalRom(args.rom, False)
if os.path.isfile(args.baserom):
baserom = LocalRom(args.baserom, True)
rom.orig_buffer = baserom.orig_buffer
else:
raise RuntimeError('Provided Rom is not a valid Link to the Past Randomizer Rom. Please provide one for adjusting.')
if not hasattr(args,"sprite"):
args.sprite = None
apply_rom_settings(rom, args.heartbeep, args.heartcolor, args.quickswap, args.fastmenu, args.disablemusic, args.sprite, args.ow_palettes, args.uw_palettes)
rom.write_to_file(output_path('%s.sfc' % outfilebase))
logger.info('Done. Enjoy.')
logger.debug('Total Time: %s', time.process_time() - start)
return args
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,117
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/DoorShuffle.py
|
import random
from collections import defaultdict, deque
import logging
import operator as op
import time
from enum import unique, Flag
from functools import reduce
from BaseClasses import RegionType, Door, DoorType, Direction, Sector, CrystalBarrier
from Regions import key_only_locations
from Dungeons import dungeon_regions, region_starts, standard_starts, split_region_starts, flexible_starts
from Dungeons import dungeon_bigs, dungeon_keys, dungeon_hints
from Items import ItemFactory
from RoomData import DoorKind, PairedDoor
from DungeonGenerator import ExplorationState, convert_regions, generate_dungeon, pre_validate, determine_required_paths
from DungeonGenerator import create_dungeon_builders, split_dungeon_builder, simple_dungeon_builder, default_dungeon_entrances
from KeyDoorShuffle import analyze_dungeon, validate_vanilla_key_logic, build_key_layout, validate_key_layout
def link_doors(world, player):
# Drop-down connections & push blocks
for exitName, regionName in logical_connections:
connect_simple_door(world, exitName, regionName, player)
# These should all be connected for now as normal connections
for edge_a, edge_b in interior_doors:
connect_interior_doors(edge_a, edge_b, world, player)
# These connections are here because they are currently unable to be shuffled
for exitName, regionName in falldown_pits:
connect_simple_door(world, exitName, regionName, player)
for exitName, regionName in dungeon_warps:
connect_simple_door(world, exitName, regionName, player)
for ent, ext in ladders:
connect_two_way(world, ent, ext, player)
if world.intensity[player] < 2:
for entrance, ext in open_edges:
connect_two_way(world, entrance, ext, player)
for entrance, ext in straight_staircases:
connect_two_way(world, entrance, ext, player)
if world.doorShuffle[player] == 'vanilla':
for entrance, ext in open_edges:
connect_two_way(world, entrance, ext, player)
for entrance, ext in straight_staircases:
connect_two_way(world, entrance, ext, player)
for exitName, regionName in vanilla_logical_connections:
connect_simple_door(world, exitName, regionName, player)
for entrance, ext in spiral_staircases:
connect_two_way(world, entrance, ext, player)
for entrance, ext in default_door_connections:
connect_two_way(world, entrance, ext, player)
for ent, ext in default_one_way_connections:
connect_one_way(world, ent, ext, player)
vanilla_key_logic(world, player)
elif world.doorShuffle[player] == 'basic':
within_dungeon(world, player)
elif world.doorShuffle[player] == 'crossed':
cross_dungeon(world, player)
else:
logging.getLogger('').error('Invalid door shuffle setting: %s' % world.doorShuffle[player])
raise Exception('Invalid door shuffle setting: %s' % world.doorShuffle[player])
if world.doorShuffle[player] != 'vanilla':
create_door_spoiler(world, player)
# todo: I think this function is not necessary
def mark_regions(world, player):
# traverse dungeons and make sure dungeon property is assigned
player_dungeons = [dungeon for dungeon in world.dungeons if dungeon.player == player]
for dungeon in player_dungeons:
queue = deque(dungeon.regions)
while len(queue) > 0:
region = world.get_region(queue.popleft(), player)
if region.name not in dungeon.regions:
dungeon.regions.append(region.name)
region.dungeon = dungeon
for ext in region.exits:
d = world.check_for_door(ext.name, player)
connected = ext.connected_region
if d is not None and connected is not None:
if d.dest is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue:
queue.append(connected) # needs to be added
elif connected is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue:
queue.append(connected) # needs to be added
def create_door_spoiler(world, player):
logger = logging.getLogger('')
queue = deque(world.dungeon_layouts[player].values())
while len(queue) > 0:
builder = queue.popleft()
done = set()
start_regions = set(convert_regions(builder.layout_starts, world, player)) # todo: set all_entrances for basic
reg_queue = deque(start_regions)
visited = set(start_regions)
while len(reg_queue) > 0:
next = reg_queue.pop()
for ext in next.exits:
door_a = ext.door
connect = ext.connected_region
if door_a and door_a.type in [DoorType.Normal, DoorType.SpiralStairs, DoorType.Open,
DoorType.StraightStairs] and door_a not in done:
done.add(door_a)
door_b = door_a.dest
if door_b:
done.add(door_b)
if not door_a.blocked and not door_b.blocked:
world.spoiler.set_door(door_a.name, door_b.name, 'both', player, builder.name)
elif door_a.blocked:
world.spoiler.set_door(door_b.name, door_a.name, 'entrance', player, builder.name)
elif door_b.blocked:
world.spoiler.set_door(door_a.name, door_b.name, 'entrance', player, builder.name)
else:
logger.warning('This is a bug during door spoiler')
else:
logger.warning('Door not connected: %s', door_a.name)
if connect and connect.type == RegionType.Dungeon and connect not in visited:
visited.add(connect)
reg_queue.append(connect)
def vanilla_key_logic(world, player):
builders = []
world.dungeon_layouts[player] = {}
for dungeon in [dungeon for dungeon in world.dungeons if dungeon.player == player]:
sector = Sector()
sector.name = dungeon.name
sector.regions.extend(convert_regions(dungeon.regions, world, player))
builder = simple_dungeon_builder(sector.name, [sector])
builder.master_sector = sector
builders.append(builder)
world.dungeon_layouts[player][builder.name] = builder
overworld_prep(world, player)
for builder in builders:
origin_list = find_accessible_entrances(world, player, builder)
start_regions = convert_regions(origin_list, world, player)
doors = convert_key_doors(default_small_key_doors[builder.name], world, player)
key_layout = build_key_layout(builder, start_regions, doors, world, player)
valid = validate_key_layout(key_layout, world, player)
if not valid:
logging.getLogger('').warning('Vanilla key layout not valid %s', builder.name)
builder.key_door_proposal = doors
if player not in world.key_logic.keys():
world.key_logic[player] = {}
analyze_dungeon(key_layout, world, player)
world.key_logic[player][builder.name] = key_layout.key_logic
log_key_logic(builder.name, key_layout.key_logic)
if world.shuffle[player] == 'vanilla' and world.accessibility[player] == 'items' and not world.retro[player]:
validate_vanilla_key_logic(world, player)
# some useful functions
oppositemap = {
Direction.South: Direction.North,
Direction.North: Direction.South,
Direction.West: Direction.East,
Direction.East: Direction.West,
Direction.Up: Direction.Down,
Direction.Down: Direction.Up,
}
def switch_dir(direction):
return oppositemap[direction]
def convert_key_doors(key_doors, world, player):
result = []
for d in key_doors:
if type(d) is tuple:
result.append((world.get_door(d[0], player), world.get_door(d[1], player)))
else:
result.append(world.get_door(d, player))
return result
def connect_simple_door(world, exit_name, region_name, player):
region = world.get_region(region_name, player)
world.get_entrance(exit_name, player).connect(region)
d = world.check_for_door(exit_name, player)
if d is not None:
d.dest = region
def connect_door_only(world, exit_name, region, player):
d = world.check_for_door(exit_name, player)
if d is not None:
d.dest = region
def connect_interior_doors(a, b, world, player):
door_a = world.get_door(a, player)
door_b = world.get_door(b, player)
if door_a.blocked:
connect_one_way(world, b, a, player)
elif door_b.blocked:
connect_one_way(world, a, b, player)
else:
connect_two_way(world, a, b, player)
def connect_two_way(world, entrancename, exitname, player):
entrance = world.get_entrance(entrancename, player)
ext = world.get_entrance(exitname, player)
# if these were already connected somewhere, remove the backreference
if entrance.connected_region is not None:
entrance.connected_region.entrances.remove(entrance)
if ext.connected_region is not None:
ext.connected_region.entrances.remove(ext)
entrance.connect(ext.parent_region)
ext.connect(entrance.parent_region)
if entrance.parent_region.dungeon:
ext.parent_region.dungeon = entrance.parent_region.dungeon
x = world.check_for_door(entrancename, player)
y = world.check_for_door(exitname, player)
if x is not None:
x.dest = y
if y is not None:
y.dest = x
def connect_one_way(world, entrancename, exitname, player):
entrance = world.get_entrance(entrancename, player)
ext = world.get_entrance(exitname, player)
# if these were already connected somewhere, remove the backreference
if entrance.connected_region is not None:
entrance.connected_region.entrances.remove(entrance)
if ext.connected_region is not None:
ext.connected_region.entrances.remove(ext)
entrance.connect(ext.parent_region)
if entrance.parent_region.dungeon:
ext.parent_region.dungeon = entrance.parent_region.dungeon
x = world.check_for_door(entrancename, player)
y = world.check_for_door(exitname, player)
if x is not None:
x.dest = y
if y is not None:
y.dest = x
def fix_big_key_doors_with_ugly_smalls(world, player):
remove_ugly_small_key_doors(world, player)
unpair_big_key_doors(world, player)
def remove_ugly_small_key_doors(world, player):
for d in ['Eastern Hint Tile Blocked Path SE', 'Eastern Darkness S', 'Thieves Hallway SE', 'Mire Left Bridge S',
'TR Lava Escape SE', 'GT Hidden Spikes SE']:
door = world.get_door(d, player)
room = world.get_room(door.roomIndex, player)
room.change(door.doorListPos, DoorKind.Normal)
door.smallKey = False
door.ugly = False
def unpair_big_key_doors(world, player):
problematic_bk_doors = ['Eastern Courtyard N', 'Eastern Big Key NE', 'Thieves BK Corner NE', 'Mire BK Door Room N',
'TR Dodgers NE', 'GT Dash Hall NE']
for paired_door in world.paired_doors[player]:
if paired_door.door_a in problematic_bk_doors or paired_door.door_b in problematic_bk_doors:
paired_door.pair = False
def pair_existing_key_doors(world, player, door_a, door_b):
already_paired = False
door_names = [door_a.name, door_b.name]
for pd in world.paired_doors[player]:
if pd.door_a in door_names and pd.door_b in door_names:
already_paired = True
break
if already_paired:
return
for paired_door in world.paired_doors[player]:
if paired_door.door_a in door_names or paired_door.door_b in door_names:
paired_door.pair = False
world.paired_doors[player].append(PairedDoor(door_a, door_b))
# def unpair_all_doors(world, player):
# for paired_door in world.paired_doors[player]:
# paired_door.pair = False
def within_dungeon(world, player):
fix_big_key_doors_with_ugly_smalls(world, player)
overworld_prep(world, player)
entrances_map, potentials, connections = determine_entrance_list(world, player)
connections_tuple = (entrances_map, potentials, connections)
dungeon_builders = {}
for key in dungeon_regions.keys():
sector_list = convert_to_sectors(dungeon_regions[key], world, player)
dungeon_builders[key] = simple_dungeon_builder(key, sector_list)
dungeon_builders[key].entrance_list = list(entrances_map[key])
recombinant_builders = {}
builder_info = None, None, world, player
handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info)
main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player)
paths = determine_required_paths(world, player)
check_required_paths(paths, world, player)
# shuffle_key_doors for dungeons
logging.getLogger('').info(world.fish.translate("cli", "cli", "shuffling.keydoors"))
start = time.process_time()
for builder in world.dungeon_layouts[player].values():
shuffle_key_doors(builder, world, player)
logging.getLogger('').info('%s: %s', world.fish.translate("cli", "cli", "keydoor.shuffle.time"), time.process_time()-start)
smooth_door_pairs(world, player)
def handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info):
dungeon_entrances, split_dungeon_entrances, world, player = builder_info
if dungeon_entrances is None:
dungeon_entrances = default_dungeon_entrances
if split_dungeon_entrances is None:
split_dungeon_entrances = split_region_starts
builder_info = dungeon_entrances, split_region_starts, world, player
for name, split_list in split_dungeon_entrances.items():
builder = dungeon_builders.pop(name)
recombinant_builders[name] = builder
split_builders = split_dungeon_builder(builder, split_list, builder_info)
dungeon_builders.update(split_builders)
for sub_name, split_entrances in split_list.items():
sub_builder = dungeon_builders[name+' '+sub_name]
sub_builder.split_flag = True
entrance_list = list(split_entrances)
if name in flexible_starts.keys():
add_shuffled_entrances(sub_builder.sectors, flexible_starts[name], entrance_list)
filtered_entrance_list = [x for x in entrance_list if x in entrances_map[name]]
sub_builder.entrance_list = filtered_entrance_list
def main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player):
entrances_map, potentials, connections = connections_tuple
enabled_entrances = {}
sector_queue = deque(dungeon_builders.values())
last_key, loops = None, 0
logging.getLogger('').info(world.fish.translate("cli", "cli", "generating.dungeon"))
while len(sector_queue) > 0:
builder = sector_queue.popleft()
split_dungeon = builder.name.startswith('Desert Palace') or builder.name.startswith('Skull Woods')
name = builder.name
if split_dungeon:
name = ' '.join(builder.name.split(' ')[:-1])
origin_list = list(builder.entrance_list)
find_enabled_origins(builder.sectors, enabled_entrances, origin_list, entrances_map, name)
if len(origin_list) <= 0 or not pre_validate(builder, origin_list, split_dungeon, world, player):
if last_key == builder.name or loops > 1000:
origin_name = world.get_region(origin_list[0], player).entrances[0].parent_region.name if len(origin_list) > 0 else 'no origin'
raise Exception('Infinite loop detected for "%s" located at %s' % (builder.name, origin_name))
sector_queue.append(builder)
last_key = builder.name
loops += 1
else:
ds = generate_dungeon(builder, origin_list, split_dungeon, world, player)
find_new_entrances(ds, entrances_map, connections, potentials, enabled_entrances, world, player)
ds.name = name
builder.master_sector = ds
builder.layout_starts = origin_list if len(builder.entrance_list) <= 0 else builder.entrance_list
last_key = None
combine_layouts(recombinant_builders, dungeon_builders, entrances_map)
world.dungeon_layouts[player] = {}
for builder in dungeon_builders.values():
builder.entrance_list = builder.layout_starts = builder.path_entrances = find_accessible_entrances(world, player, builder)
world.dungeon_layouts[player] = dungeon_builders
def determine_entrance_list(world, player):
entrance_map = {}
potential_entrances = {}
connections = {}
for key, r_names in region_starts.items():
entrance_map[key] = []
if world.mode[player] == 'standard' and key in standard_starts.keys():
r_names = standard_starts[key]
for region_name in r_names:
region = world.get_region(region_name, player)
for ent in region.entrances:
parent = ent.parent_region
if (parent.type != RegionType.Dungeon and parent.name != 'Menu') or parent.name == 'Sewer Drop':
if parent.name not in world.inaccessible_regions[player]:
entrance_map[key].append(region_name)
else:
if ent.parent_region not in potential_entrances.keys():
potential_entrances[parent] = []
potential_entrances[parent].append(region_name)
connections[region_name] = parent
return entrance_map, potential_entrances, connections
def add_shuffled_entrances(sectors, region_list, entrance_list):
for sector in sectors:
for region in sector.regions:
if region.name in region_list:
entrance_list.append(region.name)
def find_enabled_origins(sectors, enabled, entrance_list, entrance_map, key):
for sector in sectors:
for region in sector.regions:
if region.name in enabled.keys() and region.name not in entrance_list:
entrance_list.append(region.name)
origin_reg, origin_dungeon = enabled[region.name]
if origin_reg != region.name and origin_dungeon != region.dungeon:
if key not in entrance_map.keys():
key = ' '.join(key.split(' ')[:-1])
entrance_map[key].append(region.name)
def find_new_entrances(sector, entrances_map, connections, potentials, enabled, world, player):
for region in sector.regions:
if region.name in connections.keys() and (connections[region.name] in potentials.keys() or connections[region.name].name in world.inaccessible_regions[player]):
enable_new_entrances(region, connections, potentials, enabled, world, player, region)
inverted_aga_check(entrances_map, connections, potentials, enabled, world, player)
def enable_new_entrances(region, connections, potentials, enabled, world, player, region_enabler):
new_region = connections[region.name]
if new_region in potentials.keys():
for potential in potentials.pop(new_region):
enabled[potential] = (region_enabler.name, region_enabler.dungeon)
# see if this unexplored region connects elsewhere
queue = deque(new_region.exits)
visited = set()
while len(queue) > 0:
ext = queue.popleft()
visited.add(ext)
region_name = ext.connected_region.name
if region_name in connections.keys() and connections[region_name] in potentials.keys():
for potential in potentials.pop(connections[region_name]):
enabled[potential] = (region.name, region.dungeon)
if ext.connected_region.name in world.inaccessible_regions[player]:
for new_exit in ext.connected_region.exits:
if new_exit not in visited:
queue.append(new_exit)
def inverted_aga_check(entrances_map, connections, potentials, enabled, world, player):
if world.mode[player] == 'inverted':
if 'Agahnims Tower' in entrances_map.keys() or aga_tower_enabled(enabled):
for region in list(potentials.keys()):
if region.name == 'Hyrule Castle Ledge':
enabler = world.get_region('Tower Agahnim 1', player)
for r_name in potentials[region]:
new_region = world.get_region(r_name, player)
enable_new_entrances(new_region, connections, potentials, enabled, world, player, enabler)
def aga_tower_enabled(enabled):
for region_name, enabled_tuple in enabled.items():
entrance, dungeon = enabled_tuple
if dungeon.name == 'Agahnims Tower':
return True
return False
# goals:
# 1. have enough chests to be interesting (2 more than dungeon items)
# 2. have a balanced amount of regions added (check)
# 3. prevent soft locks due to key usage (algorithm written)
# 4. rules in place to affect item placement (lamp, keys, etc. -- in rules)
# 5. to be complete -- all doors linked (check, somewhat)
# 6. avoid deadlocks/dead end dungeon (check)
# 7. certain paths through dungeon must be possible - be able to reach goals (check)
def cross_dungeon(world, player):
fix_big_key_doors_with_ugly_smalls(world, player)
overworld_prep(world, player)
entrances_map, potentials, connections = determine_entrance_list(world, player)
connections_tuple = (entrances_map, potentials, connections)
all_sectors, all_regions = [], []
for key in dungeon_regions.keys():
all_regions += dungeon_regions[key]
all_sectors.extend(convert_to_sectors(all_regions, world, player))
dungeon_builders = create_dungeon_builders(all_sectors, connections_tuple, world, player)
for builder in dungeon_builders.values():
builder.entrance_list = list(entrances_map[builder.name])
dungeon_obj = world.get_dungeon(builder.name, player)
for sector in builder.sectors:
for region in sector.regions:
region.dungeon = dungeon_obj
for loc in region.locations:
if loc.name in key_only_locations:
key_name = dungeon_keys[builder.name] if loc.name != 'Hyrule Castle - Big Key Drop' else dungeon_bigs[builder.name]
loc.forced_item = loc.item = ItemFactory(key_name, player)
recombinant_builders = {}
builder_info = None, None, world, player
handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info)
main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player)
paths = determine_required_paths(world, player)
check_required_paths(paths, world, player)
hc = world.get_dungeon('Hyrule Castle', player)
hc.dungeon_items.append(ItemFactory('Compass (Escape)', player))
at = world.get_dungeon('Agahnims Tower', player)
at.dungeon_items.append(ItemFactory('Compass (Agahnims Tower)', player))
at.dungeon_items.append(ItemFactory('Map (Agahnims Tower)', player))
assign_cross_keys(dungeon_builders, world, player)
all_dungeon_items = [y for x in world.dungeons if x.player == player for y in x.all_items]
target_items = 34 if world.retro[player] else 63
d_items = target_items - len(all_dungeon_items)
world.pool_adjustment[player] = d_items
smooth_door_pairs(world, player)
# Re-assign dungeon bosses
gt = world.get_dungeon('Ganons Tower', player)
for name, builder in dungeon_builders.items():
reassign_boss('GT Ice Armos', 'bottom', builder, gt, world, player)
reassign_boss('GT Lanmolas 2', 'middle', builder, gt, world, player)
reassign_boss('GT Moldorm', 'top', builder, gt, world, player)
refine_hints(dungeon_builders)
def assign_cross_keys(dungeon_builders, world, player):
logging.getLogger('').info(world.fish.translate("cli", "cli", "shuffling.keydoors"))
start = time.process_time()
total_keys = remaining = 29
total_candidates = 0
start_regions_map = {}
# Step 1: Find Small Key Door Candidates
for name, builder in dungeon_builders.items():
dungeon = world.get_dungeon(name, player)
if not builder.bk_required or builder.bk_provided:
dungeon.big_key = None
elif builder.bk_required and not builder.bk_provided:
dungeon.big_key = ItemFactory(dungeon_bigs[name], player)
start_regions = convert_regions(builder.path_entrances, world, player)
find_small_key_door_candidates(builder, start_regions, world, player)
builder.key_doors_num = max(0, len(builder.candidates) - builder.key_drop_cnt)
total_candidates += builder.key_doors_num
start_regions_map[name] = start_regions
# Step 2: Initial Key Number Assignment & Calculate Flexibility
for name, builder in dungeon_builders.items():
calculated = int(round(builder.key_doors_num*total_keys/total_candidates))
max_keys = builder.location_cnt - calc_used_dungeon_items(builder)
cand_len = max(0, len(builder.candidates) - builder.key_drop_cnt)
limit = min(max_keys, cand_len)
suggested = min(calculated, limit)
combo_size = ncr(len(builder.candidates), suggested + builder.key_drop_cnt)
while combo_size > 500000 and suggested > 0:
suggested -= 1
combo_size = ncr(len(builder.candidates), suggested + builder.key_drop_cnt)
builder.key_doors_num = suggested + builder.key_drop_cnt
remaining -= suggested
builder.combo_size = combo_size
if suggested < limit:
builder.flex = limit - suggested
# Step 3: Initial valid combination find - reduce flex if needed
for name, builder in dungeon_builders.items():
suggested = builder.key_doors_num - builder.key_drop_cnt
find_valid_combination(builder, start_regions_map[name], world, player)
actual_chest_keys = builder.key_doors_num - builder.key_drop_cnt
if actual_chest_keys < suggested:
remaining += suggested - actual_chest_keys
builder.flex = 0
# Step 4: Try to assign remaining keys
builder_order = [x for x in dungeon_builders.values() if x.flex > 0]
builder_order.sort(key=lambda b: b.combo_size)
queue = deque(builder_order)
logger = logging.getLogger('')
while len(queue) > 0 and remaining > 0:
builder = queue.popleft()
name = builder.name
logger.debug('Cross Dungeon: Increasing key count by 1 for %s', name)
builder.key_doors_num += 1
result = find_valid_combination(builder, start_regions_map[name], world, player, drop_keys=False)
if result:
remaining -= 1
builder.flex -= 1
if builder.flex > 0:
builder.combo_size = ncr(len(builder.candidates), builder.key_doors_num)
queue.append(builder)
queue = deque(sorted(queue, key=lambda b: b.combo_size))
else:
logger.debug('Cross Dungeon: Increase failed for %s', name)
builder.key_doors_num -= 1
builder.flex = 0
logger.debug('Cross Dungeon: Keys unable to assign in pool %s', remaining)
# Last Step: Adjust Small Key Dungeon Pool
if not world.retro[player]:
for name, builder in dungeon_builders.items():
reassign_key_doors(builder, world, player)
log_key_logic(builder.name, world.key_logic[player][builder.name])
actual_chest_keys = max(builder.key_doors_num - builder.key_drop_cnt, 0)
dungeon = world.get_dungeon(name, player)
if actual_chest_keys == 0:
dungeon.small_keys = []
else:
dungeon.small_keys = [ItemFactory(dungeon_keys[name], player)] * actual_chest_keys
logger.info('%s: %s', world.fish.translate("cli", "cli", "keydoor.shuffle.time.crossed"), time.process_time()-start)
def reassign_boss(boss_region, boss_key, builder, gt, world, player):
if boss_region in builder.master_sector.region_set():
new_dungeon = world.get_dungeon(builder.name, player)
if new_dungeon != gt:
gt_boss = gt.bosses.pop(boss_key)
new_dungeon.bosses[boss_key] = gt_boss
def refine_hints(dungeon_builders):
for name, builder in dungeon_builders.items():
for region in builder.master_sector.regions:
for location in region.locations:
if not location.event and '- Boss' not in location.name and '- Prize' not in location.name and location.name != 'Sanctuary':
location.hint_text = dungeon_hints[name]
def convert_to_sectors(region_names, world, player):
region_list = convert_regions(region_names, world, player)
sectors = []
while len(region_list) > 0:
region = region_list.pop()
new_sector = True
region_chunk = [region]
exits = []
exits.extend(region.exits)
outstanding_doors = []
matching_sectors = []
while len(exits) > 0:
ext = exits.pop()
door = ext.door
if ext.connected_region is not None or door is not None and door.controller is not None:
if door is not None and door.controller is not None:
connect_region = world.get_entrance(door.controller.name, player).parent_region
else:
connect_region = ext.connected_region
if connect_region not in region_chunk and connect_region in region_list:
region_list.remove(connect_region)
region_chunk.append(connect_region)
exits.extend(connect_region.exits)
if connect_region not in region_chunk:
for existing in sectors:
if connect_region in existing.regions:
new_sector = False
if existing not in matching_sectors:
matching_sectors.append(existing)
else:
if door is not None and door.controller is None and door.dest is None:
outstanding_doors.append(door)
sector = Sector()
if not new_sector:
for match in matching_sectors:
sector.regions.extend(match.regions)
sector.outstanding_doors.extend(match.outstanding_doors)
sectors.remove(match)
sector.regions.extend(region_chunk)
sector.outstanding_doors.extend(outstanding_doors)
sectors.append(sector)
return sectors
# those with split region starts like Desert/Skull combine for key layouts
def combine_layouts(recombinant_builders, dungeon_builders, entrances_map):
for recombine in recombinant_builders.values():
queue = deque(dungeon_builders.values())
while len(queue) > 0:
builder = queue.pop()
if builder.name.startswith(recombine.name):
del dungeon_builders[builder.name]
if recombine.master_sector is None:
recombine.master_sector = builder.master_sector
recombine.master_sector.name = recombine.name
recombine.pre_open_stonewall = builder.pre_open_stonewall
else:
recombine.master_sector.regions.extend(builder.master_sector.regions)
if builder.pre_open_stonewall:
recombine.pre_open_stonewall = builder.pre_open_stonewall
recombine.layout_starts = list(entrances_map[recombine.name])
dungeon_builders[recombine.name] = recombine
def valid_region_to_explore(region, world, player):
return region.type == RegionType.Dungeon or region.name in world.inaccessible_regions[player]
def shuffle_key_doors(builder, world, player):
start_regions = convert_regions(builder.path_entrances, world, player)
# count number of key doors - this could be a table?
num_key_doors = 0
skips = []
for region in builder.master_sector.regions:
for ext in region.exits:
d = world.check_for_door(ext.name, player)
if d is not None and d.smallKey:
if d not in skips:
if d.type == DoorType.Interior:
skips.append(d.dest)
if d.type == DoorType.Normal:
for dp in world.paired_doors[player]:
if d.name == dp.door_a:
skips.append(world.get_door(dp.door_b, player))
break
elif d.name == dp.door_b:
skips.append(world.get_door(dp.door_a, player))
break
num_key_doors += 1
builder.key_doors_num = num_key_doors
find_small_key_door_candidates(builder, start_regions, world, player)
find_valid_combination(builder, start_regions, world, player)
reassign_key_doors(builder, world, player)
log_key_logic(builder.name, world.key_logic[player][builder.name])
def find_current_key_doors(builder):
current_doors = []
for region in builder.master_sector.regions:
for ext in region.exits:
d = ext.door
if d and d.smallKey:
current_doors.append(d)
return current_doors
def find_small_key_door_candidates(builder, start_regions, world, player):
# traverse dungeon and find candidates
candidates = []
checked_doors = set()
for region in start_regions:
possible, checked = find_key_door_candidates(region, checked_doors, world, player)
candidates.extend([x for x in possible if x not in candidates])
checked_doors.update(checked)
flat_candidates = []
for candidate in candidates:
# not valid if: Normal and Pair in is Checked and Pair is not in Candidates
if candidate.type != DoorType.Normal or candidate.dest not in checked_doors or candidate.dest in candidates:
flat_candidates.append(candidate)
paired_candidates = build_pair_list(flat_candidates)
builder.candidates = paired_candidates
def calc_used_dungeon_items(builder):
base = 4
if builder.bk_required and not builder.bk_provided:
base += 1
if builder.name == 'Hyrule Castle':
base -= 1 # Missing compass/map
if builder.name == 'Agahnims Tower':
base -= 2 # Missing both compass/map
# gt can lose map once compasses work
return base
def find_valid_combination(builder, start_regions, world, player, drop_keys=True):
logger = logging.getLogger('')
# find valid combination of candidates
if len(builder.candidates) < builder.key_doors_num:
if not drop_keys:
logger.info('No valid layouts for %s with %s doors', builder.name, builder.key_doors_num)
return False
builder.key_doors_num = len(builder.candidates) # reduce number of key doors
logger.info('%s: %s', world.fish.translate("cli","cli","lowering.keys.candidates"), builder.name)
combinations = ncr(len(builder.candidates), builder.key_doors_num)
itr = 0
start = time.process_time()
sample_list = list(range(0, int(combinations)))
random.shuffle(sample_list)
proposal = kth_combination(sample_list[itr], builder.candidates, builder.key_doors_num)
key_layout = build_key_layout(builder, start_regions, proposal, world, player)
while not validate_key_layout(key_layout, world, player):
itr += 1
stop_early = False
if itr % 1000 == 0:
mark = time.process_time()-start
if (mark > 10 and itr*100/combinations > 50) or (mark > 20 and itr*100/combinations > 25) or mark > 30:
stop_early = True
if itr >= combinations or stop_early:
if not drop_keys:
logger.info('No valid layouts for %s with %s doors', builder.name, builder.key_doors_num)
return False
logger.info('%s: %s', world.fish.translate("cli","cli","lowering.keys.layouts"), builder.name)
builder.key_doors_num -= 1
if builder.key_doors_num < 0:
raise Exception('Bad dungeon %s - 0 key doors not valid' % builder.name)
combinations = ncr(len(builder.candidates), builder.key_doors_num)
sample_list = list(range(0, int(combinations)))
random.shuffle(sample_list)
itr = 0
start = time.process_time() # reset time since itr reset
proposal = kth_combination(sample_list[itr], builder.candidates, builder.key_doors_num)
key_layout.reset(proposal, builder, world, player)
if (itr+1) % 1000 == 0:
mark = time.process_time()-start
logger.info('%s time elapsed. %s iterations/s', mark, itr/mark)
# make changes
if player not in world.key_logic.keys():
world.key_logic[player] = {}
analyze_dungeon(key_layout, world, player)
builder.key_door_proposal = proposal
world.key_logic[player][builder.name] = key_layout.key_logic
world.key_layout[player][builder.name] = key_layout
return True
def log_key_logic(d_name, key_logic):
logger = logging.getLogger('')
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Key Logic for %s', d_name)
if len(key_logic.bk_restricted) > 0:
logger.debug('-BK Restrictions')
for restriction in key_logic.bk_restricted:
logger.debug(restriction)
if len(key_logic.sm_restricted) > 0:
logger.debug('-Small Restrictions')
for restriction in key_logic.sm_restricted:
logger.debug(restriction)
for key in key_logic.door_rules.keys():
rule = key_logic.door_rules[key]
logger.debug('--Rule for %s: Nrm:%s Allow:%s Loc:%s Alt:%s', key, rule.small_key_num, rule.allow_small, rule.small_location, rule.alternate_small_key)
if rule.alternate_small_key is not None:
for loc in rule.alternate_big_key_loc:
logger.debug('---BK Loc %s', loc.name)
logger.debug('Placement rules for %s', d_name)
for rule in key_logic.placement_rules:
logger.debug('*Rule for %s:', rule.door_reference)
if rule.bk_conditional_set:
logger.debug('**BK Checks %s', ','.join([x.name for x in rule.bk_conditional_set]))
logger.debug('**BK Blocked (%s) : %s', rule.needed_keys_wo_bk, ','.join([x.name for x in rule.check_locations_wo_bk]))
if rule.needed_keys_w_bk:
logger.debug('**BK Available (%s) : %s', rule.needed_keys_w_bk, ','.join([x.name for x in rule.check_locations_w_bk]))
def build_pair_list(flat_list):
paired_list = []
queue = deque(flat_list)
while len(queue) > 0:
d = queue.pop()
if d.dest in queue and d.type != DoorType.SpiralStairs:
paired_list.append((d, d.dest))
queue.remove(d.dest)
else:
paired_list.append(d)
return paired_list
def flatten_pair_list(paired_list):
flat_list = []
for d in paired_list:
if type(d) is tuple:
flat_list.append(d[0])
flat_list.append(d[1])
else:
flat_list.append(d)
return flat_list
okay_normals = [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable, DoorKind.DungeonChanger]
def find_key_door_candidates(region, checked, world, player):
dungeon = region.dungeon
candidates = []
checked_doors = list(checked)
queue = deque([(region, None, None)])
while len(queue) > 0:
current, last_door, last_region = queue.pop()
for ext in current.exits:
d = ext.door
if d and d.controller:
d = d.controller
if d is not None and not d.blocked and d.dest is not last_door and d.dest is not last_region and d not in checked_doors:
valid = False
if 0 <= d.doorListPos < 4 and d.type in [DoorType.Interior, DoorType.Normal, DoorType.SpiralStairs]:
room = world.get_room(d.roomIndex, player)
position, kind = room.doorList[d.doorListPos]
if d.type == DoorType.Interior:
valid = kind in [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable]
elif d.type == DoorType.SpiralStairs:
valid = kind in [DoorKind.StairKey, DoorKind.StairKey2, DoorKind.StairKeyLow]
elif d.type == DoorType.Normal:
d2 = d.dest
if d2 not in candidates:
if d2.type == DoorType.Normal:
room_b = world.get_room(d2.roomIndex, player)
pos_b, kind_b = room_b.doorList[d2.doorListPos]
valid = kind in okay_normals and kind_b in okay_normals
else:
valid = kind in okay_normals
if valid and 0 <= d2.doorListPos < 4:
candidates.append(d2)
else:
valid = True
if valid and d not in candidates:
candidates.append(d)
if ext.connected_region.type != RegionType.Dungeon or ext.connected_region.dungeon == dungeon:
queue.append((ext.connected_region, d, current))
if d is not None:
checked_doors.append(d)
return candidates, checked_doors
def kth_combination(k, l, r):
if r == 0:
return []
elif len(l) == r:
return l
else:
i = ncr(len(l)-1, r-1)
if k < i:
return l[0:1] + kth_combination(k, l[1:], r-1)
else:
return kth_combination(k-i, l[1:], r)
def ncr(n, r):
if r == 0:
return 1
r = min(r, n-r)
numerator = reduce(op.mul, range(n, n-r, -1), 1)
denominator = reduce(op.mul, range(1, r+1), 1)
return numerator / denominator
def reassign_key_doors(builder, world, player):
logger = logging.getLogger('')
logger.debug('Key doors for %s', builder.name)
proposal = builder.key_door_proposal
flat_proposal = flatten_pair_list(proposal)
queue = deque(find_current_key_doors(builder))
while len(queue) > 0:
d = queue.pop()
if d.type is DoorType.SpiralStairs and d not in proposal:
room = world.get_room(d.roomIndex, player)
if room.doorList[d.doorListPos][1] == DoorKind.StairKeyLow:
room.delete(d.doorListPos)
else:
if len(room.doorList) > 1:
room.mirror(d.doorListPos) # I think this works for crossed now
else:
room.delete(d.doorListPos)
d.smallKey = False
elif d.type is DoorType.Interior and d not in flat_proposal and d.dest not in flat_proposal:
world.get_room(d.roomIndex, player).change(d.doorListPos, DoorKind.Normal)
d.smallKey = False
d.dest.smallKey = False
queue.remove(d.dest)
elif d.type is DoorType.Normal and d not in flat_proposal:
world.get_room(d.roomIndex, player).change(d.doorListPos, DoorKind.Normal)
d.smallKey = False
for dp in world.paired_doors[player]:
if dp.door_a == d.name or dp.door_b == d.name:
dp.pair = False
for obj in proposal:
if type(obj) is tuple:
d1 = obj[0]
d2 = obj[1]
if d1.type is DoorType.Interior:
change_door_to_small_key(d1, world, player)
d2.smallKey = True # ensure flag is set
else:
names = [d1.name, d2.name]
found = False
for dp in world.paired_doors[player]:
if dp.door_a in names and dp.door_b in names:
dp.pair = True
found = True
elif dp.door_a in names:
dp.pair = False
elif dp.door_b in names:
dp.pair = False
if not found:
world.paired_doors[player].append(PairedDoor(d1.name, d2.name))
change_door_to_small_key(d1, world, player)
change_door_to_small_key(d2, world, player)
world.spoiler.set_door_type(d1.name+' <-> '+d2.name, 'Key Door', player)
logger.debug('Key Door: %s', d1.name+' <-> '+d2.name)
else:
d = obj
if d.type is DoorType.Interior:
change_door_to_small_key(d, world, player)
d.dest.smallKey = True # ensure flag is set
elif d.type is DoorType.SpiralStairs:
pass # we don't have spiral stairs candidates yet that aren't already key doors
elif d.type is DoorType.Normal:
change_door_to_small_key(d, world, player)
world.spoiler.set_door_type(d.name, 'Key Door', player)
logger.debug('Key Door: %s', d.name)
def change_door_to_small_key(d, world, player):
d.smallKey = True
room = world.get_room(d.roomIndex, player)
if room.doorList[d.doorListPos][1] != DoorKind.SmallKey:
room.change(d.doorListPos, DoorKind.SmallKey)
def smooth_door_pairs(world, player):
all_doors = [x for x in world.doors if x.player == player]
skip = set()
for door in all_doors:
if door.type in [DoorType.Normal, DoorType.Interior] and door not in skip:
partner = door.dest
skip.add(partner)
room_a = world.get_room(door.roomIndex, player)
type_a = room_a.kind(door)
if partner.type in [DoorType.Normal, DoorType.Interior]:
room_b = world.get_room(partner.roomIndex, player)
type_b = room_b.kind(partner)
valid_pair = stateful_door(door, type_a) and stateful_door(partner, type_b)
else:
valid_pair, room_b, type_b = False, None, None
if door.type == DoorType.Normal:
if type_a == DoorKind.SmallKey or type_b == DoorKind.SmallKey:
if valid_pair:
if type_a != DoorKind.SmallKey:
room_a.change(door.doorListPos, DoorKind.SmallKey)
if type_b != DoorKind.SmallKey:
room_b.change(partner.doorListPos, DoorKind.SmallKey)
add_pair(door, partner, world, player)
else:
if type_a == DoorKind.SmallKey:
remove_pair(door, world, player)
if type_b == DoorKind.SmallKey:
remove_pair(door, world, player)
elif type_a in [DoorKind.Bombable, DoorKind.Dashable] or type_b in [DoorKind.Bombable, DoorKind.Dashable]:
if valid_pair:
if type_a == type_b:
add_pair(door, partner, world, player)
spoiler_type = 'Bomb Door' if type_a == DoorKind.Bombable else 'Dash Door'
world.spoiler.set_door_type(door.name + ' <-> ' + partner.name, spoiler_type, player)
else:
new_type = DoorKind.Dashable if type_a == DoorKind.Dashable or type_b == DoorKind.Dashable else DoorKind.Bombable
if type_a != new_type:
room_a.change(door.doorListPos, new_type)
if type_b != new_type:
room_b.change(partner.doorListPos, new_type)
add_pair(door, partner, world, player)
spoiler_type = 'Bomb Door' if new_type == DoorKind.Bombable else 'Dash Door'
world.spoiler.set_door_type(door.name + ' <-> ' + partner.name, spoiler_type, player)
else:
if type_a in [DoorKind.Bombable, DoorKind.Dashable]:
room_a.change(door.doorListPos, DoorKind.Normal)
remove_pair(door, world, player)
elif type_b in [DoorKind.Bombable, DoorKind.Dashable]:
room_b.change(partner.doorListPos, DoorKind.Normal)
remove_pair(partner, world, player)
elif world.experimental[player] and valid_pair and type_a != DoorKind.SmallKey and type_b != DoorKind.SmallKey:
random_door_type(door, partner, world, player, type_a, type_b, room_a, room_b)
world.paired_doors[player] = [x for x in world.paired_doors[player] if x.pair or x.original]
def add_pair(door_a, door_b, world, player):
pair_a, pair_b = None, None
for paired_door in world.paired_doors[player]:
if paired_door.door_a == door_a.name and paired_door.door_b == door_b.name:
paired_door.pair = True
return
if paired_door.door_a == door_b.name and paired_door.door_b == door_a.name:
paired_door.pair = True
return
if paired_door.door_a == door_a.name or paired_door.door_b == door_a.name:
pair_a = paired_door
if paired_door.door_a == door_b.name or paired_door.door_b == door_b.name:
pair_b = paired_door
if pair_a:
pair_a.pair = False
if pair_b:
pair_b.pair = False
world.paired_doors[player].append(PairedDoor(door_a, door_b))
def remove_pair(door, world, player):
for paired_door in world.paired_doors[player]:
if paired_door.door_a == door.name or paired_door.door_b == door.name:
paired_door.pair = False
break
def stateful_door(door, kind):
if 0 <= door.doorListPos < 4:
return kind in [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable] #, DoorKind.BigKey]
return False
def random_door_type(door, partner, world, player, type_a, type_b, room_a, room_b):
r_kind = random.choices([DoorKind.Normal, DoorKind.Bombable, DoorKind.Dashable], [15, 4, 6], k=1)[0]
if r_kind != DoorKind.Normal:
if door.type == DoorType.Normal:
add_pair(door, partner, world, player)
if type_a != r_kind:
room_a.change(door.doorListPos, r_kind)
if type_b != r_kind:
room_b.change(partner.doorListPos, r_kind)
spoiler_type = 'Bomb Door' if r_kind == DoorKind.Bombable else 'Dash Door'
world.spoiler.set_door_type(door.name + ' <-> ' + partner.name, spoiler_type, player)
def overworld_prep(world, player):
find_inaccessible_regions(world, player)
add_inaccessible_doors(world, player)
def find_inaccessible_regions(world, player):
world.inaccessible_regions[player] = []
if world.mode[player] != 'inverted':
start_regions = ['Links House', 'Sanctuary']
else:
start_regions = ['Inverted Links House', 'Inverted Dark Sanctuary']
regs = convert_regions(start_regions, world, player)
all_regions = set([r for r in world.regions if r.player == player and r.type is not RegionType.Dungeon])
visited_regions = set()
queue = deque(regs)
while len(queue) > 0:
next_region = queue.popleft()
visited_regions.add(next_region)
if next_region.name == 'Inverted Dark Sanctuary': # special spawn point in cave
for ent in next_region.entrances:
parent = ent.parent_region
if parent and parent.type is not RegionType.Dungeon and parent not in queue and parent not in visited_regions:
queue.append(parent)
for ext in next_region.exits:
connect = ext.connected_region
if connect and connect.type is not RegionType.Dungeon and connect not in queue and connect not in visited_regions:
queue.append(connect)
world.inaccessible_regions[player].extend([r.name for r in all_regions.difference(visited_regions) if valid_inaccessible_region(r)])
logger = logging.getLogger('')
logger.debug('Inaccessible Regions:')
for r in world.inaccessible_regions[player]:
logger.debug('%s', r)
def find_accessible_entrances(world, player, builder):
# todo: lobby shuffle
if world.mode[player] == 'standard' and builder.name == 'Hyrule Castle':
return ['Hyrule Castle Lobby']
entrances = default_dungeon_entrances[builder.name]
if world.mode[player] != 'inverted':
start_regions = ['Links House', 'Sanctuary']
else:
start_regions = ['Inverted Links House', 'Inverted Dark Sanctuary']
regs = convert_regions(start_regions, world, player)
visited_regions = set()
visited_entrances = []
queue = deque(regs)
while len(queue) > 0:
next_region = queue.popleft()
visited_regions.add(next_region)
if world.mode[player] == 'inverted' and next_region.name == 'Tower Agahnim 1':
connect = world.get_region('Hyrule Castle Ledge', player)
if connect not in queue and connect not in visited_regions:
queue.append(connect)
for ext in next_region.exits:
connect = ext.connected_region
if connect is None or ext.door and ext.door.blocked:
continue
if connect.name in entrances:
visited_entrances.append(connect.name)
elif connect and connect not in queue and connect not in visited_regions:
queue.append(connect)
return visited_entrances
def valid_inaccessible_region(r):
return r.type is not RegionType.Cave or (len(r.exits) > 0 and r.name not in ['Links House', 'Chris Houlihan Room'])
def add_inaccessible_doors(world, player):
# todo: ignore standard mode hyrule castle ledge?
for inaccessible_region in world.inaccessible_regions[player]:
region = world.get_region(inaccessible_region, player)
for ext in region.exits:
create_door(world, player, ext.name, region.name)
def create_door(world, player, entName, region_name):
entrance = world.get_entrance(entName, player)
connect = entrance.connected_region
for ext in connect.exits:
if ext.connected_region is not None and ext.connected_region.name == region_name:
d = Door(player, ext.name, DoorType.Logical, ext),
world.doors += d
connect_door_only(world, ext.name, ext.connected_region, player)
d = Door(player, entName, DoorType.Logical, entrance),
world.doors += d
connect_door_only(world, entName, connect, player)
def check_required_paths(paths, world, player):
for dungeon_name in paths.keys():
if dungeon_name in world.dungeon_layouts[player].keys():
builder = world.dungeon_layouts[player][dungeon_name]
if len(paths[dungeon_name]) > 0:
states_to_explore = defaultdict(list)
for path in paths[dungeon_name]:
if type(path) is tuple:
states_to_explore[tuple([path[0]])].append(path[1])
else:
states_to_explore[tuple(builder.path_entrances)].append(path)
cached_initial_state = None
for start_regs, dest_regs in states_to_explore.items():
check_paths = convert_regions(dest_regs, world, player)
start_regions = convert_regions(start_regs, world, player)
initial = start_regs == tuple(builder.path_entrances)
if not initial or cached_initial_state is None:
init = determine_init_crystal(initial, cached_initial_state, start_regions)
state = ExplorationState(init, dungeon_name)
for region in start_regions:
state.visit_region(region)
state.add_all_doors_check_unattached(region, world, player)
explore_state(state, world, player)
if initial and cached_initial_state is None:
cached_initial_state = state
else:
state = cached_initial_state
valid, bad_region = check_if_regions_visited(state, check_paths)
if not valid:
if check_for_pinball_fix(state, bad_region, world, player):
explore_state(state, world, player)
valid, bad_region = check_if_regions_visited(state, check_paths)
if not valid:
raise Exception('%s cannot reach %s' % (dungeon_name, bad_region.name))
def determine_init_crystal(initial, state, start_regions):
if initial:
return CrystalBarrier.Orange
if state is None:
raise Exception('Please start path checking from the entrances')
if len(start_regions) > 1:
raise NotImplementedError('Path checking for multiple start regions (not the entrances) not implemented, use more paths instead')
start_region = start_regions[0]
if start_region in state.visited_blue and start_region in state.visited_orange:
return CrystalBarrier.Either
elif start_region in state.visited_blue:
return CrystalBarrier.Blue
elif start_region in state.visited_orange:
return CrystalBarrier.Orange
else:
raise Exception('Can\'t get to %s from initial state', start_region.name)
def explore_state(state, world, player):
while len(state.avail_doors) > 0:
door = state.next_avail_door().door
connect_region = world.get_entrance(door.name, player).connected_region
if state.can_traverse(door) and not state.visited(connect_region) and valid_region_to_explore(connect_region, world, player):
state.visit_region(connect_region)
state.add_all_doors_check_unattached(connect_region, world, player)
def check_if_regions_visited(state, check_paths):
valid = True
breaking_region = None
for region_target in check_paths:
if not state.visited_at_all(region_target):
valid = False
breaking_region = region_target
break
return valid, breaking_region
def check_for_pinball_fix(state, bad_region, world, player):
pinball_region = world.get_region('Skull Pinball', player)
if bad_region.name == 'Skull 2 West Lobby' and state.visited_at_all(pinball_region): # revisit this for entrance shuffle
door = world.get_door('Skull Pinball WS', player)
room = world.get_room(door.roomIndex, player)
if room.doorList[door.doorListPos][1] == DoorKind.Trap:
room.change(door.doorListPos, DoorKind.Normal)
door.trapFlag = 0x0
door.blocked = False
connect_two_way(world, door.name, door.dest.name, player)
state.add_all_doors_check_unattached(pinball_region, world, player)
return True
return False
@unique
class DROptions(Flag):
NoOptions = 0x00
Eternal_Mini_Bosses = 0x01 # If on, GT minibosses marked as defeated when they try to spawn a heart
Town_Portal = 0x02 # If on, Players will start with mirror scroll
Map_Info = 0x04
Debug = 0x08
Open_Desert_Wall = 0x80 # If on, pre opens the desert wall, no fire required
# DATA GOES DOWN HERE
logical_connections = [
('Hyrule Dungeon North Abyss Catwalk Dropdown', 'Hyrule Dungeon North Abyss'),
('Hyrule Castle Throne Room Tapestry', 'Hyrule Castle Behind Tapestry'),
('Hyrule Castle Tapestry Backwards', 'Hyrule Castle Throne Room'),
('Sewers Secret Room Push Block', 'Sewers Secret Room Blocked Path'),
('Eastern Hint Tile Push Block', 'Eastern Hint Tile'),
('Eastern Map Balcony Hook Path', 'Eastern Map Room'),
('Eastern Map Room Drop Down', 'Eastern Map Balcony'),
('Desert Main Lobby Left Path', 'Desert Left Alcove'),
('Desert Main Lobby Right Path', 'Desert Right Alcove'),
('Desert Left Alcove Path', 'Desert Main Lobby'),
('Desert Right Alcove Path', 'Desert Main Lobby'),
('Hera Big Chest Hook Path', 'Hera Big Chest Landing'),
('Hera Big Chest Landing Exit', 'Hera 4F'),
('PoD Pit Room Block Path N', 'PoD Pit Room Blocked'),
('PoD Pit Room Block Path S', 'PoD Pit Room'),
('PoD Arena Bonk Path', 'PoD Arena Bridge'),
('PoD Arena Main Crystal Path', 'PoD Arena Crystal'),
('PoD Arena Crystal Path', 'PoD Arena Main'),
('PoD Arena Main Orange Barrier', 'PoD Arena North'),
('PoD Arena North Drop Down', 'PoD Arena Main'),
('PoD Arena Bridge Drop Down', 'PoD Arena Main'),
('PoD Map Balcony Drop Down', 'PoD Sexy Statue'),
('PoD Basement Ledge Drop Down', 'PoD Stalfos Basement'),
('PoD Falling Bridge Path N', 'PoD Falling Bridge Ledge'),
('PoD Falling Bridge Path S', 'PoD Falling Bridge'),
('Swamp Lobby Moat', 'Swamp Entrance'),
('Swamp Entrance Moat', 'Swamp Lobby'),
('Swamp Trench 1 Approach Dry', 'Swamp Trench 1 Nexus'),
('Swamp Trench 1 Approach Key', 'Swamp Trench 1 Key Ledge'),
('Swamp Trench 1 Approach Swim Depart', 'Swamp Trench 1 Departure'),
('Swamp Trench 1 Nexus Approach', 'Swamp Trench 1 Approach'),
('Swamp Trench 1 Nexus Key', 'Swamp Trench 1 Key Ledge'),
('Swamp Trench 1 Key Ledge Dry', 'Swamp Trench 1 Nexus'),
('Swamp Trench 1 Key Approach', 'Swamp Trench 1 Approach'),
('Swamp Trench 1 Key Ledge Depart', 'Swamp Trench 1 Departure'),
('Swamp Trench 1 Departure Dry', 'Swamp Trench 1 Nexus'),
('Swamp Trench 1 Departure Approach', 'Swamp Trench 1 Approach'),
('Swamp Trench 1 Departure Key', 'Swamp Trench 1 Key Ledge'),
('Swamp Hub Hook Path', 'Swamp Hub North Ledge'),
('Swamp Hub North Ledge Drop Down', 'Swamp Hub'),
('Swamp Compass Donut Push Block', 'Swamp Donut Top'),
('Swamp Shortcut Blue Barrier', 'Swamp Trench 2 Pots'),
('Swamp Trench 2 Pots Blue Barrier', 'Swamp Shortcut'),
('Swamp Trench 2 Pots Dry', 'Swamp Trench 2 Blocks'),
('Swamp Trench 2 Pots Wet', 'Swamp Trench 2 Departure'),
('Swamp Trench 2 Blocks Pots', 'Swamp Trench 2 Pots'),
('Swamp Trench 2 Departure Wet', 'Swamp Trench 2 Pots'),
('Swamp West Shallows Push Blocks', 'Swamp West Block Path'),
('Swamp West Block Path Drop Down', 'Swamp West Shallows'),
('Swamp West Ledge Drop Down', 'Swamp West Shallows'),
('Swamp West Ledge Hook Path', 'Swamp Barrier Ledge'),
('Swamp Barrier Ledge Drop Down', 'Swamp West Shallows'),
('Swamp Barrier Ledge - Orange', 'Swamp Barrier'),
('Swamp Barrier - Orange', 'Swamp Barrier Ledge'),
('Swamp Barrier Ledge Hook Path', 'Swamp West Ledge'),
('Swamp Drain Right Switch', 'Swamp Drain Left'),
('Swamp Flooded Spot Ladder', 'Swamp Flooded Room'),
('Swamp Flooded Room Ladder', 'Swamp Flooded Spot'),
('Skull Pot Circle Star Path', 'Skull Map Room'),
('Skull Big Chest Hookpath', 'Skull 1 Lobby'),
('Skull Back Drop Star Path', 'Skull Small Hall'),
('Thieves Rail Ledge Drop Down', 'Thieves BK Corner'),
('Thieves Hellway Orange Barrier', 'Thieves Hellway S Crystal'),
('Thieves Hellway Crystal Orange Barrier', 'Thieves Hellway'),
('Thieves Hellway Blue Barrier', 'Thieves Hellway N Crystal'),
('Thieves Hellway Crystal Blue Barrier', 'Thieves Hellway'),
('Thieves Attic Orange Barrier', 'Thieves Attic Hint'),
('Thieves Attic Hint Orange Barrier', 'Thieves Attic'),
('Thieves Basement Block Path', 'Thieves Blocked Entry'),
('Thieves Blocked Entry Path', 'Thieves Basement Block'),
('Thieves Conveyor Bridge Block Path', 'Thieves Conveyor Block'),
('Thieves Conveyor Block Path', 'Thieves Conveyor Bridge'),
('Ice Cross Bottom Push Block Left', 'Ice Floor Switch'),
('Ice Cross Right Push Block Top', 'Ice Bomb Drop'),
('Ice Big Key Push Block', 'Ice Dead End'),
('Ice Bomb Jump Ledge Orange Barrier', 'Ice Bomb Jump Catwalk'),
('Ice Bomb Jump Catwalk Orange Barrier', 'Ice Bomb Jump Ledge'),
('Ice Hookshot Ledge Path', 'Ice Hookshot Balcony'),
('Ice Hookshot Balcony Path', 'Ice Hookshot Ledge'),
('Ice Crystal Right Orange Barrier', 'Ice Crystal Left'),
('Ice Crystal Left Orange Barrier', 'Ice Crystal Right'),
('Ice Crystal Left Blue Barrier', 'Ice Crystal Block'),
('Ice Crystal Block Exit', 'Ice Crystal Left'),
('Ice Big Chest Landing Push Blocks', 'Ice Big Chest View'),
('Mire Lobby Gap', 'Mire Post-Gap'),
('Mire Post-Gap Gap', 'Mire Lobby'),
('Mire Hub Upper Blue Barrier', 'Mire Hub Switch'),
('Mire Hub Lower Blue Barrier', 'Mire Hub Right'),
('Mire Hub Right Blue Barrier', 'Mire Hub'),
('Mire Hub Top Blue Barrier', 'Mire Hub Switch'),
('Mire Hub Switch Blue Barrier N', 'Mire Hub Top'),
('Mire Hub Switch Blue Barrier S', 'Mire Hub'),
('Mire Map Spike Side Drop Down', 'Mire Lone Shooter'),
('Mire Map Spike Side Blue Barrier', 'Mire Crystal Dead End'),
('Mire Map Spot Blue Barrier', 'Mire Crystal Dead End'),
('Mire Crystal Dead End Left Barrier', 'Mire Map Spot'),
('Mire Crystal Dead End Right Barrier', 'Mire Map Spike Side'),
('Mire Hidden Shooters Block Path S', 'Mire Hidden Shooters'),
('Mire Hidden Shooters Block Path N', 'Mire Hidden Shooters Blocked'),
('Mire Left Bridge Hook Path', 'Mire Right Bridge'),
('Mire Crystal Right Orange Barrier', 'Mire Crystal Mid'),
('Mire Crystal Mid Orange Barrier', 'Mire Crystal Right'),
('Mire Crystal Mid Blue Barrier', 'Mire Crystal Left'),
('Mire Crystal Left Blue Barrier', 'Mire Crystal Mid'),
('Mire Firesnake Skip Orange Barrier', 'Mire Antechamber'),
('Mire Antechamber Orange Barrier', 'Mire Firesnake Skip'),
('Mire Compass Blue Barrier', 'Mire Compass Chest'),
('Mire Compass Chest Exit', 'Mire Compass Room'),
('Mire South Fish Blue Barrier', 'Mire Fishbone'),
('Mire Fishbone Blue Barrier', 'Mire South Fish'),
('TR Main Lobby Gap', 'TR Lobby Ledge'),
('TR Lobby Ledge Gap', 'TR Main Lobby'),
('TR Pipe Ledge Drop Down', 'TR Pipe Pit'),
('TR Big Chest Gap', 'TR Big Chest Entrance'),
('TR Big Chest Entrance Gap', 'TR Big Chest'),
('TR Crystal Maze Forwards Path', 'TR Crystal Maze End'),
('TR Crystal Maze Blue Path', 'TR Crystal Maze'),
('TR Crystal Maze Cane Path', 'TR Crystal Maze'),
('GT Blocked Stairs Block Path', 'GT Big Chest'),
('GT Speed Torch South Path', 'GT Speed Torch'),
('GT Speed Torch North Path', 'GT Speed Torch Upper'),
('GT Hookshot East-North Path', 'GT Hookshot North Platform'),
('GT Hookshot East-South Path', 'GT Hookshot South Platform'),
('GT Hookshot North-East Path', 'GT Hookshot East Platform'),
('GT Hookshot North-South Path', 'GT Hookshot South Platform'),
('GT Hookshot South-East Path', 'GT Hookshot East Platform'),
('GT Hookshot South-North Path', 'GT Hookshot North Platform'),
('GT Hookshot Platform Blue Barrier', 'GT Hookshot South Entry'),
('GT Hookshot Entry Blue Barrier', 'GT Hookshot South Platform'),
('GT Double Switch Orange Barrier', 'GT Double Switch Switches'),
('GT Double Switch Orange Barrier 2', 'GT Double Switch Key Spot'),
('GT Double Switch Transition Blue', 'GT Double Switch Exit'),
('GT Double Switch Blue Path', 'GT Double Switch Transition'),
('GT Double Switch Orange Path', 'GT Double Switch Entry'),
('GT Double Switch Key Blue Path', 'GT Double Switch Exit'),
('GT Double Switch Key Orange Path', 'GT Double Switch Entry'),
('GT Double Switch Blue Barrier', 'GT Double Switch Key Spot'),
('GT Warp Maze - Pit Section Warp Spot', 'GT Warp Maze - Pit Exit Warp Spot'),
('GT Warp Maze Exit Section Warp Spot', 'GT Warp Maze - Pit Exit Warp Spot'),
('GT Firesnake Room Hook Path', 'GT Firesnake Room Ledge'),
('GT Left Moldorm Ledge Drop Down', 'GT Moldorm'),
('GT Right Moldorm Ledge Drop Down', 'GT Moldorm'),
('GT Moldorm Gap', 'GT Validation'),
('GT Validation Block Path', 'GT Validation Door')
]
vanilla_logical_connections = [
('Ice Cross Left Push Block', 'Ice Compass Room'),
('Ice Cross Right Push Block Bottom', 'Ice Compass Room'),
('Ice Cross Bottom Push Block Right', 'Ice Pengator Switch'),
('Ice Cross Top Push Block Right', 'Ice Pengator Switch'),
]
spiral_staircases = [
('Hyrule Castle Back Hall Down Stairs', 'Hyrule Dungeon Map Room Up Stairs'),
('Hyrule Dungeon Armory Down Stairs', 'Hyrule Dungeon Staircase Up Stairs'),
('Hyrule Dungeon Staircase Down Stairs', 'Hyrule Dungeon Cellblock Up Stairs'),
('Sewers Behind Tapestry Down Stairs', 'Sewers Rope Room Up Stairs'),
('Sewers Secret Room Up Stairs', 'Sewers Pull Switch Down Stairs'),
('Eastern Darkness Up Stairs', 'Eastern Attic Start Down Stairs'),
('Desert Tiles 1 Up Stairs', 'Desert Bridge Down Stairs'),
('Hera Lobby Down Stairs', 'Hera Basement Cage Up Stairs'),
('Hera Lobby Key Stairs', 'Hera Tile Room Up Stairs'),
('Hera Lobby Up Stairs', 'Hera Beetles Down Stairs'),
('Hera Startile Wide Up Stairs', 'Hera 4F Down Stairs'),
('Hera 4F Up Stairs', 'Hera 5F Down Stairs'),
('Hera 5F Up Stairs', 'Hera Boss Down Stairs'),
('Tower Room 03 Up Stairs', 'Tower Lone Statue Down Stairs'),
('Tower Dark Chargers Up Stairs', 'Tower Dual Statues Down Stairs'),
('Tower Dark Archers Up Stairs', 'Tower Red Spears Down Stairs'),
('Tower Pacifist Run Up Stairs', 'Tower Push Statue Down Stairs'),
('PoD Left Cage Down Stairs', 'PoD Shooter Room Up Stairs'),
('PoD Middle Cage Down Stairs', 'PoD Warp Room Up Stairs'),
('PoD Basement Ledge Up Stairs', 'PoD Big Key Landing Down Stairs'),
('PoD Compass Room W Down Stairs', 'PoD Dark Basement W Up Stairs'),
('PoD Compass Room E Down Stairs', 'PoD Dark Basement E Up Stairs'),
('Swamp Entrance Down Stairs', 'Swamp Pot Row Up Stairs'),
('Swamp West Block Path Up Stairs', 'Swamp Attic Down Stairs'),
('Swamp Push Statue Down Stairs', 'Swamp Flooded Room Up Stairs'),
('Swamp Left Elbow Down Stairs', 'Swamp Drain Left Up Stairs'),
('Swamp Right Elbow Down Stairs', 'Swamp Drain Right Up Stairs'),
('Swamp Behind Waterfall Up Stairs', 'Swamp C Down Stairs'),
('Thieves Spike Switch Up Stairs', 'Thieves Attic Down Stairs'),
('Thieves Conveyor Maze Down Stairs', 'Thieves Basement Block Up Stairs'),
('Ice Jelly Key Down Stairs', 'Ice Floor Switch Up Stairs'),
('Ice Narrow Corridor Down Stairs', 'Ice Pengator Trap Up Stairs'),
('Ice Spike Room Up Stairs', 'Ice Hammer Block Down Stairs'),
('Ice Spike Room Down Stairs', 'Ice Spikeball Up Stairs'),
('Ice Lonely Freezor Down Stairs', 'Iced T Up Stairs'),
('Ice Backwards Room Down Stairs', 'Ice Anti-Fairy Up Stairs'),
('Mire Post-Gap Down Stairs', 'Mire 2 Up Stairs'),
('Mire Left Bridge Down Stairs', 'Mire Dark Shooters Up Stairs'),
('Mire Conveyor Barrier Up Stairs', 'Mire Torches Top Down Stairs'),
('Mire Falling Foes Up Stairs', 'Mire Firesnake Skip Down Stairs'),
('TR Chain Chomps Down Stairs', 'TR Pipe Pit Up Stairs'),
('TR Crystaroller Down Stairs', 'TR Dark Ride Up Stairs'),
('GT Lobby Left Down Stairs', 'GT Torch Up Stairs'),
('GT Lobby Up Stairs', 'GT Crystal Paths Down Stairs'),
('GT Lobby Right Down Stairs', 'GT Hope Room Up Stairs'),
('GT Blocked Stairs Down Stairs', 'GT Four Torches Up Stairs'),
('GT Cannonball Bridge Up Stairs', 'GT Gauntlet 1 Down Stairs'),
('GT Quad Pot Up Stairs', 'GT Wizzrobes 1 Down Stairs'),
('GT Moldorm Pit Up Stairs', 'GT Right Moldorm Ledge Down Stairs'),
('GT Frozen Over Up Stairs', 'GT Brightly Lit Hall Down Stairs')
]
straight_staircases = [
('Hyrule Castle Lobby North Stairs', 'Hyrule Castle Throne Room South Stairs'),
('Sewers Rope Room North Stairs', 'Sewers Dark Cross South Stairs'),
('Tower Catwalk North Stairs', 'Tower Antechamber South Stairs'),
('PoD Conveyor North Stairs', 'PoD Map Balcony South Stairs'),
('TR Crystal Maze North Stairs', 'TR Final Abyss South Stairs')
]
open_edges = [
('Hyrule Dungeon North Abyss South Edge', 'Hyrule Dungeon South Abyss North Edge'),
('Hyrule Dungeon North Abyss Catwalk Edge', 'Hyrule Dungeon South Abyss Catwalk North Edge'),
('Hyrule Dungeon South Abyss West Edge', 'Hyrule Dungeon Guardroom Abyss Edge'),
('Hyrule Dungeon South Abyss Catwalk West Edge', 'Hyrule Dungeon Guardroom Catwalk Edge'),
('Desert Main Lobby NW Edge', 'Desert North Hall SW Edge'),
('Desert Main Lobby N Edge', 'Desert Dead End Edge'),
('Desert Main Lobby NE Edge', 'Desert North Hall SE Edge'),
('Desert Main Lobby E Edge', 'Desert East Wing W Edge'),
('Desert East Wing N Edge', 'Desert Arrow Pot Corner S Edge'),
('Desert Arrow Pot Corner W Edge', 'Desert North Hall E Edge'),
('Desert West Wing N Edge', 'Desert Sandworm Corner S Edge'),
('Desert Sandworm Corner E Edge', 'Desert North Hall W Edge'),
('Thieves Lobby N Edge', 'Thieves Ambush S Edge'),
('Thieves Lobby NE Edge', 'Thieves Ambush SE Edge'),
('Thieves Ambush ES Edge', 'Thieves BK Corner WS Edge'),
('Thieves Ambush EN Edge', 'Thieves BK Corner WN Edge'),
('Thieves BK Corner S Edge', 'Thieves Compass Room N Edge'),
('Thieves BK Corner SW Edge', 'Thieves Compass Room NW Edge'),
('Thieves Compass Room WS Edge', 'Thieves Big Chest Nook ES Edge'),
('Thieves Cricket Hall Left Edge', 'Thieves Cricket Hall Right Edge')
]
falldown_pits = [
('Eastern Courtyard Potholes', 'Eastern Fairies'),
('Hera Beetles Holes', 'Hera Lobby'),
('Hera Startile Corner Holes', 'Hera Lobby'),
('Hera Startile Wide Holes', 'Hera Lobby'),
('Hera 4F Holes', 'Hera Lobby'), # failed bomb jump
('Hera Big Chest Landing Holes', 'Hera Startile Wide'), # the other holes near big chest
('Hera 5F Star Hole', 'Hera Big Chest Landing'),
('Hera 5F Pothole Chain', 'Hera Fairies'),
('Hera 5F Normal Holes', 'Hera 4F'),
('Hera Boss Outer Hole', 'Hera 5F'),
('Hera Boss Inner Hole', 'Hera 4F'),
('PoD Pit Room Freefall', 'PoD Stalfos Basement'),
('PoD Pit Room Bomb Hole', 'PoD Basement Ledge'),
('PoD Big Key Landing Hole', 'PoD Stalfos Basement'),
('Swamp Attic Right Pit', 'Swamp Barrier Ledge'),
('Swamp Attic Left Pit', 'Swamp West Ledge'),
('Skull Final Drop Hole', 'Skull Boss'),
('Ice Bomb Drop Hole', 'Ice Stalfos Hint'),
('Ice Falling Square Hole', 'Ice Tall Hint'),
('Ice Freezors Hole', 'Ice Big Chest View'),
('Ice Freezors Ledge Hole', 'Ice Big Chest View'),
('Ice Freezors Bomb Hole', 'Ice Big Chest Landing'),
('Ice Crystal Block Hole', 'Ice Switch Room'),
('Ice Crystal Right Blue Hole', 'Ice Switch Room'),
('Ice Backwards Room Hole', 'Ice Fairy'),
('Ice Antechamber Hole', 'Ice Boss'),
('Mire Attic Hint Hole', 'Mire BK Chest Ledge'),
('Mire Torches Top Holes', 'Mire Conveyor Barrier'),
('Mire Torches Bottom Holes', 'Mire Warping Pool'),
('GT Bob\'s Room Hole', 'GT Ice Armos'),
('GT Falling Torches Hole', 'GT Staredown'),
('GT Moldorm Hole', 'GT Moldorm Pit')
]
dungeon_warps = [
('Eastern Fairies\' Warp', 'Eastern Courtyard'),
('Hera Fairies\' Warp', 'Hera 5F'),
('PoD Warp Hint Warp', 'PoD Warp Room'),
('PoD Warp Room Warp', 'PoD Warp Hint'),
('PoD Stalfos Basement Warp', 'PoD Warp Room'),
('PoD Callback Warp', 'PoD Dark Alley'),
('Ice Fairy Warp', 'Ice Anti-Fairy'),
('Mire Lone Warp Warp', 'Mire BK Door Room'),
('Mire Warping Pool Warp', 'Mire Square Rail'),
('GT Compass Room Warp', 'GT Conveyor Star Pits'),
('GT Spike Crystals Warp', 'GT Firesnake Room'),
('GT Warp Maze - Left Section Warp', 'GT Warp Maze - Rando Rail'),
('GT Warp Maze - Mid Section Left Warp', 'GT Warp Maze - Main Rails'),
('GT Warp Maze - Mid Section Right Warp', 'GT Warp Maze - Main Rails'),
('GT Warp Maze - Right Section Warp', 'GT Warp Maze - Main Rails'),
('GT Warp Maze - Pit Exit Warp', 'GT Warp Maze - Pot Rail'),
('GT Warp Maze - Rail Choice Left Warp', 'GT Warp Maze - Left Section'),
('GT Warp Maze - Rail Choice Right Warp', 'GT Warp Maze - Mid Section'),
('GT Warp Maze - Rando Rail Warp', 'GT Warp Maze - Mid Section'),
('GT Warp Maze - Main Rails Best Warp', 'GT Warp Maze - Pit Section'),
('GT Warp Maze - Main Rails Mid Left Warp', 'GT Warp Maze - Mid Section'),
('GT Warp Maze - Main Rails Mid Right Warp', 'GT Warp Maze - Mid Section'),
('GT Warp Maze - Main Rails Right Top Warp', 'GT Warp Maze - Right Section'),
('GT Warp Maze - Main Rails Right Mid Warp', 'GT Warp Maze - Right Section'),
('GT Warp Maze - Pot Rail Warp', 'GT Warp Maze Exit Section'),
('GT Hidden Star Warp', 'GT Invisible Bridges')
]
ladders = [
('PoD Bow Statue Down Ladder', 'PoD Dark Pegs Up Ladder'),
('Ice Big Key Down Ladder', 'Ice Tongue Pull Up Ladder'),
('Ice Firebar Down Ladder', 'Ice Freezors Up Ladder'),
('GT Staredown Up Ladder', 'GT Falling Torches Down Ladder')
]
interior_doors = [
('Hyrule Dungeon Armory Interior Key Door S', 'Hyrule Dungeon Armory Interior Key Door N'),
('Hyrule Dungeon Armory ES', 'Hyrule Dungeon Armory Boomerang WS'),
('Hyrule Dungeon Map Room Key Door S', 'Hyrule Dungeon North Abyss Key Door N'),
('Sewers Rat Path WS', 'Sewers Secret Room ES'),
('Sewers Rat Path WN', 'Sewers Secret Room EN'),
('Sewers Yet More Rats S', 'Sewers Pull Switch N'),
('Eastern Lobby N', 'Eastern Lobby Bridge S'),
('Eastern Lobby NW', 'Eastern Lobby Left Ledge SW'),
('Eastern Lobby NE', 'Eastern Lobby Right Ledge SE'),
('Eastern East Wing EN', 'Eastern Pot Switch WN'),
('Eastern East Wing ES', 'Eastern Map Balcony WS'),
('Eastern Pot Switch SE', 'Eastern Map Room NE'),
('Eastern West Wing WS', 'Eastern Stalfos Spawn ES'),
('Eastern Stalfos Spawn NW', 'Eastern Compass Room SW'),
('Eastern Compass Room EN', 'Eastern Hint Tile WN'),
('Eastern Dark Square EN', 'Eastern Dark Pots WN'),
('Eastern Darkness NE', 'Eastern Rupees SE'),
('Eastern False Switches WS', 'Eastern Cannonball Hell ES'),
('Eastern Single Eyegore NE', 'Eastern Duo Eyegores SE'),
('Desert East Lobby WS', 'Desert East Wing ES'),
('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'),
('Desert North Hall NW', 'Desert Map SW'),
('Desert North Hall NE', 'Desert Map SE'),
('Desert Arrow Pot Corner NW', 'Desert Trap Room SW'),
('Desert Sandworm Corner NE', 'Desert Bonk Torch SE'),
('Desert Sandworm Corner WS', 'Desert Circle of Pots ES'),
('Desert Circle of Pots NW', 'Desert Big Chest SW'),
('Desert West Wing WS', 'Desert West Lobby ES',),
('Desert Fairy Fountain SW', 'Desert West Lobby NW'),
('Desert Back Lobby NW', 'Desert Tiles 1 SW'),
('Desert Bridge SW', 'Desert Four Statues NW'),
('Desert Four Statues ES', 'Desert Beamos Hall WS',),
('Desert Tiles 2 NE', 'Desert Wall Slide SE'),
('Hera Tile Room EN', 'Hera Tridorm WN'),
('Hera Tridorm SE', 'Hera Torches NE'),
('Hera Beetles WS', 'Hera Startile Corner ES'),
('Hera Startile Corner NW', 'Hera Startile Wide SW'),
('Tower Lobby NW', 'Tower Gold Knights SW'),
('Tower Gold Knights EN', 'Tower Room 03 WN'),
('Tower Lone Statue WN', 'Tower Dark Maze EN'),
('Tower Dark Maze ES', 'Tower Dark Chargers WS'),
('Tower Dual Statues WS', 'Tower Dark Pits ES'),
('Tower Dark Pits EN', 'Tower Dark Archers WN'),
('Tower Red Spears WN', 'Tower Red Guards EN'),
('Tower Red Guards SW', 'Tower Circle of Pots NW'),
('Tower Circle of Pots ES', 'Tower Pacifist Run WS'),
('Tower Push Statue WS', 'Tower Catwalk ES'),
('Tower Antechamber NW', 'Tower Altar SW'),
('PoD Lobby N', 'PoD Middle Cage S'),
('PoD Lobby NW', 'PoD Left Cage SW'),
('PoD Lobby NE', 'PoD Middle Cage SE'),
('PoD Warp Hint SE', 'PoD Jelly Hall NE'),
('PoD Jelly Hall NW', 'PoD Mimics 1 SW'),
('PoD Falling Bridge EN', 'PoD Compass Room WN'),
('PoD Compass Room SE', 'PoD Harmless Hellway NE'),
('PoD Mimics 2 NW', 'PoD Bow Statue SW'),
('PoD Dark Pegs WN', 'PoD Lonely Turtle EN'),
('PoD Lonely Turtle SW', 'PoD Turtle Party NW'),
('PoD Turtle Party ES', 'PoD Callback WS'),
('Swamp Trench 1 Nexus N', 'Swamp Trench 1 Alcove S'),
('Swamp Trench 1 Key Ledge NW', 'Swamp Hammer Switch SW'),
('Swamp Donut Top SE', 'Swamp Donut Bottom NE'),
('Swamp Donut Bottom NW', 'Swamp Compass Donut SW'),
('Swamp Crystal Switch SE', 'Swamp Shortcut NE'),
('Swamp Trench 2 Blocks N', 'Swamp Trench 2 Alcove S'),
('Swamp Push Statue NW', 'Swamp Shooters SW'),
('Swamp Push Statue NE', 'Swamp Right Elbow SE'),
('Swamp Shooters EN', 'Swamp Left Elbow WN'),
('Swamp Drain WN', 'Swamp Basement Shallows EN'),
('Swamp Flooded Room WS', 'Swamp Basement Shallows ES'),
('Swamp Waterfall Room NW', 'Swamp Refill SW'),
('Swamp Waterfall Room NE', 'Swamp Behind Waterfall SE'),
('Swamp C SE', 'Swamp Waterway NE'),
('Swamp Waterway N', 'Swamp I S'),
('Swamp Waterway NW', 'Swamp T SW'),
('Skull 1 Lobby ES', 'Skull Map Room WS'),
('Skull Pot Circle WN', 'Skull Pull Switch EN'),
('Skull Pull Switch S', 'Skull Big Chest N'),
('Skull Left Drop ES', 'Skull Compass Room WS'),
('Skull 2 East Lobby NW', 'Skull Big Key SW'),
('Skull Big Key WN', 'Skull Lone Pot EN'),
('Skull Small Hall WS', 'Skull 2 West Lobby ES'),
('Skull 2 West Lobby NW', 'Skull X Room SW'),
('Skull 3 Lobby EN', 'Skull East Bridge WN'),
('Skull East Bridge WS', 'Skull West Bridge Nook ES'),
('Skull Star Pits ES', 'Skull Torch Room WS'),
('Skull Torch Room WN', 'Skull Vines EN'),
('Skull Spike Corner ES', 'Skull Final Drop WS'),
('Thieves Hallway WS', 'Thieves Pot Alcove Mid ES'),
('Thieves Conveyor Maze SW', 'Thieves Pot Alcove Top NW'),
('Thieves Conveyor Maze EN', 'Thieves Hallway WN'),
('Thieves Spike Track NE', 'Thieves Triple Bypass SE'),
('Thieves Spike Track WS', 'Thieves Hellway Crystal ES'),
('Thieves Hellway Crystal EN', 'Thieves Triple Bypass WN'),
('Thieves Attic ES', 'Thieves Cricket Hall Left WS'),
('Thieves Cricket Hall Right ES', 'Thieves Attic Window WS'),
('Thieves Blocked Entry SW', 'Thieves Lonely Zazak NW'),
('Thieves Lonely Zazak ES', 'Thieves Blind\'s Cell WS'),
('Thieves Conveyor Bridge WS', 'Thieves Big Chest Room ES'),
('Thieves Conveyor Block WN', 'Thieves Trap EN'),
('Ice Lobby WS', 'Ice Jelly Key ES'),
('Ice Floor Switch ES', 'Ice Cross Left WS'),
('Ice Cross Top NE', 'Ice Bomb Drop SE'),
('Ice Pengator Switch ES', 'Ice Dead End WS'),
('Ice Stalfos Hint SE', 'Ice Conveyor NE'),
('Ice Bomb Jump EN', 'Ice Narrow Corridor WN'),
('Ice Spike Cross WS', 'Ice Firebar ES'),
('Ice Spike Cross NE', 'Ice Falling Square SE'),
('Ice Hammer Block ES', 'Ice Tongue Pull WS'),
('Ice Freezors Ledge ES', 'Ice Tall Hint WS'),
('Ice Hookshot Balcony SW', 'Ice Spikeball NW'),
('Ice Crystal Right NE', 'Ice Backwards Room SE'),
('Ice Crystal Left WS', 'Ice Big Chest View ES'),
('Ice Anti-Fairy SE', 'Ice Switch Room NE'),
('Mire Lone Shooter ES', 'Mire Falling Bridge WS'), # technically one-way
('Mire Falling Bridge W', 'Mire Failure Bridge E'), # technically one-way
('Mire Falling Bridge WN', 'Mire Map Spike Side EN'), # technically one-way
('Mire Hidden Shooters WS', 'Mire Cross ES'), # technically one-way
('Mire Hidden Shooters NE', 'Mire Minibridge SE'),
('Mire Spikes NW', 'Mire Ledgehop SW'),
('Mire Spike Barrier ES', 'Mire Square Rail WS'),
('Mire Square Rail NW', 'Mire Lone Warp SW'),
('Mire Wizzrobe Bypass WN', 'Mire Compass Room EN'), # technically one-way
('Mire Conveyor Crystal WS', 'Mire Tile Room ES'),
('Mire Tile Room NW', 'Mire Compass Room SW'),
('Mire Neglected Room SE', 'Mire Chest View NE'),
('Mire BK Chest Ledge WS', 'Mire Warping Pool ES'), # technically one-way
('Mire Torches Top SW', 'Mire Torches Bottom NW'),
('Mire Torches Bottom WS', 'Mire Attic Hint ES'),
('Mire Dark Shooters SE', 'Mire Key Rupees NE'),
('Mire Dark Shooters SW', 'Mire Block X NW'),
('Mire Tall Dark and Roomy WS', 'Mire Crystal Right ES'),
('Mire Tall Dark and Roomy WN', 'Mire Shooter Rupees EN'),
('Mire Crystal Mid NW', 'Mire Crystal Top SW'),
('TR Tile Room NE', 'TR Refill SE'),
('TR Pokey 1 NW', 'TR Chain Chomps SW'),
('TR Twin Pokeys EN', 'TR Dodgers WN'),
('TR Twin Pokeys SW', 'TR Hallway NW'),
('TR Hallway ES', 'TR Big View WS'),
('TR Big Chest NE', 'TR Dodgers SE'),
('TR Dash Room ES', 'TR Tongue Pull WS'),
('TR Dash Room NW', 'TR Crystaroller SW'),
('TR Tongue Pull NE', 'TR Rupees SE'),
('GT Torch EN', 'GT Hope Room WN'),
('GT Torch SW', 'GT Big Chest NW'),
('GT Tile Room EN', 'GT Speed Torch WN'),
('GT Speed Torch WS', 'GT Pots n Blocks ES'),
('GT Crystal Conveyor WN', 'GT Compass Room EN'),
('GT Conveyor Cross WN', 'GT Hookshot EN'),
('GT Hookshot ES', 'GT Map Room WS'),
('GT Double Switch EN', 'GT Spike Crystals WN'),
('GT Firesnake Room SW', 'GT Warp Maze (Rails) NW'),
('GT Ice Armos NE', 'GT Big Key Room SE'),
('GT Ice Armos WS', 'GT Four Torches ES'),
('GT Four Torches NW', 'GT Fairy Abyss SW'),
('GT Crystal Paths SW', 'GT Mimics 1 NW'),
('GT Mimics 1 ES', 'GT Mimics 2 WS'),
('GT Mimics 2 NE', 'GT Dash Hall SE'),
('GT Cannonball Bridge SE', 'GT Refill NE'),
('GT Gauntlet 1 WN', 'GT Gauntlet 2 EN'),
('GT Gauntlet 2 SW', 'GT Gauntlet 3 NW'),
('GT Gauntlet 4 SW', 'GT Gauntlet 5 NW'),
('GT Beam Dash WS', 'GT Lanmolas 2 ES'),
('GT Lanmolas 2 NW', 'GT Quad Pot SW'),
('GT Wizzrobes 1 SW', 'GT Dashing Bridge NW'),
('GT Dashing Bridge NE', 'GT Wizzrobes 2 SE'),
('GT Torch Cross ES', 'GT Staredown WS'),
('GT Falling Torches NE', 'GT Mini Helmasaur Room SE'),
('GT Mini Helmasaur Room WN', 'GT Bomb Conveyor EN'),
('GT Bomb Conveyor SW', 'GT Crystal Circles NW')
]
key_doors = [
('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'),
('Sewers Dark Cross Key Door N', 'Sewers Water S'),
('Eastern Dark Square Key Door WN', 'Eastern Cannonball Ledge Key Door EN'),
('Eastern Darkness Up Stairs', 'Eastern Attic Start Down Stairs'),
('Eastern Big Key NE', 'Eastern Hint Tile Blocked Path SE'),
('Eastern Darkness S', 'Eastern Courtyard N'),
('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'),
('Desert Tiles 1 Up Stairs', 'Desert Bridge Down Stairs'),
('Desert Beamos Hall NE', 'Desert Tiles 2 SE'),
('Desert Tiles 2 NE', 'Desert Wall Slide SE'),
('Desert Wall Slide NW', 'Desert Boss SW'),
('Hera Lobby Key Stairs', 'Hera Tile Room Up Stairs'),
('Hera Startile Corner NW', 'Hera Startile Wide SW'),
('PoD Middle Cage N', 'PoD Pit Room S'),
('PoD Arena Main NW', 'PoD Falling Bridge SW'),
('PoD Falling Bridge WN', 'PoD Dark Maze EN'),
]
default_small_key_doors = {
'Hyrule Castle': [
('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'),
('Sewers Dark Cross Key Door N', 'Sewers Water S'),
('Hyrule Dungeon Map Room Key Door S', 'Hyrule Dungeon North Abyss Key Door N'),
('Hyrule Dungeon Armory Interior Key Door N', 'Hyrule Dungeon Armory Interior Key Door S')
],
'Eastern Palace': [
('Eastern Dark Square Key Door WN', 'Eastern Cannonball Ledge Key Door EN'),
'Eastern Darkness Up Stairs',
],
'Desert Palace': [
('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'),
'Desert Tiles 1 Up Stairs',
('Desert Beamos Hall NE', 'Desert Tiles 2 SE'),
('Desert Tiles 2 NE', 'Desert Wall Slide SE'),
],
'Tower of Hera': [
'Hera Lobby Key Stairs'
],
'Agahnims Tower': [
'Tower Room 03 Up Stairs',
('Tower Dark Maze ES', 'Tower Dark Chargers WS'),
'Tower Dark Archers Up Stairs',
('Tower Circle of Pots ES', 'Tower Pacifist Run WS'),
],
'Palace of Darkness': [
('PoD Middle Cage N', 'PoD Pit Room S'),
('PoD Arena Main NW', 'PoD Falling Bridge SW'),
('PoD Falling Bridge WN', 'PoD Dark Maze EN'),
'PoD Basement Ledge Up Stairs',
('PoD Compass Room SE', 'PoD Harmless Hellway NE'),
('PoD Dark Pegs WN', 'PoD Lonely Turtle EN')
],
'Swamp Palace': [
'Swamp Entrance Down Stairs',
('Swamp Pot Row WS', 'Swamp Trench 1 Approach ES'),
('Swamp Trench 1 Key Ledge NW', 'Swamp Hammer Switch SW'),
('Swamp Hub WN', 'Swamp Crystal Switch EN'),
('Swamp Hub North Ledge N', 'Swamp Push Statue S'),
('Swamp Waterway NW', 'Swamp T SW')
],
'Skull Woods': [
('Skull 1 Lobby WS', 'Skull Pot Prison ES'),
('Skull Map Room SE', 'Skull Pinball NE'),
('Skull 2 West Lobby NW', 'Skull X Room SW'),
('Skull 3 Lobby NW', 'Skull Star Pits SW'),
('Skull Spike Corner ES', 'Skull Final Drop WS')
],
'Thieves Town': [
('Thieves Hallway WS', 'Thieves Pot Alcove Mid ES'),
'Thieves Spike Switch Up Stairs',
('Thieves Conveyor Bridge WS', 'Thieves Big Chest Room ES')
],
'Ice Palace': [
'Ice Jelly Key Down Stairs',
('Ice Conveyor SW', 'Ice Bomb Jump NW'),
('Ice Spike Cross ES', 'Ice Spike Room WS'),
('Ice Tall Hint SE', 'Ice Lonely Freezor NE'),
'Ice Backwards Room Down Stairs',
('Ice Switch Room ES', 'Ice Refill WS')
],
'Misery Mire': [
('Mire Hub WS', 'Mire Conveyor Crystal ES'),
('Mire Hub Right EN', 'Mire Map Spot WN'),
('Mire Spikes NW', 'Mire Ledgehop SW'),
('Mire Fishbone SE', 'Mire Spike Barrier NE'),
('Mire Conveyor Crystal WS', 'Mire Tile Room ES'),
('Mire Dark Shooters SE', 'Mire Key Rupees NE')
],
'Turtle Rock': [
('TR Hub NW', 'TR Pokey 1 SW'),
('TR Pokey 1 NW', 'TR Chain Chomps SW'),
'TR Chain Chomps Down Stairs',
('TR Pokey 2 ES', 'TR Lava Island WS'),
'TR Crystaroller Down Stairs',
('TR Dash Bridge WS', 'TR Crystal Maze ES')
],
'Ganons Tower': [
('GT Torch EN', 'GT Hope Room WN'),
('GT Tile Room EN', 'GT Speed Torch WN'),
('GT Hookshot ES', 'GT Map Room WS'),
('GT Double Switch EN', 'GT Spike Crystals WN'),
('GT Firesnake Room SW', 'GT Warp Maze (Rails) NW'),
('GT Conveyor Star Pits EN', 'GT Falling Bridge WN'),
('GT Mini Helmasaur Room WN', 'GT Bomb Conveyor EN'),
('GT Crystal Circles SW', 'GT Left Moldorm Ledge NW')
]
}
default_door_connections = [
('Hyrule Castle Lobby W', 'Hyrule Castle West Lobby E'),
('Hyrule Castle Lobby E', 'Hyrule Castle East Lobby W'),
('Hyrule Castle Lobby WN', 'Hyrule Castle West Lobby EN'),
('Hyrule Castle West Lobby N', 'Hyrule Castle West Hall S'),
('Hyrule Castle East Lobby N', 'Hyrule Castle East Hall S'),
('Hyrule Castle East Lobby NW', 'Hyrule Castle East Hall SW'),
('Hyrule Castle East Hall W', 'Hyrule Castle Back Hall E'),
('Hyrule Castle West Hall E', 'Hyrule Castle Back Hall W'),
('Hyrule Castle Throne Room N', 'Sewers Behind Tapestry S'),
('Hyrule Dungeon Guardroom N', 'Hyrule Dungeon Armory S'),
('Sewers Dark Cross Key Door N', 'Sewers Water S'),
('Sewers Water W', 'Sewers Key Rat E'),
('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'),
('Eastern Lobby Bridge N', 'Eastern Cannonball S'),
('Eastern Cannonball N', 'Eastern Courtyard Ledge S'),
('Eastern Cannonball Ledge WN', 'Eastern Big Key EN'),
('Eastern Cannonball Ledge Key Door EN', 'Eastern Dark Square Key Door WN'),
('Eastern Courtyard Ledge W', 'Eastern West Wing E'),
('Eastern Courtyard Ledge E', 'Eastern East Wing W'),
('Eastern Hint Tile EN', 'Eastern Courtyard WN'),
('Eastern Big Key NE', 'Eastern Hint Tile Blocked Path SE'),
('Eastern Courtyard EN', 'Eastern Map Valley WN'),
('Eastern Courtyard N', 'Eastern Darkness S'),
('Eastern Map Valley SW', 'Eastern Dark Square NW'),
('Eastern Attic Start WS', 'Eastern False Switches ES'),
('Eastern Cannonball Hell WS', 'Eastern Single Eyegore ES'),
('Desert Compass NW', 'Desert Cannonball S'),
('Desert Beamos Hall NE', 'Desert Tiles 2 SE'),
('PoD Middle Cage N', 'PoD Pit Room S'),
('PoD Pit Room NW', 'PoD Arena Main SW'),
('PoD Pit Room NE', 'PoD Arena Bridge SE'),
('PoD Arena Main NW', 'PoD Falling Bridge SW'),
('PoD Arena Crystals E', 'PoD Sexy Statue W'),
('PoD Mimics 1 NW', 'PoD Conveyor SW'),
('PoD Map Balcony WS', 'PoD Arena Ledge ES'),
('PoD Falling Bridge WN', 'PoD Dark Maze EN'),
('PoD Dark Maze E', 'PoD Big Chest Balcony W'),
('PoD Sexy Statue NW', 'PoD Mimics 2 SW'),
('Swamp Pot Row WN', 'Swamp Map Ledge EN'),
('Swamp Pot Row WS', 'Swamp Trench 1 Approach ES'),
('Swamp Trench 1 Departure WS', 'Swamp Hub ES'),
('Swamp Hammer Switch WN', 'Swamp Hub Dead Ledge EN'),
('Swamp Hub S', 'Swamp Donut Top N'),
('Swamp Hub WS', 'Swamp Trench 2 Pots ES'),
('Swamp Hub WN', 'Swamp Crystal Switch EN'),
('Swamp Hub North Ledge N', 'Swamp Push Statue S'),
('Swamp Trench 2 Departure WS', 'Swamp West Shallows ES'),
('Swamp Big Key Ledge WN', 'Swamp Barrier EN'),
('Swamp Basement Shallows NW', 'Swamp Waterfall Room SW'),
('Skull 1 Lobby WS', 'Skull Pot Prison ES'),
('Skull Map Room SE', 'Skull Pinball NE'),
('Skull Pinball WS', 'Skull Compass Room ES'),
('Skull Compass Room NE', 'Skull Pot Prison SE'),
('Skull 2 East Lobby WS', 'Skull Small Hall ES'),
('Skull 3 Lobby NW', 'Skull Star Pits SW'),
('Skull Vines NW', 'Skull Spike Corner SW'),
('Thieves Lobby E', 'Thieves Compass Room W'),
('Thieves Ambush E', 'Thieves Rail Ledge W'),
('Thieves Rail Ledge NW', 'Thieves Pot Alcove Bottom SW'),
('Thieves BK Corner NE', 'Thieves Hallway SE'),
('Thieves Pot Alcove Mid WS', 'Thieves Spike Track ES'),
('Thieves Hellway NW', 'Thieves Spike Switch SW'),
('Thieves Triple Bypass EN', 'Thieves Conveyor Maze WN'),
('Thieves Basement Block WN', 'Thieves Conveyor Bridge EN'),
('Thieves Lonely Zazak WS', 'Thieves Conveyor Bridge ES'),
('Ice Cross Bottom SE', 'Ice Compass Room NE'),
('Ice Cross Right ES', 'Ice Pengator Switch WS'),
('Ice Conveyor SW', 'Ice Bomb Jump NW'),
('Ice Pengator Trap NE', 'Ice Spike Cross SE'),
('Ice Spike Cross ES', 'Ice Spike Room WS'),
('Ice Tall Hint SE', 'Ice Lonely Freezor NE'),
('Ice Tall Hint EN', 'Ice Hookshot Ledge WN'),
('Iced T EN', 'Ice Catwalk WN'),
('Ice Catwalk NW', 'Ice Many Pots SW'),
('Ice Many Pots WS', 'Ice Crystal Right ES'),
('Ice Switch Room ES', 'Ice Refill WS'),
('Ice Switch Room SE', 'Ice Antechamber NE'),
('Mire 2 NE', 'Mire Hub SE'),
('Mire Hub ES', 'Mire Lone Shooter WS'),
('Mire Hub E', 'Mire Failure Bridge W'),
('Mire Hub NE', 'Mire Hidden Shooters SE'),
('Mire Hub WN', 'Mire Wizzrobe Bypass EN'),
('Mire Hub WS', 'Mire Conveyor Crystal ES'),
('Mire Hub Right EN', 'Mire Map Spot WN'),
('Mire Hub Top NW', 'Mire Cross SW'),
('Mire Hidden Shooters ES', 'Mire Spikes WS'),
('Mire Minibridge NE', 'Mire Right Bridge SE'),
('Mire BK Door Room EN', 'Mire Ledgehop WN'),
('Mire BK Door Room N', 'Mire Left Bridge S'),
('Mire Spikes SW', 'Mire Crystal Dead End NW'),
('Mire Ledgehop NW', 'Mire Bent Bridge SW'),
('Mire Bent Bridge W', 'Mire Over Bridge E'),
('Mire Over Bridge W', 'Mire Fishbone E'),
('Mire Fishbone SE', 'Mire Spike Barrier NE'),
('Mire Spike Barrier SE', 'Mire Wizzrobe Bypass NE'),
('Mire Conveyor Crystal SE', 'Mire Neglected Room NE'),
('Mire Tile Room SW', 'Mire Conveyor Barrier NW'),
('Mire Block X WS', 'Mire Tall Dark and Roomy ES'),
('Mire Crystal Left WS', 'Mire Falling Foes ES'),
('TR Lobby Ledge NE', 'TR Hub SE'),
('TR Compass Room NW', 'TR Hub SW'),
('TR Hub ES', 'TR Torches Ledge WS'),
('TR Hub EN', 'TR Torches WN'),
('TR Hub NW', 'TR Pokey 1 SW'),
('TR Hub NE', 'TR Tile Room SE'),
('TR Torches NW', 'TR Roller Room SW'),
('TR Pipe Pit WN', 'TR Lava Dual Pipes EN'),
('TR Lava Island ES', 'TR Pipe Ledge WS'),
('TR Lava Dual Pipes WN', 'TR Pokey 2 EN'),
('TR Lava Dual Pipes SW', 'TR Twin Pokeys NW'),
('TR Pokey 2 ES', 'TR Lava Island WS'),
('TR Dodgers NE', 'TR Lava Escape SE'),
('TR Lava Escape NW', 'TR Dash Room SW'),
('TR Hallway WS', 'TR Lazy Eyes ES'),
('TR Dark Ride SW', 'TR Dash Bridge NW'),
('TR Dash Bridge SW', 'TR Eye Bridge NW'),
('TR Dash Bridge WS', 'TR Crystal Maze ES'),
('GT Torch WN', 'GT Conveyor Cross EN'),
('GT Hope Room EN', 'GT Tile Room WN'),
('GT Big Chest SW', 'GT Invisible Catwalk NW'),
('GT Bob\'s Room SE', 'GT Invisible Catwalk NE'),
('GT Speed Torch NE', 'GT Petting Zoo SE'),
('GT Speed Torch SE', 'GT Crystal Conveyor NE'),
('GT Warp Maze (Pits) ES', 'GT Invisible Catwalk WS'),
('GT Hookshot NW', 'GT DMs Room SW'),
('GT Hookshot SW', 'GT Double Switch NW'),
('GT Warp Maze (Rails) WS', 'GT Randomizer Room ES'),
('GT Conveyor Star Pits EN', 'GT Falling Bridge WN'),
('GT Falling Bridge WS', 'GT Hidden Star ES'),
('GT Dash Hall NE', 'GT Hidden Spikes SE'),
('GT Hidden Spikes EN', 'GT Cannonball Bridge WN'),
('GT Gauntlet 3 SW', 'GT Gauntlet 4 NW'),
('GT Gauntlet 5 WS', 'GT Beam Dash ES'),
('GT Wizzrobes 2 NE', 'GT Conveyor Bridge SE'),
('GT Conveyor Bridge EN', 'GT Torch Cross WN'),
('GT Crystal Circles SW', 'GT Left Moldorm Ledge NW')
]
default_one_way_connections = [
('Sewers Pull Switch S', 'Sanctuary N'),
('Eastern Duo Eyegores NE', 'Eastern Boss SE'),
('Desert Wall Slide NW', 'Desert Boss SW'),
('Tower Altar NW', 'Tower Agahnim 1 SW'),
('PoD Harmless Hellway SE', 'PoD Arena Main NE'),
('PoD Dark Alley NE', 'PoD Boss SE'),
('Swamp T NW', 'Swamp Boss SW'),
('Thieves Hallway NE', 'Thieves Boss SE'),
('Mire Antechamber NW', 'Mire Boss SW'),
('TR Final Abyss NW', 'TR Boss SW'),
('GT Invisible Bridges WS', 'GT Invisible Catwalk ES'),
('GT Validation WS', 'GT Frozen Over ES'),
('GT Brightly Lit Hall NW', 'GT Agahnim 2 SW')
]
# For crossed
# offset from 0x122e17, sram storage, write offset from compass_w_addr, 0 = jmp or # of nops, dungeon_id
compass_data = {
'Hyrule Castle': (0x1, 0xc0, 0x16, 0, 0x02),
'Eastern Palace': (0x1C, 0xc1, 0x28, 0, 0x04),
'Desert Palace': (0x35, 0xc2, 0x4a, 0, 0x06),
'Agahnims Tower': (0x51, 0xc3, 0x5c, 0, 0x08),
'Swamp Palace': (0x6A, 0xc4, 0x7e, 0, 0x0a),
'Palace of Darkness': (0x83, 0xc5, 0xa4, 0, 0x0c),
'Misery Mire': (0x9C, 0xc6, 0xca, 0, 0x0e),
'Skull Woods': (0xB5, 0xc7, 0xf0, 0, 0x10),
'Ice Palace': (0xD0, 0xc8, 0x102, 0, 0x12),
'Tower of Hera': (0xEB, 0xc9, 0x114, 0, 0x14),
'Thieves Town': (0x106, 0xca, 0x138, 0, 0x16),
'Turtle Rock': (0x11F, 0xcb, 0x15e, 0, 0x18),
'Ganons Tower': (0x13A, 0xcc, 0x170, 2, 0x1a)
}
# For compass boss indicator
boss_indicator = {
'Eastern Palace': (0x04, 'Eastern Boss SE'),
'Desert Palace': (0x06, 'Desert Boss SW'),
'Agahnims Tower': (0x08, 'Tower Agahnim 1 SW'),
'Swamp Palace': (0x0a, 'Swamp Boss SW'),
'Palace of Darkness': (0x0c, 'PoD Boss SE'),
'Misery Mire': (0x0e, 'Mire Boss SW'),
'Skull Woods': (0x10, 'Skull Spike Corner SW'),
'Ice Palace': (0x12, 'Ice Antechamber NE'),
'Tower of Hera': (0x14, 'Hera Boss Down Stairs'),
'Thieves Town': (0x16, 'Thieves Boss SE'),
'Turtle Rock': (0x18, 'TR Boss SW'),
'Ganons Tower': (0x1a, 'GT Agahnim 2 SW')
}
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,118
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/Utils.py
|
#!/usr/bin/env python3
import os
import re
import subprocess
import sys
import xml.etree.ElementTree as ET
def int16_as_bytes(value):
value = value & 0xFFFF
return [value & 0xFF, (value >> 8) & 0xFF]
def int32_as_bytes(value):
value = value & 0xFFFFFFFF
return [value & 0xFF, (value >> 8) & 0xFF, (value >> 16) & 0xFF, (value >> 24) & 0xFF]
def pc_to_snes(value):
return ((value<<1) & 0x7F0000)|(value & 0x7FFF)|0x8000
def snes_to_pc(value):
return ((value & 0x7F0000)>>1)|(value & 0x7FFF)
def parse_player_names(names, players, teams):
names = [n for n in re.split(r'[, ]', names) if n]
ret = []
while names or len(ret) < teams:
team = [n[:16] for n in names[:players]]
while len(team) != players:
team.append(f"Player {len(team) + 1}")
ret.append(team)
names = names[players:]
return ret
def is_bundled():
return getattr(sys, 'frozen', False)
def local_path(path):
if local_path.cached_path is not None:
return os.path.join(local_path.cached_path, path)
if is_bundled():
# we are running in a bundle
local_path.cached_path = sys._MEIPASS # pylint: disable=protected-access,no-member
else:
# we are running in a normal Python environment
local_path.cached_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(local_path.cached_path, path)
local_path.cached_path = None
def output_path(path):
if output_path.cached_path is not None:
return os.path.join(output_path.cached_path, path)
if not is_bundled():
output_path.cached_path = '.'
return os.path.join(output_path.cached_path, path)
else:
# has been packaged, so cannot use CWD for output.
if sys.platform == 'win32':
#windows
import ctypes.wintypes
CSIDL_PERSONAL = 5 # My Documents
SHGFP_TYPE_CURRENT = 0 # Get current, not default value
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf)
documents = buf.value
elif sys.platform == 'darwin':
from AppKit import NSSearchPathForDirectoriesInDomains # pylint: disable=import-error
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
NSDocumentDirectory = 9
NSUserDomainMask = 1
# True for expanding the tilde into a fully qualified path
documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0]
elif sys.platform.find("linux") or sys.platform.find("ubuntu") or sys.platform.find("unix"):
documents = os.path.join(os.path.expanduser("~"),"Documents")
else:
raise NotImplementedError('Not supported yet')
output_path.cached_path = os.path.join(documents, 'ALttPDoorRandomizer')
if not os.path.exists(output_path.cached_path):
os.makedirs(output_path.cached_path)
if not os.path.join(output_path.cached_path, path):
os.makedirs(os.path.join(output_path.cached_path, path))
return os.path.join(output_path.cached_path, path)
output_path.cached_path = None
def open_file(filename):
if sys.platform == 'win32':
os.startfile(filename)
else:
open_command = 'open' if sys.platform == 'darwin' else 'xdg-open'
subprocess.call([open_command, filename])
def close_console():
if sys.platform == 'win32':
#windows
import ctypes.wintypes
try:
ctypes.windll.kernel32.FreeConsole()
except Exception:
pass
def make_new_base2current(old_rom='Zelda no Densetsu - Kamigami no Triforce (Japan).sfc', new_rom='working.sfc'):
from collections import OrderedDict
import json
import hashlib
with open(old_rom, 'rb') as stream:
old_rom_data = bytearray(stream.read())
with open(new_rom, 'rb') as stream:
new_rom_data = bytearray(stream.read())
# extend to 2 mb
old_rom_data.extend(bytearray([0x00] * (2097152 - len(old_rom_data))))
out_data = OrderedDict()
for idx, old in enumerate(old_rom_data):
new = new_rom_data[idx]
if old != new:
out_data[idx] = [int(new)]
for offset in reversed(list(out_data.keys())):
if offset - 1 in out_data:
out_data[offset-1].extend(out_data.pop(offset))
with open('data/base2current.json', 'wt') as outfile:
json.dump([{key:value} for key, value in out_data.items()], outfile, separators=(",", ":"))
basemd5 = hashlib.md5()
basemd5.update(new_rom_data)
return "New Rom Hash: " + basemd5.hexdigest()
entrance_offsets = {
'Sanctuary': 0x2,
'HC West': 0x3,
'HC South': 0x4,
'HC East': 0x5,
'Eastern': 0x8,
'Desert West': 0x9,
'Desert South': 0xa,
'Desert East': 0xb,
'Desert Back': 0xc,
'TR Lazy Eyes': 0x15,
'TR Eye Bridge': 0x18,
'TR Chest': 0x19,
'Aga Tower': 0x24,
'Swamp': 0x25,
'Palace of Darkness': 0x26,
'Mire': 0x27,
'Skull 2 West': 0x28,
'Skull 2 East': 0x29,
'Skull 1': 0x2a,
'Skull 3': 0x2b,
'Ice': 0x2d,
'Hera': 0x33,
'Thieves': 0x34,
'TR Main': 0x35,
'GT': 0x37,
'Skull Pots': 0x76,
'Skull Left Drop': 0x77,
'Skull Pinball': 0x78,
'Skull Back Drop': 0x79,
'Sewer Drop': 0x81
}
entrance_data = {
'Room Ids': (0x14577, 2),
'Relative coords': (0x14681, 8),
'ScrollX': (0x14AA9, 2),
'ScrollY': (0x14BB3, 2),
'LinkX': (0x14CBD, 2),
'LinkY': (0x14DC7, 2),
'CameraX': (0x14ED1, 2),
'CameraY': (0x14FDB, 2),
'Blockset': (0x150e5, 1),
'FloorValues': (0x1516A, 1),
'Dungeon Value': (0x151EF, 1),
'Frame on Exit': (0x15274, 1),
'BG Setting': (0x152F9, 1),
'HV Scroll': (0x1537E, 1),
'Scroll Quad': (0x15403, 1),
'Exit Door': (0x15488, 2),
'Music': (0x15592, 1)
}
def read_layout_data(old_rom='Zelda no Densetsu - Kamigami no Triforce (Japan).sfc'):
with open(old_rom, 'rb') as stream:
old_rom_data = bytearray(stream.read())
string = ''
for room in range(0, 0xff+1):
# print(ent)
pointer_start = 0xf8000+room*3
highbyte = old_rom_data[pointer_start+2]
midbyte = old_rom_data[pointer_start+1]
midbyte = midbyte - 0x80 if highbyte % 2 == 0 else midbyte
pointer = highbyte // 2 * 0x10000
pointer += midbyte * 0x100
pointer += old_rom_data[pointer_start]
layout_byte = old_rom_data[pointer+1]
layout = (layout_byte & 0x1c) >> 2
string += hex(room) + ':' + str(layout) + '\n'
print(string)
def read_entrance_data(old_rom='Zelda no Densetsu - Kamigami no Triforce (Japan).sfc'):
with open(old_rom, 'rb') as stream:
old_rom_data = bytearray(stream.read())
for ent, offset in entrance_offsets.items():
# print(ent)
string = ent
for dp, data in entrance_data.items():
byte_array = []
address, size = data
for i in range(0, size):
byte_array.append(old_rom_data[address+(offset*size)+i])
some_bytes = ', '.join('0x{:02x}'.format(x) for x in byte_array)
string += '\t'+some_bytes
# print("%s: %s" % (dp, bytes))
print(string)
def print_wiki_doors_by_region(d_regions, world, player):
for d, region_list in d_regions.items():
tile_map = {}
for region in region_list:
tile = None
r = world.get_region(region, player)
for ext in r.exits:
door = world.check_for_door(ext.name, player)
if door is not None and door.roomIndex != -1:
tile = door.roomIndex
break
if tile is not None:
if tile not in tile_map:
tile_map[tile] = []
tile_map[tile].append(r)
toprint = ""
toprint += ('<!-- ' + d + ' -->') + "\n"
toprint += ('== Room List ==') + "\n"
toprint += "\n"
toprint += ('{| class="wikitable"') + "\n"
toprint += ('|-') + "\n"
toprint += ('! Room !! Supertile !! Doors') + "\n"
for tile, region_list in tile_map.items():
tile_done = False
for region in region_list:
toprint += ('|-') + "\n"
toprint += ('| {{Dungeon Room|{{PAGENAME}}|' + region.name + '}}') + "\n"
if not tile_done:
listlen = len(region_list)
link = '| {{UnderworldMapLink|'+str(tile)+'}}'
toprint += (link if listlen < 2 else '| rowspan = '+str(listlen)+' '+link) + "\n"
tile_done = True
strs_to_print = []
for ext in region.exits:
strs_to_print.append('{{Dungeon Door|{{PAGENAME}}|' + ext.name + '}}')
toprint += ('| '+'<br />'.join(strs_to_print))
toprint += "\n"
toprint += ('|}') + "\n"
with open(os.path.join(".","resources", "user", "regions-" + d + ".txt"),"w+") as f:
f.write(toprint)
def update_deprecated_args(args):
if args:
argVars = vars(args)
truthy = [ 1, True, "True", "true" ]
# Hints default to TRUE
# Don't do: Yes
# Do: No
if "no_hints" in argVars:
src = "no_hints"
if isinstance(argVars["hints"],dict):
tmp = {}
for idx in range(1,len(argVars["hints"]) + 1):
tmp[idx] = argVars[src] not in truthy # tmp = !src
args.hints = tmp # dest = tmp
else:
args.hints = args.no_hints not in truthy # dest = !src
# Don't do: No
# Do: Yes
if "hints" in argVars:
src = "hints"
if isinstance(argVars["hints"],dict):
tmp = {}
for idx in range(1,len(argVars["hints"]) + 1):
tmp[idx] = argVars[src] not in truthy # tmp = !src
args.no_hints = tmp # dest = tmp
else:
args.no_hints = args.hints not in truthy # dest = !src
# Spoiler defaults to FALSE
# Don't do: No
# Do: Yes
if "create_spoiler" in argVars:
args.suppress_spoiler = not args.create_spoiler in truthy
# Don't do: Yes
# Do: No
if "suppress_spoiler" in argVars:
args.create_spoiler = not args.suppress_spoiler in truthy
# ROM defaults to TRUE
# Don't do: Yes
# Do: No
if "suppress_rom" in argVars:
args.create_rom = not args.suppress_rom in truthy
# Don't do: No
# Do: Yes
if "create_rom" in argVars:
args.suppress_rom = not args.create_rom in truthy
# Shuffle Ganon defaults to TRUE
# Don't do: Yes
# Do: No
if "no_shuffleganon" in argVars:
args.shuffleganon = not args.no_shuffleganon in truthy
# Don't do: No
# Do: Yes
if "shuffleganon" in argVars:
args.no_shuffleganon = not args.shuffleganon in truthy
# Playthrough defaults to TRUE
# Don't do: Yes
# Do: No
if "skip_playthrough" in argVars:
args.calc_playthrough = not args.skip_playthrough in truthy
# Don't do: No
# Do: Yes
if "calc_playthrough" in argVars:
args.skip_playthrough = not args.calc_playthrough in truthy
return args
def print_wiki_doors_by_room(d_regions, world, player):
for d, region_list in d_regions.items():
tile_map = {}
for region in region_list:
tile = None
r = world.get_region(region, player)
for ext in r.exits:
door = world.check_for_door(ext.name, player)
if door is not None and door.roomIndex != -1:
tile = door.roomIndex
break
if tile is not None:
if tile not in tile_map:
tile_map[tile] = []
tile_map[tile].append(r)
toprint = ""
toprint += ('<!-- ' + d + ' -->') + "\n"
for tile, region_list in tile_map.items():
for region in region_list:
toprint += ('<!-- ' + region.name + ' -->') + "\n"
toprint += ('{{Infobox dungeon room') + "\n"
toprint += ('| dungeon = {{ROOTPAGENAME}}') + "\n"
toprint += ('| supertile = ' + str(tile)) + "\n"
toprint += ('| tile = x') + "\n"
toprint += ('}}') + "\n"
toprint += ('') + "\n"
toprint += ('== Doors ==') + "\n"
toprint += ('{| class="wikitable"') + "\n"
toprint += ('|-') + "\n"
toprint += ('! Door !! Room Side !! Requirement') + "\n"
for ext in region.exits:
ext_part = ext.name.replace(region.name,'')
ext_part = ext_part.strip()
toprint += ('{{DungeonRoomDoorList/Row|{{ROOTPAGENAME}}|{{SUBPAGENAME}}|' + ext_part + '|Side|}}') + "\n"
toprint += ('|}') + "\n"
toprint += ('') + "\n"
with open(os.path.join(".","resources", "user", "rooms-" + d + ".txt"),"w+") as f:
f.write(toprint)
def print_xml_doors(d_regions, world, player):
root = ET.Element('root')
for d, region_list in d_regions.items():
tile_map = {}
for region in region_list:
tile = None
r = world.get_region(region, player)
for ext in r.exits:
door = world.check_for_door(ext.name, player)
if door is not None and door.roomIndex != -1:
tile = door.roomIndex
break
if tile is not None:
if tile not in tile_map:
tile_map[tile] = []
tile_map[tile].append(r)
dungeon = ET.SubElement(root, 'dungeon', {'name': d})
for tile, r_list in tile_map.items():
supertile = ET.SubElement(dungeon, 'supertile', {'id': str(tile)})
for region in r_list:
room = ET.SubElement(supertile, 'room', {'name': region.name})
for ext in region.exits:
ET.SubElement(room, 'door', {'name': ext.name})
ET.dump(root)
def print_graph(world):
root = ET.Element('root')
for region in world.regions:
r = ET.SubElement(root, 'region', {'name': region.name})
for ext in region.exits:
attribs = {'name': ext.name}
if ext.connected_region:
attribs['connected_region'] = ext.connected_region.name
if ext.door and ext.door.dest:
attribs['dest'] = ext.door.dest.name
ET.SubElement(r, 'exit', attribs)
ET.dump(root)
if __name__ == '__main__':
# make_new_base2current()
# read_entrance_data(old_rom=sys.argv[1])
read_layout_data(old_rom=sys.argv[1])
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,119
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/Doors.py
|
from BaseClasses import Door, DoorType, Direction, CrystalBarrier
from RoomData import PairedDoor
# constants
We = Direction.West
Ea = Direction.East
So = Direction.South
No = Direction.North
Up = Direction.Up
Dn = Direction.Down
# door offsets
Top = 0
Left = 0
Mid = 1
Bot = 2
Right = 2
# layer numbers
High = 0
Low = 1
# Quadrants - just been using this in my head - no reason to keep them labeled this way
A = 0
S = 1
Z = 2
X = 3
# Layer transitions
HTH = 0 # High to High 00
HTL = 1 # High to Low 01
LTH = 2 # Low to High 10
LTL = 3 # Low to Low 11
# Type Shortcuts
Nrml = DoorType.Normal
StrS = DoorType.StraightStairs
Hole = DoorType.Hole
Warp = DoorType.Warp
Sprl = DoorType.SpiralStairs
Lddr = DoorType.Ladder
Open = DoorType.Open
Lgcl = DoorType.Logical
Intr = DoorType.Interior
def create_doors(world, player):
doors = [
# hyrule castle
create_door(player, 'Hyrule Castle Lobby W', Nrml).dir(We, 0x61, Mid, High).toggler().pos(0),
create_door(player, 'Hyrule Castle Lobby E', Nrml).dir(Ea, 0x61, Mid, High).toggler().pos(2),
create_door(player, 'Hyrule Castle Lobby WN', Nrml).dir(We, 0x61, Top, High).pos(1),
create_door(player, 'Hyrule Castle Lobby North Stairs', StrS).dir(No, 0x61, Mid, High),
create_door(player, 'Hyrule Castle West Lobby E', Nrml).dir(Ea, 0x60, Mid, Low).toggler().pos(1),
create_door(player, 'Hyrule Castle West Lobby N', Nrml).dir(No, 0x60, Right, Low).pos(0),
create_door(player, 'Hyrule Castle West Lobby EN', Nrml).dir(Ea, 0x60, Top, High).pos(3),
create_door(player, 'Hyrule Castle East Lobby W', Nrml).dir(We, 0x62, Mid, Low).toggler().pos(0),
create_door(player, 'Hyrule Castle East Lobby N', Nrml).dir(No, 0x62, Mid, High).pos(3),
create_door(player, 'Hyrule Castle East Lobby NW', Nrml).dir(No, 0x62, Left, Low).pos(2),
create_door(player, 'Hyrule Castle East Hall W', Nrml).dir(We, 0x52, Top, Low).pos(0),
create_door(player, 'Hyrule Castle East Hall S', Nrml).dir(So, 0x52, Mid, High).pos(2),
create_door(player, 'Hyrule Castle East Hall SW', Nrml).dir(So, 0x52, Left, Low).pos(1),
create_door(player, 'Hyrule Castle West Hall E', Nrml).dir(Ea, 0x50, Top, Low).pos(0),
create_door(player, 'Hyrule Castle West Hall S', Nrml).dir(So, 0x50, Right, Low).pos(1),
create_door(player, 'Hyrule Castle Back Hall W', Nrml).dir(We, 0x01, Top, Low).pos(0),
create_door(player, 'Hyrule Castle Back Hall E', Nrml).dir(Ea, 0x01, Top, Low).pos(1),
create_door(player, 'Hyrule Castle Back Hall Down Stairs', Sprl).dir(Dn, 0x01, 0, HTL).ss(A, 0x2a, 0x00),
create_door(player, 'Hyrule Castle Throne Room Tapestry', Lgcl),
create_door(player, 'Hyrule Castle Tapestry Backwards', Lgcl),
create_door(player, 'Hyrule Castle Throne Room N', Nrml).dir(No, 0x51, Mid, High).pos(1),
create_door(player, 'Hyrule Castle Throne Room South Stairs', StrS).dir(So, 0x51, Mid, Low),
# hyrule dungeon level
create_door(player, 'Hyrule Dungeon Map Room Up Stairs', Sprl).dir(Up, 0x72, 0, LTH).ss(A, 0x4b, 0xec),
create_door(player, 'Hyrule Dungeon Map Room Key Door S', Intr).dir(So, 0x72, Mid, High).small_key().pos(0),
create_door(player, 'Hyrule Dungeon North Abyss Key Door N', Intr).dir(No, 0x72, Mid, High).small_key().pos(0),
create_door(player, 'Hyrule Dungeon North Abyss South Edge', Open).dir(So, 0x72, None, Low).edge(0, Z, 0x10),
create_door(player, 'Hyrule Dungeon North Abyss Catwalk Edge', Open).dir(So, 0x72, None, High).edge(1, Z, 0x08),
create_door(player, 'Hyrule Dungeon North Abyss Catwalk Dropdown', Lgcl),
create_door(player, 'Hyrule Dungeon South Abyss North Edge', Open).dir(No, 0x82, None, Low).edge(0, A, 0x10),
create_door(player, 'Hyrule Dungeon South Abyss West Edge', Open).dir(We, 0x82, None, Low).edge(3, Z, 0x18),
create_door(player, 'Hyrule Dungeon South Abyss Catwalk North Edge', Open).dir(No, 0x82, None, High).edge(1, A, 0x08),
create_door(player, 'Hyrule Dungeon South Abyss Catwalk West Edge', Open).dir(We, 0x82, None, High).edge(4, A, 0x10),
create_door(player, 'Hyrule Dungeon Guardroom Catwalk Edge', Open).dir(Ea, 0x81, None, High).edge(3, S, 0x10),
create_door(player, 'Hyrule Dungeon Guardroom Abyss Edge', Open).dir(Ea, 0x81, None, Low).edge(4, X, 0x18),
create_door(player, 'Hyrule Dungeon Guardroom N', Nrml).dir(No, 0x81, Left, Low).pos(0),
create_door(player, 'Hyrule Dungeon Armory S', Nrml).dir(So, 0x71, Left, Low).trap(0x2).pos(1),
create_door(player, 'Hyrule Dungeon Armory ES', Intr).dir(Ea, 0x71, Left, Low).pos(2),
create_door(player, 'Hyrule Dungeon Armory Boomerang WS', Intr).dir(We, 0x71, Left, Low).pos(2),
create_door(player, 'Hyrule Dungeon Armory Interior Key Door N', Intr).dir(No, 0x71, Left, High).small_key().pos(0),
create_door(player, 'Hyrule Dungeon Armory Interior Key Door S', Intr).dir(So, 0x71, Left, High).small_key().pos(0),
create_door(player, 'Hyrule Dungeon Armory Down Stairs', Sprl).dir(Dn, 0x71, 0, HTL).ss(A, 0x11, 0xa8, True),
create_door(player, 'Hyrule Dungeon Staircase Up Stairs', Sprl).dir(Up, 0x70, 2, LTH).ss(A, 0x32, 0x94, True),
create_door(player, 'Hyrule Dungeon Staircase Down Stairs', Sprl).dir(Dn, 0x70, 1, HTH).ss(A, 0x11, 0x58),
create_door(player, 'Hyrule Dungeon Cellblock Up Stairs', Sprl).dir(Up, 0x80, 0, HTH).ss(A, 0x1a, 0x44),
# sewers
create_door(player, 'Sewers Behind Tapestry S', Nrml).dir(So, 0x41, Mid, High).no_exit().trap(0x4).pos(0),
create_door(player, 'Sewers Behind Tapestry Down Stairs', Sprl).dir(Dn, 0x41, 0, HTH).ss(S, 0x12, 0xb0),
create_door(player, 'Sewers Rope Room Up Stairs', Sprl).dir(Up, 0x42, 0, HTH).ss(S, 0x1b, 0x9c),
create_door(player, 'Sewers Rope Room North Stairs', StrS).dir(No, 0x42, Mid, High),
create_door(player, 'Sewers Dark Cross South Stairs', StrS).dir(So, 0x32, Mid, High),
create_door(player, 'Sewers Dark Cross Key Door N', Nrml).dir(No, 0x32, Mid, High).small_key().pos(0),
create_door(player, 'Sewers Water S', Nrml).dir(So, 0x22, Mid, High).small_key().pos(0),
create_door(player, 'Sewers Water W', Nrml).dir(We, 0x22, Bot, High).pos(1),
create_door(player, 'Sewers Key Rat E', Nrml).dir(Ea, 0x21, Bot, High).pos(1),
create_door(player, 'Sewers Key Rat Key Door N', Nrml).dir(No, 0x21, Right, High).small_key().pos(0),
create_door(player, 'Sewers Secret Room Key Door S', Nrml).dir(So, 0x11, Right, High).small_key().pos(2),
create_door(player, 'Sewers Rat Path WS', Intr).dir(We, 0x11, Bot, High).pos(1),
create_door(player, 'Sewers Rat Path WN', Intr).dir(We, 0x11, Top, High).pos(0),
create_door(player, 'Sewers Secret Room ES', Intr).dir(Ea, 0x11, Bot, High).pos(1),
create_door(player, 'Sewers Secret Room EN', Intr).dir(Ea, 0x11, Top, High).pos(0),
create_door(player, 'Sewers Secret Room Push Block', Lgcl),
create_door(player, 'Sewers Secret Room Up Stairs', Sprl).dir(Up, 0x11, 0, LTH).ss(S, 0x33, 0x6c, True),
create_door(player, 'Sewers Pull Switch Down Stairs', Sprl).dir(Dn, 0x02, 0, HTL).ss(S, 0x12, 0x80),
create_door(player, 'Sewers Yet More Rats S', Intr).dir(So, 0x02, Mid, Low).pos(1),
create_door(player, 'Sewers Pull Switch N', Intr).dir(No, 0x02, Mid, Low).pos(1),
create_door(player, 'Sewers Pull Switch S', Nrml).dir(So, 0x02, Mid, Low).trap(0x4).toggler().pos(0),
# logically one way the sanc, but should be linked - also toggle
create_door(player, 'Sanctuary N', Nrml).dir(No, 0x12, Mid, High).no_exit().toggler().pos(0),
# Eastern Palace
create_door(player, 'Eastern Lobby N', Intr).dir(No, 0xc9, Mid, High).pos(0),
create_door(player, 'Eastern Lobby Bridge S', Intr).dir(So, 0xc9, Mid, High).pos(0),
create_door(player, 'Eastern Lobby NW', Intr).dir(No, 0xc9, Left, High).pos(2),
create_door(player, 'Eastern Lobby Left Ledge SW', Intr).dir(So, 0xc9, Left, High).pos(2),
create_door(player, 'Eastern Lobby NE', Intr).dir(No, 0xc9, Right, High).pos(3),
create_door(player, 'Eastern Lobby Right Ledge SE', Intr).dir(So, 0xc9, Right, High).pos(3),
create_door(player, 'Eastern Lobby Bridge N', Nrml).dir(No, 0xc9, Mid, High).pos(1).trap(0x2),
create_door(player, 'Eastern Cannonball S', Nrml).dir(So, 0xb9, Mid, High).pos(2),
create_door(player, 'Eastern Cannonball N', Nrml).dir(No, 0xb9, Mid, High).pos(1),
create_door(player, 'Eastern Cannonball Ledge WN', Nrml).dir(We, 0xb9, Top, High).pos(3),
create_door(player, 'Eastern Cannonball Ledge Key Door EN', Nrml).dir(Ea, 0xb9, Top, High).small_key().pos(0),
create_door(player, 'Eastern Courtyard Ledge S', Nrml).dir(So, 0xa9, Mid, High).pos(5),
create_door(player, 'Eastern Courtyard Ledge W', Nrml).dir(We, 0xa9, Mid, High).trap(0x4).pos(0),
create_door(player, 'Eastern Courtyard Ledge E', Nrml).dir(Ea, 0xa9, Mid, High).trap(0x2).pos(1),
create_door(player, 'Eastern East Wing W', Nrml).dir(We, 0xaa, Mid, High).pos(4),
create_door(player, 'Eastern East Wing EN', Intr).dir(Ea, 0xaa, Top, High).pos(2),
create_door(player, 'Eastern Pot Switch WN', Intr).dir(We, 0xaa, Top, High).pos(2),
create_door(player, 'Eastern East Wing ES', Intr).dir(Ea, 0xaa, Bot, High).pos(3),
create_door(player, 'Eastern Map Balcony WS', Intr).dir(We, 0xaa, Bot, High).pos(3),
create_door(player, 'Eastern Pot Switch SE', Intr).dir(So, 0xaa, Right, High).pos(0),
create_door(player, 'Eastern Map Room NE', Intr).dir(No, 0xaa, Right, High).pos(0),
create_door(player, 'Eastern Map Balcony Hook Path', Lgcl),
create_door(player, 'Eastern Map Room Drop Down', Lgcl),
create_door(player, 'Eastern West Wing E', Nrml).dir(Ea, 0xa8, Mid, High).pos(5),
create_door(player, 'Eastern West Wing WS', Intr).dir(We, 0xa8, Bot, High).pos(0),
create_door(player, 'Eastern Stalfos Spawn ES', Intr).dir(Ea, 0xa8, Bot, High).pos(0),
create_door(player, 'Eastern Stalfos Spawn NW', Intr).dir(No, 0xa8, Left, High).pos(1),
create_door(player, 'Eastern Compass Room SW', Intr).dir(So, 0xa8, Left, High).pos(1),
create_door(player, 'Eastern Compass Room EN', Intr).dir(Ea, 0xa8, Top, High).pos(3),
create_door(player, 'Eastern Hint Tile WN', Intr).dir(We, 0xa8, Top, High).pos(3),
create_door(player, 'Eastern Hint Tile EN', Nrml).dir(Ea, 0xa8, Top, Low).pos(4),
create_door(player, 'Eastern Hint Tile Blocked Path SE', Nrml).dir(So, 0xa8, Right, High).small_key().pos(2).kill(),
create_door(player, 'Eastern Hint Tile Push Block', Lgcl),
create_door(player, 'Eastern Courtyard WN', Nrml).dir(We, 0xa9, Top, Low).pos(3),
create_door(player, 'Eastern Courtyard EN', Nrml).dir(Ea, 0xa9, Top, Low).pos(4),
create_door(player, 'Eastern Courtyard N', Nrml).dir(No, 0xa9, Mid, High).big_key().pos(2),
create_door(player, 'Eastern Courtyard Potholes', Hole),
create_door(player, 'Eastern Fairies\' Warp', Warp),
create_door(player, 'Eastern Map Valley WN', Nrml).dir(We, 0xaa, Top, Low).pos(1),
create_door(player, 'Eastern Map Valley SW', Nrml).dir(So, 0xaa, Left, High).pos(5),
create_door(player, 'Eastern Dark Square NW', Nrml).dir(No, 0xba, Left, High).trap(0x2).pos(1),
create_door(player, 'Eastern Dark Square Key Door WN', Nrml).dir(We, 0xba, Top, High).small_key().pos(0),
create_door(player, 'Eastern Dark Square EN', Intr).dir(Ea, 0xba, Top, High).pos(2),
create_door(player, 'Eastern Dark Pots WN', Intr).dir(We, 0xba, Top, High).pos(2),
create_door(player, 'Eastern Big Key EN', Nrml).dir(Ea, 0xb8, Top, High).pos(1),
create_door(player, 'Eastern Big Key NE', Nrml).dir(No, 0xb8, Right, High).big_key().pos(0),
create_door(player, 'Eastern Darkness S', Nrml).dir(So, 0x99, Mid, High).small_key().pos(1),
create_door(player, 'Eastern Darkness NE', Intr).dir(No, 0x99, Right, High).pos(2),
create_door(player, 'Eastern Rupees SE', Intr).dir(So, 0x99, Right, High).pos(2),
# Up is a keydoor and down is not. Only the up stairs should be considered a key door for now.
create_door(player, 'Eastern Darkness Up Stairs', Sprl).dir(Up, 0x99, 0, HTH).ss(Z, 0x1a, 0x6c, False, True).small_key().pos(0),
create_door(player, 'Eastern Attic Start Down Stairs', Sprl).dir(Dn, 0xda, 0, HTH).ss(Z, 0x11, 0x80, True, True),
create_door(player, 'Eastern Attic Start WS', Nrml).dir(We, 0xda, Bot, High).trap(0x4).pos(0),
create_door(player, 'Eastern False Switches ES', Nrml).dir(Ea, 0xd9, Bot, High).trap(0x1).pos(2),
create_door(player, 'Eastern False Switches WS', Intr).dir(We, 0xd9, Bot, High).pos(1),
create_door(player, 'Eastern Cannonball Hell ES', Intr).dir(Ea, 0xd9, Bot, High).pos(1),
create_door(player, 'Eastern Cannonball Hell WS', Nrml).dir(We, 0xd9, Bot, High).trap(0x4).pos(0),
create_door(player, 'Eastern Single Eyegore ES', Nrml).dir(Ea, 0xd8, Bot, High).pos(2),
create_door(player, 'Eastern Single Eyegore NE', Intr).dir(No, 0xd8, Right, High).pos(1),
create_door(player, 'Eastern Duo Eyegores SE', Intr).dir(So, 0xd8, Right, High).pos(1),
create_door(player, 'Eastern Duo Eyegores NE', Nrml).dir(No, 0xd8, Right, High).trap(0x4).pos(0),
create_door(player, 'Eastern Boss SE', Nrml).dir(So, 0xc8, Right, High).no_exit().trap(0x4).pos(0),
# Desert Palace
create_door(player, 'Desert Main Lobby NW Edge', Open).dir(No, 0x84, None, High).edge(3, A, 0x20),
create_door(player, 'Desert Main Lobby N Edge', Open).dir(No, 0x84, None, High).edge(4, A, 0xa0),
create_door(player, 'Desert Main Lobby NE Edge', Open).dir(No, 0x84, None, High).edge(5, S, 0x20),
create_door(player, 'Desert Main Lobby E Edge', Open).dir(Ea, 0x84, None, High).edge(5, S, 0xa0),
create_door(player, 'Desert Main Lobby Left Path', Lgcl),
create_door(player, 'Desert Main Lobby Right Path', Lgcl),
create_door(player, 'Desert Left Alcove Path', Lgcl),
create_door(player, 'Desert Right Alcove Path', Lgcl),
create_door(player, 'Desert Dead End Edge', Open).dir(So, 0x74, None, High).edge(4, Z, 0xa0),
create_door(player, 'Desert East Wing W Edge', Open).dir(We, 0x85, None, High).edge(5, A, 0xa0),
create_door(player, 'Desert East Wing N Edge', Open).dir(No, 0x85, None, High).edge(6, A, 0x20),
create_door(player, 'Desert East Lobby WS', Intr).dir(We, 0x85, Bot, High).pos(3),
create_door(player, 'Desert East Wing ES', Intr).dir(Ea, 0x85, Bot, High).pos(3),
create_door(player, 'Desert East Wing Key Door EN', Intr).dir(Ea, 0x85, Top, High).small_key().pos(1),
create_door(player, 'Desert Compass Key Door WN', Intr).dir(We, 0x85, Top, High).small_key().pos(1),
create_door(player, 'Desert Compass NW', Nrml).dir(No, 0x85, Right, High).trap(0x4).pos(0),
create_door(player, 'Desert Cannonball S', Nrml).dir(So, 0x75, Right, High).pos(1),
create_door(player, 'Desert Arrow Pot Corner S Edge', Open).dir(So, 0x75, None, High).edge(6, Z, 0x20),
create_door(player, 'Desert Arrow Pot Corner W Edge', Open).dir(We, 0x75, None, High).edge(2, Z, 0x20),
create_door(player, 'Desert Arrow Pot Corner NW', Intr).dir(No, 0x75, Left, High).pos(0),
create_door(player, 'Desert Trap Room SW', Intr).dir(So, 0x75, Left, High).pos(0),
create_door(player, 'Desert North Hall SE Edge', Open).dir(So, 0x74, None, High).edge(5, X, 0x20),
create_door(player, 'Desert North Hall SW Edge', Open).dir(So, 0x74, None, High).edge(3, Z, 0x20),
create_door(player, 'Desert North Hall W Edge', Open).dir(We, 0x74, None, High).edge(1, Z, 0x20),
create_door(player, 'Desert North Hall E Edge', Open).dir(Ea, 0x74, None, High).edge(2, X, 0x20),
create_door(player, 'Desert North Hall NW', Intr).dir(No, 0x74, Left, High).pos(1),
create_door(player, 'Desert Map SW', Intr).dir(So, 0x74, Left, High).pos(1),
create_door(player, 'Desert North Hall NE', Intr).dir(No, 0x74, Right, High).pos(0),
create_door(player, 'Desert Map SE', Intr).dir(So, 0x74, Right, High).pos(0),
create_door(player, 'Desert Sandworm Corner S Edge', Open).dir(So, 0x73, None, High).edge(2, X, 0x20),
create_door(player, 'Desert Sandworm Corner E Edge', Open).dir(Ea, 0x73, None, High).edge(1, X, 0x20),
create_door(player, 'Desert Sandworm Corner NE', Intr).dir(No, 0x73, Right, High).pos(2),
create_door(player, 'Desert Bonk Torch SE', Intr).dir(So, 0x73, Right, High).pos(2),
create_door(player, 'Desert Sandworm Corner WS', Intr).dir(We, 0x73, Bot, High).pos(1),
create_door(player, 'Desert Circle of Pots ES', Intr).dir(Ea, 0x73, Bot, High).pos(1),
create_door(player, 'Desert Circle of Pots NW', Intr).dir(No, 0x73, Left, High).pos(0),
create_door(player, 'Desert Big Chest SW', Intr).dir(So, 0x73, Left, High).pos(0),
create_door(player, 'Desert West Wing N Edge', Open).dir(No, 0x83, None, High).edge(2, S, 0x20),
create_door(player, 'Desert West Wing WS', Intr).dir(We, 0x83, Bot, High).pos(2),
create_door(player, 'Desert West Lobby ES', Intr).dir(Ea, 0x83, Bot, High).pos(2),
create_door(player, 'Desert West Lobby NW', Intr).dir(No, 0x83, Left, High).pos(0),
create_door(player, 'Desert Fairy Fountain SW', Intr).dir(So, 0x83, Left, High).pos(0),
# Desert Back
create_door(player, 'Desert Back Lobby NW', Intr).dir(No, 0x63, Left, High).pos(1),
create_door(player, 'Desert Tiles 1 SW', Intr).dir(So, 0x63, Left, High).pos(1),
create_door(player, 'Desert Tiles 1 Up Stairs', Sprl).dir(Up, 0x63, 0, HTH).ss(A, 0x1b, 0x6c, True).small_key().pos(0),
create_door(player, 'Desert Bridge Down Stairs', Sprl).dir(Dn, 0x53, 0, HTH).ss(A, 0x0f, 0x80, True),
create_door(player, 'Desert Bridge SW', Intr).dir(So, 0x53, Left, High).pos(0),
create_door(player, 'Desert Four Statues NW', Intr).dir(No, 0x53, Left, High).pos(0),
create_door(player, 'Desert Four Statues ES', Intr).dir(Ea, 0x53, Bot, High).pos(1),
create_door(player, 'Desert Beamos Hall WS', Intr).dir(We, 0x53, Bot, High).pos(1),
create_door(player, 'Desert Beamos Hall NE', Nrml).dir(No, 0x53, Right, High).small_key().pos(2),
create_door(player, 'Desert Tiles 2 SE', Nrml).dir(So, 0x43, Right, High).small_key().pos(2).kill(),
create_door(player, 'Desert Tiles 2 NE', Intr).dir(No, 0x43, Right, High).small_key().pos(1),
create_door(player, 'Desert Wall Slide SE', Intr).dir(So, 0x43, Right, High).small_key().pos(1),
create_door(player, 'Desert Wall Slide NW', Nrml).dir(No, 0x43, Left, High).big_key().pos(0).no_entrance(),
create_door(player, 'Desert Boss SW', Nrml).dir(So, 0x33, Left, High).no_exit().trap(0x4).pos(0),
# Hera
create_door(player, 'Hera Lobby Down Stairs', Sprl).dir(Dn, 0x77, 3, HTL).ss(Z, 0x21, 0x90, False, True),
create_door(player, 'Hera Lobby Key Stairs', Sprl).dir(Dn, 0x77, 1, HTL).ss(A, 0x12, 0x80).small_key().pos(1),
create_door(player, 'Hera Lobby Up Stairs', Sprl).dir(Up, 0x77, 2, HTL).ss(X, 0x2b, 0x5c, False, True),
create_door(player, 'Hera Basement Cage Up Stairs', Sprl).dir(Up, 0x87, 3, LTH).ss(Z, 0x42, 0x7c, True, True),
create_door(player, 'Hera Tile Room Up Stairs', Sprl).dir(Up, 0x87, 1, LTH).ss(A, 0x32, 0x6c, True, True),
create_door(player, 'Hera Tile Room EN', Intr).dir(Ea, 0x87, Top, High).pos(0),
create_door(player, 'Hera Tridorm WN', Intr).dir(We, 0x87, Top, High).pos(0),
create_door(player, 'Hera Tridorm SE', Intr).dir(So, 0x87, Right, High).pos(1),
create_door(player, 'Hera Torches NE', Intr).dir(No, 0x87, Right, High).pos(1),
create_door(player, 'Hera Beetles Down Stairs', Sprl).dir(Dn, 0x31, 2, LTH).ss(X, 0x3a, 0x70, True, True),
create_door(player, 'Hera Beetles WS', Intr).dir(We, 0x31, Bot, High).pos(1),
create_door(player, 'Hera Beetles Holes', Hole),
create_door(player, 'Hera Startile Corner ES', Intr).dir(Ea, 0x31, Bot, High).pos(1),
create_door(player, 'Hera Startile Corner NW', Intr).dir(No, 0x31, Left, High).big_key().pos(0),
create_door(player, 'Hera Startile Corner Holes', Hole),
# technically ugly but causes lots of failures in basic
create_door(player, 'Hera Startile Wide SW', Intr).dir(So, 0x31, Left, High).pos(0),
create_door(player, 'Hera Startile Wide Up Stairs', Sprl).dir(Up, 0x31, 0, HTH).ss(S, 0x6b, 0xac, False, True),
create_door(player, 'Hera Startile Wide Holes', Hole),
create_door(player, 'Hera 4F Down Stairs', Sprl).dir(Dn, 0x27, 0, HTH).ss(S, 0x62, 0xc0),
create_door(player, 'Hera 4F Up Stairs', Sprl).dir(Up, 0x27, 1, HTH).ss(A, 0x6b, 0x2c),
create_door(player, 'Hera 4F Holes', Hole),
create_door(player, 'Hera Big Chest Hook Path', Lgcl),
create_door(player, 'Hera Big Chest Landing Exit', Lgcl),
create_door(player, 'Hera Big Chest Landing Holes', Hole),
create_door(player, 'Hera 5F Down Stairs', Sprl).dir(Dn, 0x17, 1, HTH).ss(A, 0x62, 0x40),
create_door(player, 'Hera 5F Up Stairs', Sprl).dir(Up, 0x17, 0, HTH).ss(S, 0x6a, 0x9c),
create_door(player, 'Hera 5F Star Hole', Hole),
create_door(player, 'Hera 5F Pothole Chain', Hole),
create_door(player, 'Hera 5F Normal Holes', Hole),
create_door(player, 'Hera Fairies\' Warp', Warp),
create_door(player, 'Hera Boss Down Stairs', Sprl).dir(Dn, 0x07, 0, HTH).ss(S, 0x61, 0xb0).kill(),
create_door(player, 'Hera Boss Outer Hole', Hole),
create_door(player, 'Hera Boss Inner Hole', Hole),
# Castle Tower
create_door(player, 'Tower Lobby NW', Intr).dir(No, 0xe0, Left, High).pos(1),
create_door(player, 'Tower Gold Knights SW', Intr).dir(So, 0xe0, Left, High).pos(1),
create_door(player, 'Tower Gold Knights EN', Intr).dir(Ea, 0xe0, Top, High).pos(0),
create_door(player, 'Tower Room 03 WN', Intr).dir(We, 0xe0, Bot, High).pos(0),
create_door(player, 'Tower Room 03 Up Stairs', Sprl).dir(Up, 0xe0, 0, HTH).ss(S, 0x1a, 0x6c, True, True).small_key().pos(2),
create_door(player, 'Tower Lone Statue Down Stairs', Sprl).dir(Dn, 0xd0, 0, HTH).ss(S, 0x11, 0x80, True, True),
create_door(player, 'Tower Lone Statue WN', Intr).dir(We, 0xd0, Top, High).pos(1),
create_door(player, 'Tower Dark Maze EN', Intr).dir(Ea, 0xd0, Top, High).pos(1),
create_door(player, 'Tower Dark Maze ES', Intr).dir(Ea, 0xd0, Bot, High).small_key().pos(0),
create_door(player, 'Tower Dark Chargers WS', Intr).dir(We, 0xd0, Bot, High).small_key().pos(0),
create_door(player, 'Tower Dark Chargers Up Stairs', Sprl).dir(Up, 0xd0, 2, HTH).ss(X, 0x1b, 0x8c, True, True),
create_door(player, 'Tower Dual Statues Down Stairs', Sprl).dir(Dn, 0xc0, 2, HTH).ss(X, 0x12, 0xa0, True, True),
create_door(player, 'Tower Dual Statues WS', Intr).dir(We, 0xc0, Bot, High).pos(1),
create_door(player, 'Tower Dark Pits ES', Intr).dir(Ea, 0xc0, Bot, High).pos(1),
create_door(player, 'Tower Dark Pits EN', Intr).dir(Ea, 0xc0, Top, High).pos(0),
create_door(player, 'Tower Dark Archers WN', Intr).dir(We, 0xc0, Top, High).pos(0),
create_door(player, 'Tower Dark Archers Up Stairs', Sprl).dir(Up, 0xc0, 0, HTH).ss(S, 0x1b, 0x6c, True, True).small_key().pos(2),
create_door(player, 'Tower Red Spears Down Stairs', Sprl).dir(Dn, 0xb0, 0, HTH).ss(S, 0x12, 0x80, True, True),
create_door(player, 'Tower Red Spears WN', Intr).dir(We, 0xb0, Top, High).pos(1),
create_door(player, 'Tower Red Guards EN', Intr).dir(Ea, 0xb0, Top, High).pos(1),
create_door(player, 'Tower Red Guards SW', Intr).dir(So, 0xb0, Left, High).pos(0),
create_door(player, 'Tower Circle of Pots NW', Intr).dir(No, 0xb0, Left, High).pos(0),
create_door(player, 'Tower Circle of Pots ES', Intr).dir(Ea, 0xb0, Bot, High).small_key().pos(2),
create_door(player, 'Tower Pacifist Run WS', Intr).dir(We, 0xb0, Bot, High).small_key().pos(2),
create_door(player, 'Tower Pacifist Run Up Stairs', Sprl).dir(Up, 0xb0, 2, LTH).ss(X, 0x33, 0x8c, True, True),
create_door(player, 'Tower Push Statue Down Stairs', Sprl).dir(Dn, 0x40, 0, HTL).ss(X, 0x12, 0xa0, True, True).kill(),
create_door(player, 'Tower Push Statue WS', Intr).dir(We, 0x40, Bot, Low).pos(0),
create_door(player, 'Tower Catwalk ES', Intr).dir(Ea, 0x40, Bot, Low).pos(0),
create_door(player, 'Tower Catwalk North Stairs', StrS).dir(No, 0x40, Left, High),
create_door(player, 'Tower Antechamber South Stairs', StrS).dir(So, 0x30, Left, High),
create_door(player, 'Tower Antechamber NW', Intr).dir(No, 0x30, Left, High).pos(1),
create_door(player, 'Tower Altar SW', Intr).dir(So, 0x30, Left, High).no_exit().pos(1),
create_door(player, 'Tower Altar NW', Nrml).dir(No, 0x30, Left, High).pos(0),
create_door(player, 'Tower Agahnim 1 SW', Nrml).dir(So, 0x20, Left, High).no_exit().trap(0x4).pos(0),
# Palace of Darkness
create_door(player, 'PoD Lobby N', Intr).dir(No, 0x4a, Mid, High).pos(3),
create_door(player, 'PoD Lobby NW', Intr).dir(No, 0x4a, Left, High).pos(0),
create_door(player, 'PoD Lobby NE', Intr).dir(No, 0x4a, Right, High).pos(1),
create_door(player, 'PoD Left Cage SW', Intr).dir(So, 0x4a, Left, High).pos(0),
create_door(player, 'PoD Middle Cage S', Intr).dir(So, 0x4a, Mid, High).pos(3),
create_door(player, 'PoD Middle Cage SE', Intr).dir(So, 0x4a, Right, High).pos(1),
create_door(player, 'PoD Left Cage Down Stairs', Sprl).dir(Dn, 0x4a, 1, HTH).ss(A, 0x12, 0x80, False, True),
create_door(player, 'PoD Middle Cage Down Stairs', Sprl).dir(Dn, 0x4a, 0, HTH).ss(S, 0x12, 0x80, False, True),
create_door(player, 'PoD Middle Cage N', Nrml).dir(No, 0x4a, Mid, High).small_key().pos(2),
create_door(player, 'PoD Shooter Room Up Stairs', Sprl).dir(Up, 0x09, 1, HTH).ss(A, 0x1b, 0x6c, True, True),
create_door(player, 'PoD Warp Room Up Stairs', Sprl).dir(Up, 0x09, 0, HTH).ss(S, 0x1a, 0x6c, True, True),
create_door(player, 'PoD Warp Room Warp', Warp),
create_door(player, 'PoD Pit Room S', Nrml).dir(So, 0x3a, Mid, High).small_key().pos(0),
create_door(player, 'PoD Pit Room NW', Nrml).dir(No, 0x3a, Left, High).pos(1),
create_door(player, 'PoD Pit Room NE', Nrml).dir(No, 0x3a, Right, High).pos(2),
create_door(player, 'PoD Pit Room Freefall', Hole),
create_door(player, 'PoD Pit Room Bomb Hole', Hole),
create_door(player, 'PoD Pit Room Block Path N', Lgcl),
create_door(player, 'PoD Pit Room Block Path S', Lgcl),
create_door(player, 'PoD Big Key Landing Hole', Hole),
create_door(player, 'PoD Big Key Landing Down Stairs', Sprl).dir(Dn, 0x3a, 0, HTH).ss(A, 0x11, 0x00).kill(),
create_door(player, 'PoD Basement Ledge Up Stairs', Sprl).dir(Up, 0x0a, 0, HTH).ss(A, 0x1a, 0xec).small_key().pos(0),
create_door(player, 'PoD Basement Ledge Drop Down', Lgcl),
create_door(player, 'PoD Stalfos Basement Warp', Warp),
create_door(player, 'PoD Arena Main SW', Nrml).dir(So, 0x2a, Left, High).pos(4),
create_door(player, 'PoD Arena Bridge SE', Nrml).dir(So, 0x2a, Right, High).pos(5),
create_door(player, 'PoD Arena Main NW', Nrml).dir(No, 0x2a, Left, High).small_key().pos(1),
create_door(player, 'PoD Arena Main NE', Nrml).dir(No, 0x2a, Right, High).no_exit().trap(0x4).pos(0),
create_door(player, 'PoD Arena Main Crystal Path', Lgcl),
create_door(player, 'PoD Arena Main Orange Barrier', Lgcl),
create_door(player, 'PoD Arena North Drop Down', Lgcl),
create_door(player, 'PoD Arena Bonk Path', Lgcl),
create_door(player, 'PoD Arena Crystals E', Nrml).dir(Ea, 0x2a, Mid, High).pos(3),
create_door(player, 'PoD Arena Crystal Path', Lgcl),
create_door(player, 'PoD Arena Bridge Drop Down', Lgcl),
create_door(player, 'PoD Arena Ledge ES', Nrml).dir(Ea, 0x2a, Bot, High).pos(2),
create_door(player, 'PoD Sexy Statue W', Nrml).dir(We, 0x2b, Mid, High).pos(3),
create_door(player, 'PoD Sexy Statue NW', Nrml).dir(No, 0x2b, Left, High).trap(0x1).pos(2),
create_door(player, 'PoD Map Balcony Drop Down', Lgcl),
create_door(player, 'PoD Map Balcony WS', Nrml).dir(We, 0x2b, Bot, High).pos(1),
create_door(player, 'PoD Map Balcony South Stairs', StrS).dir(So, 0x2b, Left, High),
create_door(player, 'PoD Conveyor North Stairs', StrS).dir(No, 0x3b, Left, High),
create_door(player, 'PoD Conveyor SW', Nrml).dir(So, 0x3b, Left, High).pos(0),
create_door(player, 'PoD Mimics 1 NW', Nrml).dir(No, 0x4b, Left, High).trap(0x4).pos(0),
create_door(player, 'PoD Mimics 1 SW', Intr).dir(So, 0x4b, Left, High).pos(1),
create_door(player, 'PoD Jelly Hall NW', Intr).dir(No, 0x4b, Left, High).pos(1),
create_door(player, 'PoD Jelly Hall NE', Intr).dir(No, 0x4b, Right, High).pos(2),
create_door(player, 'PoD Warp Hint SE', Intr).dir(So, 0x4b, Right, High).pos(2),
create_door(player, 'PoD Warp Hint Warp', Warp),
create_door(player, 'PoD Falling Bridge SW', Nrml).dir(So, 0x1a, Left, High).small_key().pos(3),
create_door(player, 'PoD Falling Bridge WN', Nrml).dir(We, 0x1a, Top, High).small_key().pos(1),
create_door(player, 'PoD Falling Bridge EN', Intr).dir(Ea, 0x1a, Top, High).pos(4),
create_door(player, 'PoD Falling Bridge Path N', Lgcl),
create_door(player, 'PoD Falling Bridge Path S', Lgcl),
create_door(player, 'PoD Big Chest Balcony W', Nrml).dir(We, 0x1a, Mid, High).pos(2),
create_door(player, 'PoD Dark Maze EN', Nrml).dir(Ea, 0x19, Top, High).small_key().pos(1),
create_door(player, 'PoD Dark Maze E', Nrml).dir(Ea, 0x19, Mid, High).pos(0),
create_door(player, 'PoD Compass Room WN', Intr).dir(We, 0x1a, Top, High).pos(4),
create_door(player, 'PoD Compass Room SE', Intr).dir(So, 0x1a, Mid, High).small_key().pos(0),
create_door(player, 'PoD Harmless Hellway NE', Intr).dir(No, 0x1a, Right, High).small_key().pos(0),
create_door(player, 'PoD Harmless Hellway SE', Nrml).dir(So, 0x1a, Right, High).pos(5),
create_door(player, 'PoD Compass Room W Down Stairs', Sprl).dir(Dn, 0x1a, 0, HTH).ss(S, 0x12, 0x50, True, True),
create_door(player, 'PoD Compass Room E Down Stairs', Sprl).dir(Dn, 0x1a, 1, HTH).ss(S, 0x11, 0xb0, True, True),
create_door(player, 'PoD Dark Basement W Up Stairs', Sprl).dir(Up, 0x6a, 0, HTH).ss(S, 0x1b, 0x3c, True),
create_door(player, 'PoD Dark Basement E Up Stairs', Sprl).dir(Up, 0x6a, 1, HTH).ss(S, 0x1b, 0x9c, True),
create_door(player, 'PoD Dark Alley NE', Nrml).dir(No, 0x6a, Right, High).big_key().pos(0),
create_door(player, 'PoD Mimics 2 SW', Nrml).dir(So, 0x1b, Left, High).pos(1).kill(),
create_door(player, 'PoD Mimics 2 NW', Intr).dir(No, 0x1b, Left, High).pos(0),
create_door(player, 'PoD Bow Statue SW', Intr).dir(So, 0x1b, Left, High).pos(0),
create_door(player, 'PoD Bow Statue Down Ladder', Lddr).no_entrance(),
create_door(player, 'PoD Dark Pegs Up Ladder', Lddr),
create_door(player, 'PoD Dark Pegs WN', Intr).dir(We, 0x0b, Mid, High).small_key().pos(2),
create_door(player, 'PoD Lonely Turtle SW', Intr).dir(So, 0x0b, Mid, High).pos(0),
create_door(player, 'PoD Lonely Turtle EN', Intr).dir(Ea, 0x0b, Mid, High).small_key().pos(2),
create_door(player, 'PoD Turtle Party ES', Intr).dir(Ea, 0x0b, Mid, High).pos(1),
create_door(player, 'PoD Turtle Party NW', Intr).dir(No, 0x0b, Mid, High).pos(0),
create_door(player, 'PoD Callback WS', Intr).dir(We, 0x0b, Mid, High).pos(1),
create_door(player, 'PoD Callback Warp', Warp),
create_door(player, 'PoD Boss SE', Nrml).dir(So, 0x5a, Right, High).no_exit().trap(0x4).pos(0),
create_door(player, 'Swamp Lobby Moat', Lgcl),
create_door(player, 'Swamp Entrance Down Stairs', Sprl).dir(Dn, 0x28, 0, HTH).ss(A, 0x11, 0x80).small_key().pos(0),
create_door(player, 'Swamp Entrance Moat', Lgcl),
create_door(player, 'Swamp Pot Row Up Stairs', Sprl).dir(Up, 0x38, 0, HTH).ss(A, 0x1a, 0x6c, True),
create_door(player, 'Swamp Pot Row WN', Nrml).dir(We, 0x38, Top, High).pos(0),
create_door(player, 'Swamp Pot Row WS', Nrml).dir(We, 0x38, Bot, High).small_key().pos(1),
create_door(player, 'Swamp Map Ledge EN', Nrml).dir(Ea, 0x37, Top, High).pos(1),
create_door(player, 'Swamp Trench 1 Approach ES', Nrml).dir(Ea, 0x37, Bot, High).small_key().pos(3),
create_door(player, 'Swamp Trench 1 Approach Dry', Lgcl),
create_door(player, 'Swamp Trench 1 Approach Key', Lgcl),
create_door(player, 'Swamp Trench 1 Approach Swim Depart', Lgcl),
create_door(player, 'Swamp Trench 1 Nexus Approach', Lgcl),
create_door(player, 'Swamp Trench 1 Nexus Key', Lgcl),
create_door(player, 'Swamp Trench 1 Nexus N', Intr).dir(No, 0x37, Mid, Low).pos(5),
create_door(player, 'Swamp Trench 1 Alcove S', Intr).dir(So, 0x37, Mid, Low).pos(5),
create_door(player, 'Swamp Trench 1 Key Ledge Dry', Lgcl),
create_door(player, 'Swamp Trench 1 Key Approach', Lgcl),
create_door(player, 'Swamp Trench 1 Key Ledge Depart', Lgcl),
create_door(player, 'Swamp Trench 1 Key Ledge NW', Intr).dir(No, 0x37, Left, High).small_key().pos(2),
create_door(player, 'Swamp Trench 1 Departure Dry', Lgcl),
create_door(player, 'Swamp Trench 1 Departure Approach', Lgcl),
create_door(player, 'Swamp Trench 1 Departure Key', Lgcl),
create_door(player, 'Swamp Trench 1 Departure WS', Nrml).dir(We, 0x37, Bot, High).pos(4),
create_door(player, 'Swamp Hammer Switch SW', Intr).dir(So, 0x37, Left, High).small_key().pos(2),
create_door(player, 'Swamp Hammer Switch WN', Nrml).dir(We, 0x37, Top, High).pos(0),
create_door(player, 'Swamp Hub ES', Nrml).dir(Ea, 0x36, Bot, High).pos(4),
create_door(player, 'Swamp Hub S', Nrml).dir(So, 0x36, Mid, High).pos(5),
create_door(player, 'Swamp Hub WS', Nrml).dir(We, 0x36, Bot, High).pos(3),
create_door(player, 'Swamp Hub WN', Nrml).dir(We, 0x36, Top, High).small_key().pos(2),
create_door(player, 'Swamp Hub Hook Path', Lgcl),
create_door(player, 'Swamp Hub Dead Ledge EN', Nrml).dir(Ea, 0x36, Top, High).pos(0),
create_door(player, 'Swamp Hub North Ledge N', Nrml).dir(No, 0x36, Mid, High).small_key().pos(1),
create_door(player, 'Swamp Hub North Ledge Drop Down', Lgcl),
create_door(player, 'Swamp Donut Top N', Nrml).dir(No, 0x46, Mid, High).pos(0),
create_door(player, 'Swamp Donut Top SE', Intr).dir(So, 0x46, Right, High).pos(2),
create_door(player, 'Swamp Donut Bottom NE', Intr).dir(No, 0x46, Right, High).pos(2),
create_door(player, 'Swamp Donut Bottom NW', Intr).dir(No, 0x46, Left, High).pos(1),
create_door(player, 'Swamp Compass Donut SW', Intr).dir(So, 0x46, Left, High).pos(1),
create_door(player, 'Swamp Compass Donut Push Block', Lgcl),
create_door(player, 'Swamp Crystal Switch EN', Nrml).dir(Ea, 0x35, Top, High).small_key().pos(0),
create_door(player, 'Swamp Crystal Switch SE', Intr).dir(So, 0x35, Right, High).pos(3),
create_door(player, 'Swamp Shortcut NE', Intr).dir(No, 0x35, Right, High).pos(3),
create_door(player, 'Swamp Shortcut Blue Barrier', Lgcl),
create_door(player, 'Swamp Trench 2 Pots ES', Nrml).dir(Ea, 0x35, Bot, High).pos(4),
create_door(player, 'Swamp Trench 2 Pots Blue Barrier', Lgcl),
create_door(player, 'Swamp Trench 2 Pots Dry', Lgcl),
create_door(player, 'Swamp Trench 2 Pots Wet', Lgcl),
create_door(player, 'Swamp Trench 2 Blocks Pots', Lgcl),
create_door(player, 'Swamp Trench 2 Blocks N', Intr).dir(No, 0x35, Mid, Low).pos(5),
create_door(player, 'Swamp Trench 2 Alcove S', Intr).dir(So, 0x35, Mid, Low).pos(5),
create_door(player, 'Swamp Trench 2 Departure Wet', Lgcl),
create_door(player, 'Swamp Trench 2 Departure WS', Nrml).dir(We, 0x35, Bot, High).pos(2),
create_door(player, 'Swamp Big Key Ledge WN', Nrml).dir(We, 0x35, Top, High).pos(1),
create_door(player, 'Swamp West Shallows ES', Nrml).dir(Ea, 0x34, Bot, High).pos(1),
create_door(player, 'Swamp West Shallows Push Blocks', Lgcl),
create_door(player, 'Swamp West Block Path Up Stairs', Sprl).dir(Up, 0x34, 0, HTH).ss(Z, 0x1b, 0x6c),
create_door(player, 'Swamp West Block Path Drop Down', Lgcl),
create_door(player, 'Swamp West Ledge Drop Down', Lgcl),
create_door(player, 'Swamp West Ledge Hook Path', Lgcl),
create_door(player, 'Swamp Barrier Ledge Drop Down', Lgcl),
create_door(player, 'Swamp Barrier Ledge - Orange', Lgcl),
create_door(player, 'Swamp Barrier EN', Nrml).dir(Ea, 0x34, Top, High).pos(0),
create_door(player, 'Swamp Barrier - Orange', Lgcl),
create_door(player, 'Swamp Barrier Ledge Hook Path', Lgcl),
create_door(player, 'Swamp Attic Down Stairs', Sprl).dir(Dn, 0x54, 0, HTH).ss(Z, 0x12, 0x80).kill(),
create_door(player, 'Swamp Attic Left Pit', Hole),
create_door(player, 'Swamp Attic Right Pit', Hole),
create_door(player, 'Swamp Push Statue S', Nrml).dir(So, 0x26, Mid, High).small_key().pos(0),
create_door(player, 'Swamp Push Statue NW', Intr).dir(No, 0x26, Left, High).pos(1),
create_door(player, 'Swamp Push Statue NE', Intr).dir(No, 0x26, Right, High).pos(2),
create_door(player, 'Swamp Push Statue Down Stairs', Sprl).dir(Dn, 0x26, 2, HTH).ss(X, 0x12, 0xc0, False, True),
create_door(player, 'Swamp Shooters SW', Intr).dir(So, 0x26, Left, High).pos(1),
create_door(player, 'Swamp Shooters EN', Intr).dir(Ea, 0x26, Top, High).pos(3),
create_door(player, 'Swamp Left Elbow WN', Intr).dir(We, 0x26, Top, High).pos(3),
create_door(player, 'Swamp Left Elbow Down Stairs', Sprl).dir(Dn, 0x26, 0, HTH).ss(S, 0x11, 0x40, True, True),
create_door(player, 'Swamp Right Elbow SE', Intr).dir(So, 0x26, Right, High).pos(2),
create_door(player, 'Swamp Right Elbow Down Stairs', Sprl).dir(Dn, 0x26, 1, HTH).ss(S, 0x12, 0xb0, True, True),
create_door(player, 'Swamp Drain Left Up Stairs', Sprl).dir(Up, 0x76, 0, HTH).ss(S, 0x1b, 0x2c, True, True),
create_door(player, 'Swamp Drain WN', Intr).dir(We, 0x76, Top, Low).pos(0),
create_door(player, 'Swamp Drain Right Switch', Lgcl),
create_door(player, 'Swamp Drain Right Up Stairs', Sprl).dir(Up, 0x76, 1, HTH).ss(S, 0x1b, 0x9c, True, True).kill(),
create_door(player, 'Swamp Flooded Room Up Stairs', Sprl).dir(Up, 0x76, 2, HTH).ss(X, 0x1a, 0xac, True, True),
create_door(player, 'Swamp Flooded Room WS', Intr).dir(We, 0x76, Bot, Low).pos(1),
create_door(player, 'Swamp Flooded Spot Ladder', Lgcl),
create_door(player, 'Swamp Flooded Room Ladder', Lgcl),
create_door(player, 'Swamp Basement Shallows NW', Nrml).dir(No, 0x76, Left, High).toggler().pos(2),
create_door(player, 'Swamp Basement Shallows EN', Intr).dir(Ea, 0x76, Top, High).pos(0),
create_door(player, 'Swamp Basement Shallows ES', Intr).dir(Ea, 0x76, Bot, High).pos(1),
create_door(player, 'Swamp Waterfall Room SW', Nrml).dir(So, 0x66, Left, Low).toggler().pos(1),
create_door(player, 'Swamp Waterfall Room NW', Intr).dir(No, 0x66, Left, Low).pos(3),
create_door(player, 'Swamp Waterfall Room NE', Intr).dir(No, 0x66, Right, Low).pos(0),
create_door(player, 'Swamp Refill SW', Intr).dir(So, 0x66, Left, Low).pos(3),
create_door(player, 'Swamp Behind Waterfall SE', Intr).dir(So, 0x66, Right, Low).pos(0),
create_door(player, 'Swamp Behind Waterfall Up Stairs', Sprl).dir(Up, 0x66, 0, HTH).ss(S, 0x1a, 0x6c, True, True),
create_door(player, 'Swamp C Down Stairs', Sprl).dir(Dn, 0x16, 0, HTH).ss(S, 0x11, 0x80, True, True),
create_door(player, 'Swamp C SE', Intr).dir(So, 0x16, Right, High).pos(2),
create_door(player, 'Swamp Waterway NE', Intr).dir(No, 0x16, Right, High).pos(2),
create_door(player, 'Swamp Waterway N', Intr).dir(No, 0x16, Mid, High).pos(0),
create_door(player, 'Swamp Waterway NW', Intr).dir(No, 0x16, Left, High).small_key().pos(1),
create_door(player, 'Swamp I S', Intr).dir(So, 0x16, Mid, High).pos(0),
create_door(player, 'Swamp T SW', Intr).dir(So, 0x16, Left, High).small_key().pos(1),
create_door(player, 'Swamp T NW', Nrml).dir(No, 0x16, Left, High).pos(3),
create_door(player, 'Swamp Boss SW', Nrml).dir(So, 0x06, Left, High).no_exit().trap(0x4).pos(0),
create_door(player, 'Skull 1 Lobby WS', Nrml).dir(We, 0x58, Bot, High).small_key().pos(1),
create_door(player, 'Skull 1 Lobby ES', Intr).dir(Ea, 0x58, Bot, High).pos(5),
create_door(player, 'Skull Map Room WS', Intr).dir(We, 0x58, Bot, High).pos(5),
create_door(player, 'Skull Map Room SE', Nrml).dir(So, 0x58, Right, High).small_key().pos(2),
create_door(player, 'Skull Pot Circle WN', Intr).dir(We, 0x58, Top, High).pos(3),
create_door(player, 'Skull Pull Switch EN', Intr).dir(Ea, 0x58, Top, High).pos(3),
create_door(player, 'Skull Pot Circle Star Path', Lgcl),
create_door(player, 'Skull Pull Switch S', Intr).dir(So, 0x58, Left, High).pos(0),
create_door(player, 'Skull Big Chest N', Intr).dir(No, 0x58, Left, High).no_exit().pos(0),
create_door(player, 'Skull Big Chest Hookpath', Lgcl),
create_door(player, 'Skull Pinball NE', Nrml).dir(No, 0x68, Right, High).small_key().pos(1),
create_door(player, 'Skull Pinball WS', Nrml).dir(We, 0x68, Bot, High).no_exit().trap(0x4).pos(0),
create_door(player, 'Skull Compass Room NE', Nrml).dir(No, 0x67, Right, High).pos(0),
create_door(player, 'Skull Compass Room ES', Nrml).dir(Ea, 0x67, Bot, High).pos(2),
create_door(player, 'Skull Left Drop ES', Intr).dir(Ea, 0x67, Bot, High).pos(1),
create_door(player, 'Skull Compass Room WS', Intr).dir(We, 0x67, Bot, High).pos(1),
create_door(player, 'Skull Pot Prison ES', Nrml).dir(Ea, 0x57, Bot, High).small_key().pos(2),
create_door(player, 'Skull Pot Prison SE', Nrml).dir(So, 0x57, Right, High).pos(5),
create_door(player, 'Skull 2 East Lobby WS', Nrml).dir(We, 0x57, Bot, High).pos(4),
create_door(player, 'Skull 2 East Lobby NW', Intr).dir(No, 0x57, Left, High).pos(1),
create_door(player, 'Skull Big Key SW', Intr).dir(So, 0x57, Left, High).pos(1),
create_door(player, 'Skull Big Key WN', Intr).dir(We, 0x57, Top, High).pos(0),
create_door(player, 'Skull Lone Pot EN', Intr).dir(Ea, 0x57, Top, High).pos(0),
create_door(player, 'Skull Small Hall ES', Nrml).dir(Ea, 0x56, Bot, High).pos(3),
create_door(player, 'Skull Small Hall WS', Intr).dir(We, 0x56, Bot, High).pos(2),
create_door(player, 'Skull 2 West Lobby ES', Intr).dir(Ea, 0x56, Bot, High).pos(2),
create_door(player, 'Skull 2 West Lobby NW', Intr).dir(No, 0x56, Left, High).small_key().pos(0),
create_door(player, 'Skull X Room SW', Intr).dir(So, 0x56, Left, High).small_key().pos(0),
create_door(player, 'Skull Back Drop Star Path', Lgcl),
create_door(player, 'Skull 3 Lobby NW', Nrml).dir(No, 0x59, Left, High).small_key().pos(0),
create_door(player, 'Skull 3 Lobby EN', Intr).dir(Ea, 0x59, Top, High).pos(2),
create_door(player, 'Skull East Bridge WN', Intr).dir(We, 0x59, Top, High).pos(2),
create_door(player, 'Skull East Bridge WS', Intr).dir(We, 0x59, Bot, High).pos(3),
create_door(player, 'Skull West Bridge Nook ES', Intr).dir(Ea, 0x59, Bot, High).pos(3),
create_door(player, 'Skull Star Pits SW', Nrml).dir(So, 0x49, Left, High).small_key().pos(2),
create_door(player, 'Skull Star Pits ES', Intr).dir(Ea, 0x49, Bot, High).pos(3),
create_door(player, 'Skull Torch Room WS', Intr).dir(We, 0x49, Bot, High).pos(3),
create_door(player, 'Skull Torch Room WN', Intr).dir(We, 0x49, Top, High).pos(1),
create_door(player, 'Skull Vines EN', Intr).dir(Ea, 0x49, Top, High).pos(1),
create_door(player, 'Skull Vines NW', Nrml).dir(No, 0x49, Left, High).pos(0),
create_door(player, 'Skull Spike Corner SW', Nrml).dir(So, 0x39, Left, High).no_exit().trap(0x4).pos(0),
create_door(player, 'Skull Spike Corner ES', Intr).dir(Ea, 0x39, Bot, High).small_key().pos(1),
create_door(player, 'Skull Final Drop WS', Intr).dir(We, 0x39, Bot, High).small_key().pos(1),
create_door(player, 'Skull Final Drop Hole', Hole),
create_door(player, 'Thieves Lobby N Edge', Open).dir(No, 0xdb, None, Low).edge(7, A, 0x10),
create_door(player, 'Thieves Lobby NE Edge', Open).dir(No, 0xdb, None, Low).edge(8, S, 0x18),
create_door(player, 'Thieves Lobby E', Nrml).dir(Ea, 0xdb, Mid, High).no_exit().trap(0x4).pos(0),
create_door(player, 'Thieves Big Chest Nook ES Edge', Open).dir(Ea, 0xdb, None, Low).edge(8, X, 0x50),
create_door(player, 'Thieves Ambush S Edge', Open).dir(So, 0xcb, None, Low).edge(7, Z, 0x10),
create_door(player, 'Thieves Ambush SE Edge', Open).dir(So, 0xcb, None, Low).edge(8, X, 0x18),
create_door(player, 'Thieves Ambush ES Edge', Open).dir(Ea, 0xcb, None, Low).edge(6, X, 0x50),
create_door(player, 'Thieves Ambush EN Edge', Open).dir(Ea, 0xcb, None, Low).edge(7, S, 0x50),
create_door(player, 'Thieves Ambush E', Nrml).dir(Ea, 0xcb, Mid, High).pos(0),
create_door(player, 'Thieves BK Corner WN Edge', Open).dir(We, 0xcc, None, Low).edge(7, A, 0x50),
create_door(player, 'Thieves BK Corner WS Edge', Open).dir(We, 0xcc, None, Low).edge(6, Z, 0x50),
create_door(player, 'Thieves BK Corner S Edge', Open).dir(So, 0xcc, None, Low).edge(10, Z, 0x10),
create_door(player, 'Thieves BK Corner SW Edge', Open).dir(So, 0xcc, None, Low).edge(9, Z, 0x18),
create_door(player, 'Thieves Rail Ledge Drop Down', Lgcl),
create_door(player, 'Thieves Rail Ledge W', Nrml).dir(We, 0xcc, Mid, High).pos(2),
create_door(player, 'Thieves Rail Ledge NW', Nrml).dir(No, 0xcc, Left, High).pos(1),
create_door(player, 'Thieves BK Corner NE', Nrml).dir(No, 0xcc, Right, High).big_key().pos(0),
create_door(player, 'Thieves Compass Room NW Edge', Open).dir(No, 0xdc, None, Low).edge(9, A, 0x18),
create_door(player, 'Thieves Compass Room N Edge', Open).dir(No, 0xdc, None, Low).edge(10, A, 0x10),
create_door(player, 'Thieves Compass Room WS Edge', Open).dir(We, 0xdc, None, Low).edge(8, Z, 0x50),
create_door(player, 'Thieves Compass Room W', Nrml).dir(We, 0xdc, Mid, High).pos(0),
create_door(player, 'Thieves Hallway SE', Nrml).dir(So, 0xbc, Right, High).small_key().pos(1),
create_door(player, 'Thieves Hallway NE', Nrml).dir(No, 0xbc, Right, High).pos(7),
create_door(player, 'Thieves Pot Alcove Mid WS', Nrml).dir(We, 0xbc, Bot, High).pos(5),
create_door(player, 'Thieves Pot Alcove Bottom SW', Nrml).dir(So, 0xbc, Left, High).pos(3),
create_door(player, 'Thieves Conveyor Maze WN', Nrml).dir(We, 0xbc, Top, High).pos(4),
create_door(player, 'Thieves Hallway WS', Intr).dir(We, 0xbc, Bot, High).small_key().pos(0),
create_door(player, 'Thieves Pot Alcove Mid ES', Intr).dir(Ea, 0xbc, Bot, High).small_key().pos(0),
create_door(player, 'Thieves Conveyor Maze SW', Intr).dir(So, 0xbc, Left, High).pos(6),
create_door(player, 'Thieves Pot Alcove Top NW', Intr).dir(No, 0xbc, Left, High).pos(6),
create_door(player, 'Thieves Conveyor Maze EN', Intr).dir(Ea, 0xbc, Top, High).pos(2),
create_door(player, 'Thieves Hallway WN', Intr).dir(We, 0xbc, Top, High).no_exit().pos(2),
create_door(player, 'Thieves Conveyor Maze Down Stairs', Sprl).dir(Dn, 0xbc, 0, HTH).ss(A, 0x11, 0x80, True, True),
create_door(player, 'Thieves Boss SE', Nrml).dir(So, 0xac, Right, High).no_exit().trap(0x4).pos(0),
create_door(player, 'Thieves Spike Track ES', Nrml).dir(Ea, 0xbb, Bot, High).pos(5),
create_door(player, 'Thieves Hellway NW', Nrml).dir(No, 0xbb, Left, High).pos(0),
create_door(player, 'Thieves Triple Bypass EN', Nrml).dir(Ea, 0xbb, Top, High).pos(4),
create_door(player, 'Thieves Hellway Orange Barrier', Lgcl),
create_door(player, 'Thieves Hellway Crystal Orange Barrier', Lgcl),
create_door(player, 'Thieves Hellway Blue Barrier', Lgcl),
create_door(player, 'Thieves Hellway Crystal Blue Barrier', Lgcl),
create_door(player, 'Thieves Spike Track WS', Intr).dir(We, 0xbb, Bot, High).pos(2),
create_door(player, 'Thieves Hellway Crystal ES', Intr).dir(Ea, 0xbb, Bot, High).pos(2),
create_door(player, 'Thieves Spike Track NE', Intr).dir(No, 0xbb, Right, High).pos(3),
create_door(player, 'Thieves Triple Bypass SE', Intr).dir(So, 0xbb, Right, High).pos(3),
create_door(player, 'Thieves Hellway Crystal EN', Intr).dir(Ea, 0xbb, Top, High).pos(1),
create_door(player, 'Thieves Triple Bypass WN', Intr).dir(We, 0xbb, Top, High).pos(1),
create_door(player, 'Thieves Spike Switch SW', Nrml).dir(So, 0xab, Left, High).pos(1),
create_door(player, 'Thieves Spike Switch Up Stairs', Sprl).dir(Up, 0xab, 0, HTH).ss(Z, 0x1a, 0x6c, True, True).small_key().pos(0),
create_door(player, 'Thieves Attic Down Stairs', Sprl).dir(Dn, 0x64, 0, HTH).ss(Z, 0x11, 0x80, True, True),
create_door(player, 'Thieves Attic ES', Intr).dir(Ea, 0x64, Bot, High).pos(0),
create_door(player, 'Thieves Attic Orange Barrier', Lgcl),
create_door(player, 'Thieves Attic Hint Orange Barrier', Lgcl),
create_door(player, 'Thieves Cricket Hall Left WS', Intr).dir(We, 0x64, Bot, High).pos(0),
create_door(player, 'Thieves Cricket Hall Left Edge', Open).dir(Ea, 0x64, None, High).edge(0, X, 0x30),
create_door(player, 'Thieves Cricket Hall Right Edge', Open).dir(We, 0x65, None, High).edge(0, Z, 0x30),
create_door(player, 'Thieves Cricket Hall Right ES', Intr).dir(Ea, 0x65, Bot, High).pos(0),
create_door(player, 'Thieves Attic Window WS', Intr).dir(We, 0x65, Bot, High).pos(0),
create_door(player, 'Thieves Basement Block Up Stairs', Sprl).dir(Up, 0x45, 0, HTH).ss(A, 0x1a, 0x6c, True, True),
create_door(player, 'Thieves Basement Block WN', Nrml).dir(We, 0x45, Top, High).trap(0x4).pos(0),
create_door(player, 'Thieves Basement Block Path', Lgcl),
create_door(player, 'Thieves Blocked Entry Path', Lgcl),
create_door(player, 'Thieves Lonely Zazak WS', Nrml).dir(We, 0x45, Bot, High).pos(2),
create_door(player, 'Thieves Blocked Entry SW', Intr).dir(So, 0x45, Left, High).pos(1),
create_door(player, 'Thieves Lonely Zazak NW', Intr).dir(No, 0x45, Left, High).pos(1),
create_door(player, 'Thieves Lonely Zazak ES', Intr).dir(Ea, 0x45, Right, High).pos(3),
create_door(player, 'Thieves Blind\'s Cell WS', Intr).dir(We, 0x45, Right, High).pos(3),
create_door(player, 'Thieves Conveyor Bridge EN', Nrml).dir(Ea, 0x44, Top, High).pos(2),
create_door(player, 'Thieves Conveyor Bridge ES', Nrml).dir(Ea, 0x44, Bot, High).pos(3),
create_door(player, 'Thieves Conveyor Bridge Block Path', Lgcl),
create_door(player, 'Thieves Conveyor Block Path', Lgcl),
create_door(player, 'Thieves Conveyor Bridge WS', Intr).dir(We, 0x44, Bot, High).small_key().pos(1),
create_door(player, 'Thieves Big Chest Room ES', Intr).dir(Ea, 0x44, Bot, High).small_key().pos(1),
create_door(player, 'Thieves Conveyor Block WN', Intr).dir(We, 0x44, Top, High).pos(0),
create_door(player, 'Thieves Trap EN', Intr).dir(Ea, 0x44, Left, Top).pos(0),
create_door(player, 'Ice Lobby WS', Intr).dir(We, 0x0e, Bot, High).pos(1),
create_door(player, 'Ice Jelly Key ES', Intr).dir(Ea, 0x0e, Bot, High).pos(1),
create_door(player, 'Ice Jelly Key Down Stairs', Sprl).dir(Dn, 0x0e, 0, HTH).ss(Z, 0x11, 0x80, True, True).small_key().pos(0),
create_door(player, 'Ice Floor Switch Up Stairs', Sprl).dir(Up, 0x1e, 0, HTH).ss(Z, 0x1a, 0x6c, True, True),
create_door(player, 'Ice Floor Switch ES', Intr).dir(Ea, 0x1e, Bot, High).pos(1),
create_door(player, 'Ice Cross Left WS', Intr).dir(We, 0x1e, Bot, High).pos(1),
create_door(player, 'Ice Cross Top NE', Intr).dir(No, 0x1e, Right, High).pos(2),
create_door(player, 'Ice Bomb Drop SE', Intr).dir(So, 0x1e, Right, High).pos(2),
create_door(player, 'Ice Cross Left Push Block', Lgcl), # dynamic
create_door(player, 'Ice Cross Bottom Push Block Left', Lgcl),
create_door(player, 'Ice Cross Bottom Push Block Right', Lgcl), # dynamic
create_door(player, 'Ice Cross Right Push Block Top', Lgcl),
create_door(player, 'Ice Cross Right Push Block Bottom', Lgcl), # dynamic
create_door(player, 'Ice Cross Top Push Block Bottom', Lgcl), # dynamic
create_door(player, 'Ice Cross Top Push Block Right', Lgcl), # dynamic
create_door(player, 'Ice Cross Bottom SE', Nrml).dir(So, 0x1e, Right, High).pos(3),
create_door(player, 'Ice Cross Right ES', Nrml).dir(Ea, 0x1e, Bot, High).trap(0x4).pos(0),
create_door(player, 'Ice Bomb Drop Hole', Hole),
create_door(player, 'Ice Compass Room NE', Nrml).dir(No, 0x2e, Right, High).pos(0),
create_door(player, 'Ice Pengator Switch WS', Nrml).dir(We, 0x1f, Bot, High).trap(0x4).pos(0),
create_door(player, 'Ice Pengator Switch ES', Intr).dir(Ea, 0x1f, Bot, High).pos(1),
create_door(player, 'Ice Dead End WS', Intr).dir(We, 0x1f, Bot, High).pos(1),
create_door(player, 'Ice Big Key Push Block', Lgcl),
create_door(player, 'Ice Big Key Down Ladder', Lddr),
create_door(player, 'Ice Stalfos Hint SE', Intr).dir(So, 0x3e, Right, High).pos(0),
create_door(player, 'Ice Conveyor NE', Intr).dir(No, 0x3e, Right, High).no_exit().pos(0),
create_door(player, 'Ice Conveyor SW', Nrml).dir(So, 0x3e, Left, High).small_key().pos(1),
create_door(player, 'Ice Bomb Jump NW', Nrml).dir(No, 0x4e, Left, High).small_key().pos(1),
create_door(player, 'Ice Bomb Jump Ledge Orange Barrier', Lgcl),
create_door(player, 'Ice Bomb Jump Catwalk Orange Barrier', Lgcl),
create_door(player, 'Ice Bomb Jump EN', Intr).dir(Ea, 0x4e, Top, High).pos(0),
create_door(player, 'Ice Narrow Corridor WN', Intr).dir(We, 0x4e, Top, High).pos(0),
create_door(player, 'Ice Narrow Corridor Down Stairs', Sprl).dir(Dn, 0x4e, 0, HTH).ss(S, 0x52, 0xc0, True, True),
create_door(player, 'Ice Pengator Trap Up Stairs', Sprl).dir(Up, 0x6e, 0, HTH).ss(S, 0x5a, 0xac, True, True),
create_door(player, 'Ice Pengator Trap NE', Nrml).dir(No, 0x6e, Right, High).trap(0x4).pos(0),
create_door(player, 'Ice Spike Cross SE', Nrml).dir(So, 0x5e, Right, High).pos(2),
create_door(player, 'Ice Spike Cross ES', Nrml).dir(Ea, 0x5e, Bot, High).small_key().pos(0),
create_door(player, 'Ice Spike Cross WS', Intr).dir(We, 0x5e, Bot, High).pos(3),
create_door(player, 'Ice Firebar ES', Intr).dir(Ea, 0x5e, Bot, High).pos(3),
create_door(player, 'Ice Firebar Down Ladder', Lddr),
create_door(player, 'Ice Spike Cross NE', Intr).dir(No, 0x5e, Right, High).pos(1),
create_door(player, 'Ice Falling Square SE', Intr).dir(So, 0x5e, Right, High).no_exit().pos(1),
create_door(player, 'Ice Falling Square Hole', Hole),
create_door(player, 'Ice Spike Room WS', Nrml).dir(We, 0x5f, Bot, High).small_key().pos(0),
create_door(player, 'Ice Spike Room Down Stairs', Sprl).dir(Dn, 0x5f, 3, HTH).ss(Z, 0x11, 0x48, True, True),
create_door(player, 'Ice Spike Room Up Stairs', Sprl).dir(Up, 0x5f, 4, HTH).ss(Z, 0x1a, 0xa4, True, True),
create_door(player, 'Ice Hammer Block Down Stairs', Sprl).dir(Dn, 0x3f, 0, HTH).ss(Z, 0x11, 0xb8, True, True).kill(),
create_door(player, 'Ice Hammer Block ES', Intr).dir(Ea, 0x3f, Bot, High).pos(0),
create_door(player, 'Ice Tongue Pull WS', Intr).dir(We, 0x3f, Bot, High).pos(0),
create_door(player, 'Ice Tongue Pull Up Ladder', Lddr),
create_door(player, 'Ice Freezors Up Ladder', Lddr),
create_door(player, 'Ice Freezors Hole', Hole),
create_door(player, 'Ice Freezors Bomb Hole', Hole), # combine these two? -- they have to lead to the same spot
create_door(player, 'Ice Freezors Ledge Hole', Hole),
create_door(player, 'Ice Freezors Ledge ES', Intr).dir(Ea, 0x7e, Bot, High).pos(2),
create_door(player, 'Ice Tall Hint WS', Intr).dir(We, 0x7e, Bot, High).pos(1),
create_door(player, 'Ice Tall Hint EN', Nrml).dir(Ea, 0x7e, Top, High).pos(2),
create_door(player, 'Ice Tall Hint SE', Nrml).dir(So, 0x7e, Right, High).small_key().pos(0),
create_door(player, 'Ice Hookshot Ledge WN', Nrml).dir(We, 0x7f, Top, High).no_exit().trap(0x4).pos(0).kill(),
create_door(player, 'Ice Hookshot Ledge Path', Lgcl),
create_door(player, 'Ice Hookshot Balcony Path', Lgcl),
create_door(player, 'Ice Hookshot Balcony SW', Intr).dir(So, 0x7f, Left, High).pos(1),
create_door(player, 'Ice Spikeball NW', Intr).dir(No, 0x7f, Left, High).pos(1),
create_door(player, 'Ice Spikeball Up Stairs', Sprl).dir(Up, 0x7f, 0, HTH).ss(Z, 0x1a, 0x34, True, True),
create_door(player, 'Ice Lonely Freezor NE', Nrml).dir(No, 0x8e, Right, High).small_key().pos(0),
create_door(player, 'Ice Lonely Freezor Down Stairs', Sprl).dir(Dn, 0x8e, 0, HTH).ss(S, 0x11, 0x50, True, True),
create_door(player, 'Iced T EN', Nrml).dir(Ea, 0xae, Top, High).pos(0),
create_door(player, 'Iced T Up Stairs', Sprl).dir(Up, 0xae, 0, HTH).ss(S, 0x1a, 0x3c, True, True),
create_door(player, 'Ice Catwalk WN', Nrml).dir(We, 0xaf, Top, High).pos(1),
create_door(player, 'Ice Catwalk NW', Nrml).dir(No, 0xaf, Left, High).pos(0),
create_door(player, 'Ice Many Pots SW', Nrml).dir(So, 0x9f, Left, High).trap(0x2).pos(1),
create_door(player, 'Ice Many Pots WS', Nrml).dir(We, 0x9f, Bot, High).trap(0x4).pos(0),
create_door(player, 'Ice Crystal Right ES', Nrml).dir(Ea, 0x9e, Bot, High).pos(3),
create_door(player, 'Ice Crystal Right Orange Barrier', Lgcl),
create_door(player, 'Ice Crystal Right Blue Hole', Hole), # combine holes again??
create_door(player, 'Ice Crystal Left Orange Barrier', Lgcl),
create_door(player, 'Ice Crystal Left Blue Barrier', Lgcl),
create_door(player, 'Ice Crystal Block Exit', Lgcl),
create_door(player, 'Ice Crystal Block Hole', Hole),
create_door(player, 'Ice Crystal Left WS', Intr).dir(We, 0x9e, Bot, High).pos(2),
create_door(player, 'Ice Big Chest View ES', Intr).dir(Ea, 0x9e, Bot, High).pos(2),
create_door(player, 'Ice Big Chest Landing Push Blocks', Lgcl),
create_door(player, 'Ice Crystal Right NE', Intr).dir(No, 0x9e, Right, High).big_key().pos(1),
create_door(player, 'Ice Backwards Room SE', Intr).dir(So, 0x9e, Right, High).pos(1),
create_door(player, 'Ice Backwards Room Down Stairs', Sprl).dir(Dn, 0x9e, 0, HTH).ss(S, 0x11, 0x80, True, True).small_key().pos(0),
create_door(player, 'Ice Backwards Room Hole', Hole),
create_door(player, 'Ice Anti-Fairy Up Stairs', Sprl).dir(Up, 0xbe, 0, HTH).ss(S, 0x1a, 0x6c, True, True),
create_door(player, 'Ice Anti-Fairy SE', Intr).dir(So, 0xbe, Right, High).pos(2),
create_door(player, 'Ice Switch Room NE', Intr).dir(No, 0xbe, Right, High).pos(2),
create_door(player, 'Ice Switch Room ES', Nrml).dir(Ea, 0xbe, Bot, High).small_key().pos(1),
create_door(player, 'Ice Switch Room SE', Nrml).dir(So, 0xbe, Right, High).trap(0x4).pos(0),
create_door(player, 'Ice Refill WS', Nrml).dir(We, 0xbf, Bot, High).small_key().pos(0),
create_door(player, 'Ice Fairy Warp', Warp),
create_door(player, 'Ice Antechamber NE', Nrml).dir(No, 0xce, Right, High).trap(0x4).pos(0),
create_door(player, 'Ice Antechamber Hole', Hole),
create_door(player, 'Mire Lobby Gap', Lgcl),
create_door(player, 'Mire Post-Gap Gap', Lgcl),
create_door(player, 'Mire Post-Gap Down Stairs', Sprl).dir(Dn, 0x98, 0, HTH).ss(X, 0x11, 0x90, False, True),
create_door(player, 'Mire 2 Up Stairs', Sprl).dir(Up, 0xd2, 0, HTH).ss(X, 0x1a, 0x7c, False, True),
create_door(player, 'Mire 2 NE', Nrml).dir(No, 0xd2, Right, High).trap(0x4).pos(0),
create_door(player, 'Mire Hub SE', Nrml).dir(So, 0xc2, Right, High).pos(5),
create_door(player, 'Mire Hub ES', Nrml).dir(Ea, 0xc2, Bot, High).pos(6),
create_door(player, 'Mire Hub E', Nrml).dir(Ea, 0xc2, Mid, High).pos(4),
create_door(player, 'Mire Hub NE', Nrml).dir(No, 0xc2, Right, High).pos(7),
create_door(player, 'Mire Hub WN', Nrml).dir(We, 0xc2, Top, High).pos(3),
create_door(player, 'Mire Hub WS', Nrml).dir(We, 0xc2, Bot, High).small_key().pos(1),
create_door(player, 'Mire Hub Upper Blue Barrier', Lgcl),
create_door(player, 'Mire Hub Lower Blue Barrier', Lgcl),
create_door(player, 'Mire Hub Right Blue Barrier', Lgcl),
create_door(player, 'Mire Hub Top Blue Barrier', Lgcl),
create_door(player, 'Mire Hub Switch Blue Barrier N', Lgcl),
create_door(player, 'Mire Hub Switch Blue Barrier S', Lgcl),
create_door(player, 'Mire Hub Right EN', Nrml).dir(Ea, 0xc2, Top, High).small_key().pos(0),
create_door(player, 'Mire Hub Top NW', Nrml).dir(No, 0xc2, Left, High).pos(2),
create_door(player, 'Mire Lone Shooter WS', Nrml).dir(We, 0xc3, Bot, High).pos(6),
create_door(player, 'Mire Lone Shooter ES', Intr).dir(Ea, 0xc3, Bot, High).pos(3),
create_door(player, 'Mire Falling Bridge WS', Intr).dir(We, 0xc3, Bot, High).no_exit().pos(3),
create_door(player, 'Mire Falling Bridge W', Intr).dir(We, 0xc3, Mid, High).pos(2),
create_door(player, 'Mire Failure Bridge E', Intr).dir(Ea, 0xc3, Mid, High).no_exit().pos(2),
create_door(player, 'Mire Failure Bridge W', Nrml).dir(We, 0xc3, Mid, High).pos(5),
create_door(player, 'Mire Falling Bridge WN', Intr).dir(We, 0xc3, Top, High).pos(1),
create_door(player, 'Mire Map Spike Side EN', Intr).dir(Ea, 0xc3, Top, High).no_exit().pos(1),
create_door(player, 'Mire Map Spot WN', Nrml).dir(We, 0xc3, Top, High).small_key().pos(0),
create_door(player, 'Mire Crystal Dead End NW', Nrml).dir(No, 0xc3, Left, High).pos(4),
create_door(player, 'Mire Map Spike Side Drop Down', Lgcl),
create_door(player, 'Mire Map Spike Side Blue Barrier', Lgcl),
create_door(player, 'Mire Map Spot Blue Barrier', Lgcl),
create_door(player, 'Mire Crystal Dead End Left Barrier', Lgcl),
create_door(player, 'Mire Crystal Dead End Right Barrier', Lgcl),
create_door(player, 'Mire Hidden Shooters SE', Nrml).dir(So, 0xb2, Right, High).pos(6),
create_door(player, 'Mire Hidden Shooters ES', Nrml).dir(Ea, 0xb2, Bot, High).pos(7),
create_door(player, 'Mire Hidden Shooters WS', Intr).dir(We, 0xb2, Bot, High).pos(1),
create_door(player, 'Mire Cross ES', Intr).dir(Ea, 0xb2, Bot, High).pos(1),
create_door(player, 'Mire Hidden Shooters Block Path S', Lgcl),
create_door(player, 'Mire Hidden Shooters Block Path N', Lgcl),
create_door(player, 'Mire Hidden Shooters NE', Intr).dir(No, 0xb2, Right, High).pos(2),
create_door(player, 'Mire Minibridge SE', Intr).dir(So, 0xb2, Right, High).pos(2),
create_door(player, 'Mire Cross SW', Nrml).dir(So, 0xb2, Left, High).pos(5),
create_door(player, 'Mire Minibridge NE', Nrml).dir(No, 0xb2, Right, High).pos(4),
create_door(player, 'Mire BK Door Room EN', Nrml).dir(Ea, 0xb2, Top, Low).pos(3),
create_door(player, 'Mire BK Door Room N', Nrml).dir(No, 0xb2, Mid, High).big_key().pos(0),
create_door(player, 'Mire Spikes WS', Nrml).dir(We, 0xb3, Bot, High).pos(3),
create_door(player, 'Mire Spikes SW', Nrml).dir(So, 0xb3, Left, High).pos(4),
create_door(player, 'Mire Spikes NW', Intr).dir(No, 0xb3, Left, High).small_key().pos(0),
create_door(player, 'Mire Ledgehop SW', Intr).dir(So, 0xb3, Left, High).small_key().pos(0),
create_door(player, 'Mire Ledgehop WN', Nrml).dir(We, 0xb3, Top, Low).pos(1),
create_door(player, 'Mire Ledgehop NW', Nrml).dir(No, 0xb3, Left, High).pos(2),
create_door(player, 'Mire Bent Bridge SW', Nrml).dir(So, 0xa3, Left, High).pos(1),
create_door(player, 'Mire Bent Bridge W', Nrml).dir(We, 0xa3, Mid, High).pos(0),
create_door(player, 'Mire Over Bridge E', Nrml).dir(Ea, 0xa2, Mid, High).pos(2),
create_door(player, 'Mire Over Bridge W', Nrml).dir(We, 0xa2, Mid, High).pos(1),
create_door(player, 'Mire Right Bridge SE', Nrml).dir(So, 0xa2, Right, High).pos(3),
create_door(player, 'Mire Left Bridge S', Nrml).dir(So, 0xa2, Mid, High).small_key().pos(0),
create_door(player, 'Mire Left Bridge Hook Path', Lgcl),
create_door(player, 'Mire Left Bridge Down Stairs', Sprl).dir(Dn, 0xa2, 0, HTL).ss(A, 0x12, 0x00),
create_door(player, 'Mire Fishbone E', Nrml).dir(Ea, 0xa1, Mid, High).pos(1),
create_door(player, 'Mire Fishbone Blue Barrier', Lgcl),
create_door(player, 'Mire South Fish Blue Barrier', Lgcl),
create_door(player, 'Mire Fishbone SE', Nrml).dir(So, 0xa1, Right, High).small_key().pos(0),
create_door(player, 'Mire Spike Barrier NE', Nrml).dir(No, 0xb1, Right, High).small_key().pos(1),
create_door(player, 'Mire Spike Barrier SE', Nrml).dir(So, 0xb1, Right, High).pos(2),
create_door(player, 'Mire Spike Barrier ES', Intr).dir(Ea, 0xb1, Bot, High).pos(3),
create_door(player, 'Mire Square Rail WS', Intr).dir(We, 0xb1, Bot, High).pos(3),
create_door(player, 'Mire Square Rail NW', Intr).dir(No, 0xb1, Left, High).big_key().pos(0),
create_door(player, 'Mire Lone Warp SW', Intr).dir(So, 0xb1, Left, High).pos(0),
create_door(player, 'Mire Lone Warp Warp', Warp),
create_door(player, 'Mire Wizzrobe Bypass EN', Nrml).dir(Ea, 0xc1, Top, High).pos(5),
create_door(player, 'Mire Wizzrobe Bypass NE', Nrml).dir(No, 0xc1, Right, High).pos(6),
create_door(player, 'Mire Conveyor Crystal ES', Nrml).dir(Ea, 0xc1, Bot, High).small_key().pos(1),
create_door(player, 'Mire Conveyor Crystal SE', Nrml).dir(So, 0xc1, Right, High).pos(7),
create_door(player, 'Mire Conveyor Crystal WS', Intr).dir(We, 0xc1, Bot, High).small_key().pos(0),
create_door(player, 'Mire Tile Room ES', Intr).dir(Ea, 0xc1, Bot, High).small_key().pos(0),
create_door(player, 'Mire Tile Room SW', Nrml).dir(So, 0xc1, Left, High).pos(4),
create_door(player, 'Mire Tile Room NW', Intr).dir(No, 0xc1, Left, High).pos(3),
create_door(player, 'Mire Compass Room SW', Intr).dir(So, 0xc1, Left, High).pos(3),
create_door(player, 'Mire Compass Room EN', Intr).dir(Ea, 0xc1, Top, High).pos(2),
create_door(player, 'Mire Wizzrobe Bypass WN', Intr).dir(We, 0xc1, Top, High).no_exit().pos(2),
create_door(player, 'Mire Compass Blue Barrier', Lgcl),
create_door(player, 'Mire Compass Chest Exit', Lgcl),
create_door(player, 'Mire Neglected Room NE', Nrml).dir(No, 0xd1, Right, High).pos(2),
create_door(player, 'Mire Conveyor Barrier NW', Nrml).dir(No, 0xd1, Left, High).pos(1),
create_door(player, 'Mire Conveyor Barrier Up Stairs', Sprl).dir(Up, 0xd1, 0, HTH).ss(A, 0x1a, 0x9c, True),
create_door(player, 'Mire Neglected Room SE', Intr).dir(So, 0xd1, Right, High).pos(3),
create_door(player, 'Mire Chest View NE', Intr).dir(No, 0xd1, Right, High).pos(3),
create_door(player, 'Mire BK Chest Ledge WS', Intr).dir(We, 0xd1, Bot, High).pos(0),
create_door(player, 'Mire Warping Pool ES', Intr).dir(Ea, 0xd1, Bot, High).no_exit().pos(0),
create_door(player, 'Mire Warping Pool Warp', Warp),
create_door(player, 'Mire Torches Top Down Stairs', Sprl).dir(Dn, 0x97, 0, HTH).ss(A, 0x11, 0xb0, True).kill(),
create_door(player, 'Mire Torches Top SW', Intr).dir(So, 0x97, Left, High).pos(1),
create_door(player, 'Mire Torches Bottom Holes', Hole),
create_door(player, 'Mire Torches Bottom NW', Intr).dir(No, 0x97, Left, High).pos(1),
create_door(player, 'Mire Torches Bottom WS', Intr).dir(We, 0x97, Bot, High).pos(0),
create_door(player, 'Mire Torches Top Holes', Hole),
create_door(player, 'Mire Attic Hint ES', Intr).dir(Ea, 0x97, Bot, High).pos(0),
create_door(player, 'Mire Attic Hint Hole', Hole),
create_door(player, 'Mire Dark Shooters Up Stairs', Sprl).dir(Up, 0x93, 0, LTH).ss(A, 0x32, 0xec),
create_door(player, 'Mire Dark Shooters SW', Intr).dir(So, 0x93, Left, High).pos(0),
create_door(player, 'Mire Block X NW', Intr).dir(No, 0x93, Left, High).pos(0),
create_door(player, 'Mire Dark Shooters SE', Intr).dir(So, 0x93, Right, High).small_key().pos(1),
create_door(player, 'Mire Key Rupees NE', Intr).dir(No, 0x93, Right, High).small_key().pos(1),
create_door(player, 'Mire Block X WS', Nrml).dir(We, 0x93, Bot, High).pos(2),
create_door(player, 'Mire Tall Dark and Roomy ES', Nrml).dir(Ea, 0x92, Bot, High).pos(4),
create_door(player, 'Mire Tall Dark and Roomy WN', Intr).dir(We, 0x92, Top, High).pos(0),
create_door(player, 'Mire Shooter Rupees EN', Intr).dir(Ea, 0x92, Top, High).pos(0),
create_door(player, 'Mire Tall Dark and Roomy WS', Intr).dir(We, 0x92, Bot, High).pos(3),
create_door(player, 'Mire Crystal Right ES', Intr).dir(Ea, 0x92, Bot, High).pos(3),
create_door(player, 'Mire Crystal Mid NW', Intr).dir(No, 0x92, Left, High).pos(1),
create_door(player, 'Mire Crystal Top SW', Intr).dir(So, 0x92, Left, High).pos(1),
create_door(player, 'Mire Crystal Right Orange Barrier', Lgcl),
create_door(player, 'Mire Crystal Mid Orange Barrier', Lgcl),
create_door(player, 'Mire Crystal Mid Blue Barrier', Lgcl),
create_door(player, 'Mire Crystal Left Blue Barrier', Lgcl),
create_door(player, 'Mire Crystal Left WS', Nrml).dir(We, 0x92, Bot, High).pos(2),
create_door(player, 'Mire Falling Foes ES', Nrml).dir(Ea, 0x91, Bot, High).pos(0),
create_door(player, 'Mire Falling Foes Up Stairs', Sprl).dir(Up, 0x91, 0, HTH).ss(S, 0x9b, 0x6c, True),
create_door(player, 'Mire Firesnake Skip Down Stairs', Sprl).dir(Dn, 0xa0, 0, HTH).ss(S, 0x92, 0x80, True, True),
create_door(player, 'Mire Firesnake Skip Orange Barrier', Lgcl),
create_door(player, 'Mire Antechamber Orange Barrier', Lgcl),
create_door(player, 'Mire Antechamber NW', Nrml).dir(No, 0xa0, Left, High).big_key().pos(0),
create_door(player, 'Mire Boss SW', Nrml).dir(So, 0x90, Left, High).no_exit().trap(0x4).pos(0),
create_door(player, 'TR Lobby Ledge NE', Nrml).dir(No, 0xd6, Right, High).pos(2),
create_door(player, 'TR Main Lobby Gap', Lgcl),
create_door(player, 'TR Lobby Ledge Gap', Lgcl),
create_door(player, 'TR Compass Room NW', Nrml).dir(No, 0xd6, Left, High).pos(0),
create_door(player, 'TR Hub SW', Nrml).dir(So, 0xc6, Left, High).pos(4),
create_door(player, 'TR Hub SE', Nrml).dir(So, 0xc6, Right, High).pos(5),
create_door(player, 'TR Hub ES', Nrml).dir(Ea, 0xc6, Bot, High).pos(3),
create_door(player, 'TR Hub EN', Nrml).dir(Ea, 0xc6, Top, High).pos(2),
create_door(player, 'TR Hub NW', Nrml).dir(No, 0xc6, Left, High).small_key().pos(0),
create_door(player, 'TR Hub NE', Nrml).dir(No, 0xc6, Right, High).pos(1),
create_door(player, 'TR Torches Ledge WS', Nrml).dir(We, 0xc7, Bot, High).pos(2),
create_door(player, 'TR Torches WN', Nrml).dir(We, 0xc7, Top, High).pos(1),
create_door(player, 'TR Torches NW', Nrml).dir(No, 0xc7, Left, High).trap(0x4).pos(0),
create_door(player, 'TR Roller Room SW', Nrml).dir(So, 0xb7, Left, High).pos(0),
create_door(player, 'TR Pokey 1 SW', Nrml).dir(So, 0xb6, Left, High).small_key().pos(2),
create_door(player, 'TR Tile Room SE', Nrml).dir(So, 0xb6, Right, High).pos(4),
create_door(player, 'TR Tile Room NE', Intr).dir(No, 0xb6, Right, High).pos(1),
create_door(player, 'TR Refill SE', Intr).dir(So, 0xb6, Right, High).pos(1),
create_door(player, 'TR Pokey 1 NW', Intr).dir(No, 0xb6, Left, High).small_key().pos(3),
create_door(player, 'TR Chain Chomps SW', Intr).dir(So, 0xb6, Left, High).small_key().pos(3),
create_door(player, 'TR Chain Chomps Down Stairs', Sprl).dir(Dn, 0xb6, 0, HTH).ss(A, 0x12, 0x80, True, True).small_key().pos(0),
create_door(player, 'TR Pipe Pit Up Stairs', Sprl).dir(Up, 0x15, 0, HTH).ss(A, 0x1b, 0x6c),
create_door(player, 'TR Pipe Pit WN', Nrml).dir(We, 0x15, Top, High).pos(1),
create_door(player, 'TR Pipe Ledge WS', Nrml).dir(We, 0x15, Bot, High).no_exit().trap(0x4).pos(0),
create_door(player, 'TR Pipe Ledge Drop Down', Lgcl),
create_door(player, 'TR Lava Dual Pipes EN', Nrml).dir(Ea, 0x14, Top, High).pos(5),
create_door(player, 'TR Lava Dual Pipes WN', Nrml).dir(We, 0x14, Top, High).pos(3),
create_door(player, 'TR Lava Dual Pipes SW', Nrml).dir(So, 0x14, Left, High).pos(4),
create_door(player, 'TR Lava Island WS', Nrml).dir(We, 0x14, Bot, High).small_key().pos(1),
create_door(player, 'TR Lava Island ES', Nrml).dir(Ea, 0x14, Bot, High).pos(6),
create_door(player, 'TR Lava Escape SE', Nrml).dir(So, 0x14, Right, High).small_key().pos(0),
create_door(player, 'TR Lava Escape NW', Nrml).dir(No, 0x14, Left, High).pos(2),
create_door(player, 'TR Pokey 2 EN', Nrml).dir(Ea, 0x13, Top, High).pos(1),
create_door(player, 'TR Pokey 2 ES', Nrml).dir(Ea, 0x13, Bot, High).small_key().pos(0),
create_door(player, 'TR Twin Pokeys NW', Nrml).dir(No, 0x24, Left, High).pos(5),
create_door(player, 'TR Twin Pokeys SW', Intr).dir(So, 0x24, Left, High).pos(2),
create_door(player, 'TR Hallway NW', Intr).dir(No, 0x24, Left, High).pos(2),
create_door(player, 'TR Hallway WS', Nrml).dir(We, 0x24, Bot, High).pos(6),
create_door(player, 'TR Twin Pokeys EN', Intr).dir(Ea, 0x24, Top, High).pos(1),
create_door(player, 'TR Dodgers WN', Intr).dir(We, 0x24, Top, High).pos(1),
create_door(player, 'TR Hallway ES', Intr).dir(Ea, 0x24, Bot, High).pos(7),
create_door(player, 'TR Big View WS', Intr).dir(We, 0x24, Bot, High).pos(7),
create_door(player, 'TR Big Chest Gap', Lgcl),
create_door(player, 'TR Big Chest Entrance Gap', Lgcl),
create_door(player, 'TR Big Chest NE', Intr).dir(No, 0x24, Right, High).pos(3),
create_door(player, 'TR Dodgers SE', Intr).dir(So, 0x24, Right, High).no_exit().pos(3),
create_door(player, 'TR Dodgers NE', Nrml).dir(No, 0x24, Right, High).big_key().pos(0),
create_door(player, 'TR Lazy Eyes ES', Nrml).dir(Ea, 0x23, Bot, High).pos(1),
create_door(player, 'TR Dash Room SW', Nrml).dir(So, 0x04, Left, High).pos(4),
create_door(player, 'TR Dash Room ES', Intr).dir(Ea, 0x04, Bot, High).pos(2),
create_door(player, 'TR Tongue Pull WS', Intr).dir(We, 0x04, Bot, High).pos(2),
create_door(player, 'TR Tongue Pull NE', Intr).dir(No, 0x04, Right, High).pos(3),
create_door(player, 'TR Rupees SE', Intr).dir(So, 0x04, Right, High).pos(3),
create_door(player, 'TR Dash Room NW', Intr).dir(No, 0x04, Left, High).pos(1),
create_door(player, 'TR Crystaroller SW', Intr).dir(So, 0x04, Left, High).pos(1),
create_door(player, 'TR Crystaroller Down Stairs', Sprl).dir(Dn, 0x04, 0, HTH).ss(A, 0x12, 0x80, True, True).small_key().pos(0),
create_door(player, 'TR Dark Ride Up Stairs', Sprl).dir(Up, 0xb5, 0, HTH).ss(A, 0x1b, 0x6c),
create_door(player, 'TR Dark Ride SW', Nrml).dir(So, 0xb5, Left, High).trap(0x4).pos(0),
create_door(player, 'TR Dash Bridge NW', Nrml).dir(No, 0xc5, Left, High).pos(1),
create_door(player, 'TR Dash Bridge SW', Nrml).dir(So, 0xc5, Left, High).pos(2),
create_door(player, 'TR Dash Bridge WS', Nrml).dir(We, 0xc5, Bot, High).small_key().pos(0),
create_door(player, 'TR Eye Bridge NW', Nrml).dir(No, 0xd5, Left, High).pos(1),
create_door(player, 'TR Crystal Maze ES', Nrml).dir(Ea, 0xc4, Bot, High).small_key().pos(0),
create_door(player, 'TR Crystal Maze Forwards Path', Lgcl),
create_door(player, 'TR Crystal Maze Blue Path', Lgcl),
create_door(player, 'TR Crystal Maze Cane Path', Lgcl),
create_door(player, 'TR Crystal Maze North Stairs', StrS).dir(No, 0xc4, Mid, High),
create_door(player, 'TR Final Abyss South Stairs', StrS).dir(So, 0xb4, Mid, High),
create_door(player, 'TR Final Abyss NW', Nrml).dir(No, 0xb4, Left, High).big_key().pos(0),
create_door(player, 'TR Boss SW', Nrml).dir(So, 0xa4, Left, High).no_exit().trap(0x4).pos(0),
create_door(player, 'GT Lobby Left Down Stairs', Sprl).dir(Dn, 0x0c, 1, HTL).ss(A, 0x0f, 0x80),
create_door(player, 'GT Lobby Up Stairs', Sprl).dir(Up, 0x0c, 2, HTH).ss(A, 0x1b, 0xec),
create_door(player, 'GT Lobby Right Down Stairs', Sprl).dir(Dn, 0x0c, 0, HTL).ss(S, 0x12, 0x80),
create_door(player, 'GT Torch Up Stairs', Sprl).dir(Up, 0x8c, 1, LTH).ss(A, 0x33, 0x6c, True, True),
create_door(player, 'GT Torch WN', Nrml).dir(We, 0x8c, Top, High).pos(3),
create_door(player, 'GT Hope Room Up Stairs', Sprl).dir(Up, 0x8c, 0, LTH).ss(S, 0x33, 0x6c, True, True),
create_door(player, 'GT Hope Room EN', Nrml).dir(Ea, 0x8c, Top, High).trap(0x4).pos(0),
create_door(player, 'GT Torch EN', Intr).dir(Ea, 0x8c, Top, High).small_key().pos(2),
create_door(player, 'GT Hope Room WN', Intr).dir(We, 0x8c, Top, High).small_key().pos(2),
create_door(player, 'GT Torch SW', Intr).dir(So, 0x8c, Left, High).no_exit().pos(1),
create_door(player, 'GT Big Chest NW', Intr).dir(No, 0x8c, Left, High).pos(1),
create_door(player, 'GT Blocked Stairs Down Stairs', Sprl).dir(Dn, 0x8c, 3, HTH).ss(Z, 0x12, 0x40, True, True).kill(),
create_door(player, 'GT Blocked Stairs Block Path', Lgcl),
create_door(player, 'GT Big Chest SW', Nrml).dir(So, 0x8c, Left, High).pos(4),
create_door(player, 'GT Bob\'s Room SE', Nrml).dir(So, 0x8c, Right, High).pos(5).kill(),
create_door(player, 'GT Bob\'s Room Hole', Hole),
create_door(player, 'GT Tile Room WN', Nrml).dir(We, 0x8d, Top, High).pos(2),
create_door(player, 'GT Tile Room EN', Intr).dir(Ea, 0x8d, Top, High).small_key().pos(1),
create_door(player, 'GT Speed Torch WN', Intr).dir(We, 0x8d, Top, High).small_key().pos(1),
create_door(player, 'GT Speed Torch NE', Nrml).dir(No, 0x8d, Right, High).pos(3),
create_door(player, 'GT Speed Torch South Path', Lgcl),
create_door(player, 'GT Speed Torch North Path', Lgcl),
create_door(player, 'GT Speed Torch WS', Intr).dir(We, 0x8d, Bot, High).pos(4),
create_door(player, 'GT Pots n Blocks ES', Intr).dir(Ea, 0x8d, Bot, High).pos(4),
create_door(player, 'GT Speed Torch SE', Nrml).dir(So, 0x8d, Right, High).trap(0x4).pos(0),
create_door(player, 'GT Crystal Conveyor NE', Nrml).dir(No, 0x9d, Right, High).pos(0).kill(),
create_door(player, 'GT Crystal Conveyor WN', Intr).dir(We, 0x9d, Top, High).pos(2),
create_door(player, 'GT Compass Room EN', Intr).dir(Ea, 0x9d, Top, High).pos(2),
create_door(player, 'GT Compass Room Warp', Warp),
create_door(player, 'GT Invisible Bridges WS', Nrml).dir(We, 0x9d, Bot, High).pos(1),
create_door(player, 'GT Invisible Catwalk ES', Nrml).dir(Ea, 0x9c, Bot, High).no_exit().trap(0x4).pos(0),
create_door(player, 'GT Invisible Catwalk WS', Nrml).dir(We, 0x9c, Bot, High).pos(3),
create_door(player, 'GT Invisible Catwalk NW', Nrml).dir(No, 0x9c, Left, High).pos(1),
create_door(player, 'GT Invisible Catwalk NE', Nrml).dir(No, 0x9c, Right, High).pos(2),
create_door(player, 'GT Conveyor Cross EN', Nrml).dir(Ea, 0x8b, Top, High).pos(2),
create_door(player, 'GT Conveyor Cross WN', Intr).dir(We, 0x8b, Top, High).pos(0),
create_door(player, 'GT Hookshot EN', Intr).dir(Ea, 0x8b, Top, High).pos(0),
create_door(player, 'GT Hookshot East-North Path', Lgcl),
create_door(player, 'GT Hookshot East-South Path', Lgcl),
create_door(player, 'GT Hookshot North-East Path', Lgcl),
create_door(player, 'GT Hookshot North-South Path', Lgcl),
create_door(player, 'GT Hookshot South-East Path', Lgcl),
create_door(player, 'GT Hookshot South-North Path', Lgcl),
create_door(player, 'GT Hookshot Platform Blue Barrier', Lgcl),
create_door(player, 'GT Hookshot Entry Blue Barrier', Lgcl),
create_door(player, 'GT Hookshot NW', Nrml).dir(No, 0x8b, Left, High).pos(4),
create_door(player, 'GT Hookshot ES', Intr).dir(Ea, 0x8b, Bot, High).small_key().pos(1),
create_door(player, 'GT Map Room WS', Intr).dir(We, 0x8b, Bot, High).small_key().pos(1),
create_door(player, 'GT Hookshot SW', Nrml).dir(So, 0x8b, Left, High).pos(3),
create_door(player, 'GT Double Switch NW', Nrml).dir(No, 0x9b, Left, High).pos(1).kill(),
create_door(player, 'GT Double Switch Orange Barrier', Lgcl),
create_door(player, 'GT Double Switch Orange Barrier 2', Lgcl),
create_door(player, 'GT Double Switch Blue Path', Lgcl),
create_door(player, 'GT Double Switch Orange Path', Lgcl),
create_door(player, 'GT Double Switch Key Blue Path', Lgcl),
create_door(player, 'GT Double Switch Key Orange Path', Lgcl),
create_door(player, 'GT Double Switch Blue Barrier', Lgcl),
create_door(player, 'GT Double Switch Transition Blue', Lgcl),
create_door(player, 'GT Double Switch EN', Intr).dir(Ea, 0x9b, Top, High).small_key().pos(0),
create_door(player, 'GT Spike Crystals WN', Intr).dir(We, 0x9b, Top, High).small_key().pos(0),
create_door(player, 'GT Spike Crystals Warp', Warp),
create_door(player, 'GT Warp Maze - Left Section Warp', Warp),
create_door(player, 'GT Warp Maze - Mid Section Left Warp', Warp),
create_door(player, 'GT Warp Maze - Mid Section Right Warp', Warp),
create_door(player, 'GT Warp Maze - Right Section Warp', Warp),
create_door(player, 'GT Warp Maze - Pit Section Warp Spot', Lgcl),
create_door(player, 'GT Warp Maze Exit Section Warp Spot', Lgcl),
create_door(player, 'GT Warp Maze - Pit Exit Warp', Warp),
create_door(player, 'GT Warp Maze (Pits) ES', Nrml).dir(Ea, 0x9b, Bot, High).pos(2),
create_door(player, 'GT Firesnake Room Hook Path', Lgcl),
create_door(player, 'GT Firesnake Room SW', Intr).dir(So, 0x7d, Left, High).small_key().pos(2),
create_door(player, 'GT Warp Maze (Rails) NW', Intr).dir(No, 0x7d, Left, High).small_key().pos(2),
create_door(player, 'GT Warp Maze - Rail Choice Left Warp', Warp),
create_door(player, 'GT Warp Maze - Rail Choice Right Warp', Warp),
create_door(player, 'GT Warp Maze - Rando Rail Warp', Warp),
create_door(player, 'GT Warp Maze - Main Rails Best Warp', Warp),
create_door(player, 'GT Warp Maze - Main Rails Mid Left Warp', Warp),
create_door(player, 'GT Warp Maze - Main Rails Mid Right Warp', Warp),
create_door(player, 'GT Warp Maze - Main Rails Right Top Warp', Warp),
create_door(player, 'GT Warp Maze - Main Rails Right Mid Warp', Warp),
create_door(player, 'GT Warp Maze - Pot Rail Warp', Warp),
create_door(player, 'GT Warp Maze (Rails) WS', Nrml).dir(We, 0x7d, Bot, High).pos(1),
create_door(player, 'GT Petting Zoo SE', Nrml).dir(So, 0x7d, Right, High).trap(0x4).pos(0),
create_door(player, 'GT Conveyor Star Pits EN', Nrml).dir(Ea, 0x7b, Top, High).small_key().pos(1),
create_door(player, 'GT Hidden Star ES', Nrml).dir(Ea, 0x7b, Bot, High).pos(2).kill(),
create_door(player, 'GT Hidden Star Warp', Warp),
create_door(player, 'GT DMs Room SW', Nrml).dir(So, 0x7b, Left, High).trap(0x4).pos(0),
create_door(player, 'GT Falling Bridge WN', Nrml).dir(We, 0x7c, Top, High).small_key().pos(2),
create_door(player, 'GT Falling Bridge WS', Nrml).dir(We, 0x7c, Bot, High).pos(3),
create_door(player, 'GT Randomizer Room ES', Nrml).dir(Ea, 0x7c, Bot, High).pos(1),
create_door(player, 'GT Ice Armos NE', Intr).dir(No, 0x1c, Right, High).pos(0),
create_door(player, 'GT Big Key Room SE', Intr).dir(So, 0x1c, Right, High).pos(0),
create_door(player, 'GT Ice Armos WS', Intr).dir(We, 0x1c, Bot, High).pos(1),
create_door(player, 'GT Four Torches ES', Intr).dir(Ea, 0x1c, Bot, High).no_exit().pos(1),
create_door(player, 'GT Four Torches NW', Intr).dir(No, 0x1c, Left, High).pos(2),
create_door(player, 'GT Fairy Abyss SW', Intr).dir(So, 0x1c, Left, High).pos(2),
create_door(player, 'GT Four Torches Up Stairs', Sprl).dir(Up, 0x1c, 0, HTH).ss(Z, 0x1b, 0x2c, True, True),
create_door(player, 'GT Crystal Paths Down Stairs', Sprl).dir(Dn, 0x6b, 0, HTH).ss(A, 0x12, 0x00, False, True),
create_door(player, 'GT Crystal Paths SW', Intr).dir(So, 0x6b, Left, High).pos(3),
create_door(player, 'GT Mimics 1 NW', Intr).dir(No, 0x6b, Left, High).pos(3),
create_door(player, 'GT Mimics 1 ES', Intr).dir(Ea, 0x6b, Bot, High).pos(2),
create_door(player, 'GT Mimics 2 WS', Intr).dir(We, 0x6b, Bot, High).pos(2),
create_door(player, 'GT Mimics 2 NE', Intr).dir(No, 0x6b, Right, High).pos(1),
create_door(player, 'GT Dash Hall SE', Intr).dir(So, 0x6b, Right, High).pos(1),
create_door(player, 'GT Dash Hall NE', Nrml).dir(No, 0x6b, Right, High).big_key().pos(0),
create_door(player, 'GT Hidden Spikes SE', Nrml).dir(So, 0x5b, Right, High).small_key().pos(0),
create_door(player, 'GT Hidden Spikes EN', Nrml).dir(Ea, 0x5b, Top, High).trap(0x2).pos(1),
create_door(player, 'GT Cannonball Bridge WN', Nrml).dir(We, 0x5c, Top, High).pos(1),
create_door(player, 'GT Cannonball Bridge SE', Intr).dir(So, 0x5c, Right, High).pos(0),
create_door(player, 'GT Refill NE', Intr).dir(No, 0x5c, Right, High).pos(0),
create_door(player, 'GT Cannonball Bridge Up Stairs', Sprl).dir(Up, 0x5c, 0, HTH).ss(S, 0x1a, 0x6c, True),
create_door(player, 'GT Gauntlet 1 Down Stairs', Sprl).dir(Dn, 0x5d, 0, HTH).ss(S, 0x11, 0x80, True, True),
create_door(player, 'GT Gauntlet 1 WN', Intr).dir(We, 0x5d, Top, High).pos(2),
create_door(player, 'GT Gauntlet 2 EN', Intr).dir(Ea, 0x5d, Top, High).pos(2),
create_door(player, 'GT Gauntlet 2 SW', Intr).dir(So, 0x5d, Left, High).pos(0),
create_door(player, 'GT Gauntlet 3 NW', Intr).dir(No, 0x5d, Left, High).pos(0),
create_door(player, 'GT Gauntlet 3 SW', Nrml).dir(So, 0x5d, Left, High).trap(0x2).pos(1),
create_door(player, 'GT Gauntlet 4 NW', Nrml).dir(No, 0x6d, Left, High).trap(0x4).pos(0),
create_door(player, 'GT Gauntlet 4 SW', Intr).dir(So, 0x6d, Left, High).pos(1),
create_door(player, 'GT Gauntlet 5 NW', Intr).dir(No, 0x6d, Left, High).pos(1),
create_door(player, 'GT Gauntlet 5 WS', Nrml).dir(We, 0x6d, Bot, High).trap(0x1).pos(2),
create_door(player, 'GT Beam Dash ES', Nrml).dir(Ea, 0x6c, Bot, High).pos(2).kill(),
create_door(player, 'GT Beam Dash WS', Intr).dir(We, 0x6c, Bot, High).pos(0),
create_door(player, 'GT Lanmolas 2 ES', Intr).dir(Ea, 0x6c, Bot, High).pos(0),
create_door(player, 'GT Lanmolas 2 NW', Intr).dir(No, 0x6c, Left, High).pos(1),
create_door(player, 'GT Quad Pot SW', Intr).dir(So, 0x6c, Left, High).no_exit().pos(1),
create_door(player, 'GT Quad Pot Up Stairs', Sprl).dir(Up, 0x6c, 0, HTH).ss(A, 0x1b, 0x6c, True, True),
create_door(player, 'GT Wizzrobes 1 Down Stairs', Sprl).dir(Dn, 0xa5, 0, HTH).ss(A, 0x12, 0x80, True, True),
create_door(player, 'GT Wizzrobes 1 SW', Intr).dir(So, 0xa5, Left, High).pos(2),
create_door(player, 'GT Dashing Bridge NW', Intr).dir(No, 0xa5, Left, High).pos(2),
create_door(player, 'GT Dashing Bridge NE', Intr).dir(No, 0xa5, Right, High).pos(1),
create_door(player, 'GT Wizzrobes 2 SE', Intr).dir(So, 0xa5, Right, High).pos(1),
create_door(player, 'GT Wizzrobes 2 NE', Nrml).dir(No, 0xa5, Right, High).trap(0x4).pos(0),
create_door(player, 'GT Conveyor Bridge SE', Nrml).dir(So, 0x95, Right, High).pos(0),
create_door(player, 'GT Conveyor Bridge EN', Nrml).dir(Ea, 0x95, Top, High).pos(1),
create_door(player, 'GT Torch Cross WN', Nrml).dir(We, 0x96, Top, High).pos(1),
create_door(player, 'GT Torch Cross ES', Intr).dir(Ea, 0x96, Bot, High).pos(0),
create_door(player, 'GT Staredown WS', Intr).dir(We, 0x96, Bot, High).pos(0),
create_door(player, 'GT Staredown Up Ladder', Lddr),
create_door(player, 'GT Falling Torches Down Ladder', Lddr),
create_door(player, 'GT Falling Torches NE', Intr).dir(No, 0x3d, Right, High).pos(0),
create_door(player, 'GT Mini Helmasaur Room SE', Intr).dir(So, 0x3d, Right, High).pos(0),
create_door(player, 'GT Falling Torches Hole', Hole),
create_door(player, 'GT Mini Helmasaur Room WN', Intr).dir(We, 0x3d, Top, High).small_key().pos(1),
create_door(player, 'GT Bomb Conveyor EN', Intr).dir(Ea, 0x3d, Top, High).small_key().pos(1),
create_door(player, 'GT Bomb Conveyor SW', Intr).dir(So, 0x3d, Left, High).pos(3),
create_door(player, 'GT Crystal Circles NW', Intr).dir(No, 0x3d, Left, High).pos(3),
create_door(player, 'GT Crystal Circles SW', Nrml).dir(So, 0x3d, Left, High).small_key().pos(2),
create_door(player, 'GT Left Moldorm Ledge NW', Nrml).dir(No, 0x4d, Left, High).small_key().pos(0).kill(),
create_door(player, 'GT Left Moldorm Ledge Drop Down', Lgcl),
create_door(player, 'GT Right Moldorm Ledge Drop Down', Lgcl),
create_door(player, 'GT Moldorm Gap', Lgcl),
create_door(player, 'GT Moldorm Hole', Hole),
create_door(player, 'GT Validation Block Path', Lgcl),
create_door(player, 'GT Validation WS', Nrml).dir(We, 0x4d, Bot, High).pos(1),
create_door(player, 'GT Right Moldorm Ledge Down Stairs', Sprl).dir(Dn, 0x4d, 0, HTH).ss(S, 0x12, 0x80).kill(),
create_door(player, 'GT Moldorm Pit Up Stairs', Sprl).dir(Up, 0xa6, 0, HTH).ss(S, 0x1b, 0x6c),
create_door(player, 'GT Frozen Over ES', Nrml).dir(Ea, 0x4c, Bot, High).no_exit().trap(0x4).pos(0),
create_door(player, 'GT Frozen Over Up Stairs', Sprl).dir(Up, 0x4c, 0, HTH).ss(S, 0x1a, 0x6c, True),
create_door(player, 'GT Brightly Lit Hall Down Stairs', Sprl).dir(Dn, 0x1d, 0, HTH).ss(S, 0x11, 0x80, False, True),
create_door(player, 'GT Brightly Lit Hall NW', Nrml).dir(No, 0x1d, Left, High).big_key().pos(0),
create_door(player, 'GT Agahnim 2 SW', Nrml).dir(So, 0x0d, Left, High).no_exit().trap(0x4).pos(0)
]
world.doors += doors
world.initialize_doors(doors)
create_paired_doors(world, player)
# swamp events
world.get_door('Swamp Trench 1 Approach Key', player).event('Trench 1 Switch')
world.get_door('Swamp Trench 1 Approach Swim Depart', player).event('Trench 1 Switch')
world.get_door('Swamp Trench 1 Key Approach', player).event('Trench 1 Switch')
world.get_door('Swamp Trench 1 Key Ledge Depart', player).event('Trench 1 Switch')
world.get_door('Swamp Trench 1 Departure Approach', player).event('Trench 1 Switch')
world.get_door('Swamp Trench 1 Departure Key', player).event('Trench 1 Switch')
world.get_door('Swamp Trench 2 Pots Wet', player).event('Trench 2 Switch')
world.get_door('Swamp Trench 2 Departure Wet', player).event('Trench 2 Switch')
world.get_door('Swamp Drain WN', player).event('Swamp Drain')
world.get_door('Swamp Flooded Room WS', player).event('Swamp Drain')
world.get_door('Swamp Drain Right Switch', player).event('Swamp Drain')
world.get_door('Swamp Flooded Room Ladder', player).event('Swamp Drain')
if world.mode[player] == 'standard':
world.get_door('Hyrule Castle Throne Room Tapestry', player).event('Zelda Pickup')
world.get_door('Hyrule Castle Tapestry Backwards', player).event('Zelda Pickup')
# crystal switches and barriers
world.get_door('Hera Lobby Down Stairs', player).c_switch()
world.get_door('Hera Lobby Key Stairs', player).c_switch()
world.get_door('Hera Lobby Up Stairs', player).c_switch()
world.get_door('Hera Basement Cage Up Stairs', player).c_switch()
world.get_door('Hera Tile Room Up Stairs', player).c_switch()
world.get_door('Hera Tile Room EN', player).c_switch()
world.get_door('Hera Tridorm WN', player).c_switch()
world.get_door('Hera Tridorm SE', player).c_switch()
world.get_door('Hera Beetles Down Stairs', player).c_switch()
world.get_door('Hera Beetles WS', player).c_switch()
world.get_door('Hera Beetles Holes', player).c_switch()
world.get_door('Hera Startile Wide SW', player).c_switch()
world.get_door('Hera Startile Wide Up Stairs', player).c_switch()
world.get_door('Hera Startile Wide Holes', player).c_switch()
world.get_door('PoD Arena Main SW', player).c_switch()
world.get_door('PoD Arena Bonk Path', player).c_switch()
world.get_door('PoD Arena Bridge SE', player).c_switch()
world.get_door('PoD Arena Bridge Drop Down', player).c_switch()
world.get_door('PoD Arena Main Orange Barrier', player).barrier(CrystalBarrier.Orange)
# maybe you can cross this way with blue up??
world.get_door('PoD Arena Main Crystal Path', player).barrier(CrystalBarrier.Blue)
world.get_door('PoD Arena Crystal Path', player).barrier(CrystalBarrier.Blue)
world.get_door('PoD Sexy Statue W', player).c_switch()
world.get_door('PoD Sexy Statue NW', player).c_switch()
world.get_door('PoD Map Balcony WS', player).c_switch()
world.get_door('PoD Map Balcony South Stairs', player).c_switch()
world.get_door('PoD Bow Statue SW', player).c_switch()
world.get_door('PoD Bow Statue Down Ladder', player).c_switch()
world.get_door('PoD Dark Pegs Up Ladder', player).c_switch()
world.get_door('PoD Dark Pegs WN', player).c_switch()
world.get_door('Swamp Crystal Switch EN', player).c_switch()
world.get_door('Swamp Crystal Switch SE', player).c_switch()
world.get_door('Swamp Shortcut Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Swamp Trench 2 Pots Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Swamp Barrier Ledge - Orange', player).barrier(CrystalBarrier.Orange)
world.get_door('Swamp Barrier - Orange', player).barrier(CrystalBarrier.Orange)
world.get_door('Thieves Spike Switch Up Stairs', player).c_switch()
world.get_door('Thieves Spike Switch SW', player).c_switch()
world.get_door('Thieves Attic ES', player).barrier(CrystalBarrier.Blue)
world.get_door('Thieves Hellway Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Thieves Hellway Crystal Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Thieves Triple Bypass SE', player).barrier(CrystalBarrier.Blue)
world.get_door('Thieves Triple Bypass WN', player).barrier(CrystalBarrier.Blue)
world.get_door('Thieves Triple Bypass EN', player).barrier(CrystalBarrier.Blue)
world.get_door('Thieves Hellway Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Thieves Hellway Crystal Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Thieves Hellway Crystal Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Thieves Attic Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Thieves Attic Hint Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Ice Bomb Drop SE', player).c_switch()
world.get_door('Ice Conveyor SW', player).c_switch()
world.get_door('Ice Refill WS', player).c_switch()
world.get_door('Ice Bomb Drop Hole', player).barrier(CrystalBarrier.Orange) # not required to hit switch w/ bomb
world.get_door('Ice Bomb Jump Ledge Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Ice Bomb Jump Catwalk Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Ice Crystal Right Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Ice Crystal Right Blue Hole', player).barrier(CrystalBarrier.Blue)
world.get_door('Ice Crystal Left Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Ice Crystal Left Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Ice Backwards Room Hole', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Fishbone E', player).c_switch()
world.get_door('Mire Conveyor Crystal ES', player).c_switch()
world.get_door('Mire Conveyor Crystal SE', player).c_switch()
world.get_door('Mire Conveyor Crystal WS', player).c_switch()
world.get_door('Mire Tall Dark and Roomy ES', player).c_switch()
world.get_door('Mire Tall Dark and Roomy WN', player).c_switch()
world.get_door('Mire Tall Dark and Roomy WS', player).c_switch()
world.get_door('Mire Crystal Top SW', player).c_switch()
world.get_door('Mire Falling Foes ES', player).c_switch()
world.get_door('Mire Falling Foes Up Stairs', player).c_switch()
world.get_door('Mire Hub Upper Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Hub Lower Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Hub Right Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Hub Top Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Hub Switch Blue Barrier N', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Hub Switch Blue Barrier S', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Map Spike Side Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Map Spot Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Crystal Dead End Left Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Crystal Dead End Right Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Fishbone Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire South Fish Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Compass Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Crystal Mid Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Crystal Left Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('Mire Crystal Right Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Mire Crystal Mid Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Mire Firesnake Skip Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('Mire Antechamber Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('TR Chain Chomps SW', player).c_switch()
world.get_door('TR Chain Chomps Down Stairs', player).c_switch()
world.get_door('TR Pokey 2 EN', player).c_switch()
world.get_door('TR Pokey 2 ES', player).c_switch()
world.get_door('TR Crystaroller SW', player).c_switch()
world.get_door('TR Crystaroller Down Stairs', player).c_switch()
world.get_door('TR Crystal Maze ES', player).c_switch()
world.get_door('TR Crystal Maze Forwards Path', player).c_switch()
world.get_door('TR Crystal Maze Cane Path', player).c_switch()
world.get_door('TR Crystal Maze Blue Path', player).barrier(CrystalBarrier.Blue)
world.get_door('GT Crystal Conveyor NE', player).c_switch()
world.get_door('GT Crystal Conveyor WN', player).c_switch()
world.get_door('GT Hookshot South-North Path', player).c_switch()
world.get_door('GT Hookshot South-East Path', player).c_switch()
world.get_door('GT Hookshot ES', player).c_switch()
world.get_door('GT Hookshot Platform Blue Barrier', player).c_switch()
world.get_door('GT Double Switch Orange Path', player).c_switch()
world.get_door('GT Double Switch Blue Path', player).c_switch()
world.get_door('GT Spike Crystals WN', player).c_switch()
world.get_door('GT Spike Crystals Warp', player).c_switch()
world.get_door('GT Crystal Paths Down Stairs', player).c_switch()
world.get_door('GT Crystal Paths SW', player).c_switch()
world.get_door('GT Hidden Spikes SE', player).c_switch()
world.get_door('GT Hidden Spikes EN', player).c_switch()
world.get_door('GT Crystal Circles NW', player).c_switch()
world.get_door('GT Crystal Circles SW', player).c_switch()
world.get_door('GT Hookshot Entry Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('GT Double Switch Orange Barrier', player).barrier(CrystalBarrier.Orange)
world.get_door('GT Double Switch Orange Barrier 2', player).barrier(CrystalBarrier.Orange)
world.get_door('GT Double Switch Orange Path', player).barrier(CrystalBarrier.Orange)
world.get_door('GT Double Switch Key Orange Path', player).barrier(CrystalBarrier.Orange)
world.get_door('GT Double Switch Key Blue Path', player).barrier(CrystalBarrier.Blue)
world.get_door('GT Double Switch Blue Barrier', player).barrier(CrystalBarrier.Blue)
world.get_door('GT Double Switch Transition Blue', player).barrier(CrystalBarrier.Blue)
# nifty dynamic logical doors:
south_controller = world.get_door('Ice Cross Bottom SE', player)
east_controller = world.get_door('Ice Cross Right ES', player)
controller_door(south_controller, world.get_door('Ice Cross Left Push Block', player))
controller_door(south_controller, world.get_door('Ice Cross Right Push Block Bottom', player))
controller_door(south_controller, world.get_door('Ice Cross Top Push Block Bottom', player))
controller_door(east_controller, world.get_door('Ice Cross Bottom Push Block Right', player))
controller_door(east_controller, world.get_door('Ice Cross Top Push Block Right', player))
assign_entrances(world, player)
def create_paired_doors(world, player):
world.paired_doors[player] = [
PairedDoor('Sewers Secret Room Key Door S', 'Sewers Key Rat Key Door N', True),
PairedDoor('TR Pokey 2 ES', 'TR Lava Island WS', True), # TR Pokey Key
PairedDoor('TR Dodgers NE', 'TR Lava Escape SE', True), # TR Big key door by pipes
PairedDoor('PoD Falling Bridge WN', 'PoD Dark Maze EN', True), # Pod Dark maze door
PairedDoor('PoD Dark Maze E', 'PoD Big Chest Balcony W', True), # PoD Bombable by Big Chest
PairedDoor('PoD Arena Main NW', 'PoD Falling Bridge SW', True), # Pod key door by bridge
PairedDoor('Sewers Dark Cross Key Door N', 'Sewers Water S', True),
PairedDoor('Swamp Hub WN', 'Swamp Crystal Switch EN', True), # Swamp key door crystal switch
PairedDoor('Swamp Hub North Ledge N', 'Swamp Push Statue S', True), # Swamp key door above big chest
PairedDoor('PoD Map Balcony WS', 'PoD Arena Ledge ES', True), # Pod bombable by arena
PairedDoor('Swamp Hub Dead Ledge EN', 'Swamp Hammer Switch WN', True), # Swamp bombable to random pots
PairedDoor('Swamp Pot Row WN', 'Swamp Map Ledge EN', True), # Swamp bombable to map chest
PairedDoor('Swamp Pot Row WS', 'Swamp Trench 1 Approach ES', True), # Swamp key door early room $38
PairedDoor('PoD Middle Cage N', 'PoD Pit Room S', True),
PairedDoor('GT Crystal Circles SW', 'GT Left Moldorm Ledge NW', True), # GT moldorm key door
PairedDoor('Ice Conveyor SW', 'Ice Bomb Jump NW', True), # Ice BJ key door
PairedDoor('Desert Tiles 2 SE', 'Desert Beamos Hall NE', True),
PairedDoor('Skull 3 Lobby NW', 'Skull Star Pits SW', True), # Skull 3 key door
PairedDoor('Skull 1 Lobby WS', 'Skull Pot Prison ES', True), # Skull 1 key door - pot prison to big chest
PairedDoor('Skull Map Room SE', 'Skull Pinball NE', True), # Skull 1 - pinball key door
PairedDoor('GT Dash Hall NE', 'GT Hidden Spikes SE', True), # gt main big key door
PairedDoor('Ice Spike Cross ES', 'Ice Spike Room WS', True), # ice door to spike chest
PairedDoor('GT Conveyor Star Pits EN', 'GT Falling Bridge WN', True), # gt right side key door to cape bridge
PairedDoor('GT Warp Maze (Rails) WS', 'GT Randomizer Room ES', True), # gt bombable to rando room
PairedDoor('Ice Tall Hint SE', 'Ice Lonely Freezor NE', True), # ice's big icy room key door to lonely freezor
PairedDoor('Eastern Courtyard N', 'Eastern Darkness S', True),
PairedDoor('Mire Fishbone SE', 'Mire Spike Barrier NE', True), # mire fishbone key door
PairedDoor('Mire BK Door Room N', 'Mire Left Bridge S', True), # mire big key door to bridges
PairedDoor('Eastern Big Key NE', 'Eastern Hint Tile Blocked Path SE', True),
PairedDoor('TR Hub NW', 'TR Pokey 1 SW', True), # TR somaria hub to pokey
PairedDoor('Eastern Dark Square Key Door WN', 'Eastern Cannonball Ledge Key Door EN', True),
PairedDoor('Thieves Rail Ledge NW', 'Thieves Pot Alcove Bottom SW', True), # TT random bomb to pots
PairedDoor('Thieves BK Corner NE', 'Thieves Hallway SE', True), # TT big key door
PairedDoor('Ice Switch Room ES', 'Ice Refill WS', True), # Ice last key door to crystal switch
PairedDoor('Mire Hub WS', 'Mire Conveyor Crystal ES', True), # mire hub key door to attic
PairedDoor('Mire Hub Right EN', 'Mire Map Spot WN', True), # mire hub key door to map
PairedDoor('TR Dash Bridge WS', 'TR Crystal Maze ES', True), # tr last key door to switch maze
PairedDoor('Thieves Ambush E', 'Thieves Rail Ledge W', True) # TT dashable above
]
def assign_entrances(world, player):
for door in world.doors:
if door.player == player:
entrance = world.check_for_entrance(door.name, player)
if entrance is not None:
door.entrance = entrance
entrance.door = door
def controller_door(controller, dependent):
dependent.controller = controller
controller.dependents.append(dependent)
def create_door(player, name, door_type):
return Door(player, name, door_type)
def ugly_door(door):
door.ugly = True
return door
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,120
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/Fill.py
|
import random
import logging
from BaseClasses import CollectionState
class FillError(RuntimeError):
pass
def distribute_items_cutoff(world, cutoffrate=0.33):
# get list of locations to fill in
fill_locations = world.get_unfilled_locations()
random.shuffle(fill_locations)
# get items to distribute
random.shuffle(world.itempool)
itempool = world.itempool
total_advancement_items = len([item for item in itempool if item.advancement])
placed_advancement_items = 0
progress_done = False
advancement_placed = False
# sweep once to pick up preplaced items
world.state.sweep_for_events()
while itempool and fill_locations:
candidate_item_to_place = None
item_to_place = None
for item in itempool:
if advancement_placed or (progress_done and (item.advancement or item.priority)):
item_to_place = item
break
if item.advancement:
candidate_item_to_place = item
if world.unlocks_new_location(item):
item_to_place = item
placed_advancement_items += 1
break
if item_to_place is None:
# check if we can reach all locations and that is why we find no new locations to place
if not progress_done and len(world.get_reachable_locations()) == len(world.get_locations()):
progress_done = True
continue
# check if we have now placed all advancement items
if progress_done:
advancement_placed = True
continue
# we might be in a situation where all new locations require multiple items to reach. If that is the case, just place any advancement item we've found and continue trying
if candidate_item_to_place is not None:
item_to_place = candidate_item_to_place
placed_advancement_items += 1
else:
# we placed all available progress items. Maybe the game can be beaten anyway?
if world.can_beat_game():
logging.getLogger('').warning('Not all locations reachable. Game beatable anyway.')
progress_done = True
continue
raise FillError('No more progress items left to place.')
spot_to_fill = None
for location in fill_locations if placed_advancement_items / total_advancement_items < cutoffrate else reversed(fill_locations):
if location.can_fill(world.state, item_to_place):
spot_to_fill = location
break
if spot_to_fill is None:
# we filled all reachable spots. Maybe the game can be beaten anyway?
if world.can_beat_game():
logging.getLogger('').warning('Not all items placed. Game beatable anyway.')
break
raise FillError('No more spots to place %s' % item_to_place)
world.push_item(spot_to_fill, item_to_place, True)
itempool.remove(item_to_place)
fill_locations.remove(spot_to_fill)
unplaced = [item.name for item in itempool]
unfilled = [location.name for location in fill_locations]
if unplaced or unfilled:
logging.warning('Unplaced items: %s - Unfilled Locations: %s', unplaced, unfilled)
def distribute_items_staleness(world):
# get list of locations to fill in
fill_locations = world.get_unfilled_locations()
random.shuffle(fill_locations)
# get items to distribute
random.shuffle(world.itempool)
itempool = world.itempool
progress_done = False
advancement_placed = False
# sweep once to pick up preplaced items
world.state.sweep_for_events()
while itempool and fill_locations:
candidate_item_to_place = None
item_to_place = None
for item in itempool:
if advancement_placed or (progress_done and (item.advancement or item.priority)):
item_to_place = item
break
if item.advancement:
candidate_item_to_place = item
if world.unlocks_new_location(item):
item_to_place = item
break
if item_to_place is None:
# check if we can reach all locations and that is why we find no new locations to place
if not progress_done and len(world.get_reachable_locations()) == len(world.get_locations()):
progress_done = True
continue
# check if we have now placed all advancement items
if progress_done:
advancement_placed = True
continue
# we might be in a situation where all new locations require multiple items to reach. If that is the case, just place any advancement item we've found and continue trying
if candidate_item_to_place is not None:
item_to_place = candidate_item_to_place
else:
# we placed all available progress items. Maybe the game can be beaten anyway?
if world.can_beat_game():
logging.getLogger('').warning('Not all locations reachable. Game beatable anyway.')
progress_done = True
continue
raise FillError('No more progress items left to place.')
spot_to_fill = None
for location in fill_locations:
# increase likelyhood of skipping a location if it has been found stale
if not progress_done and random.randint(0, location.staleness_count) > 2:
continue
if location.can_fill(world.state, item_to_place):
spot_to_fill = location
break
else:
location.staleness_count += 1
# might have skipped too many locations due to potential staleness. Do not check for staleness now to find a candidate
if spot_to_fill is None:
for location in fill_locations:
if location.can_fill(world.state, item_to_place):
spot_to_fill = location
break
if spot_to_fill is None:
# we filled all reachable spots. Maybe the game can be beaten anyway?
if world.can_beat_game():
logging.getLogger('').warning('Not all items placed. Game beatable anyway.')
break
raise FillError('No more spots to place %s' % item_to_place)
world.push_item(spot_to_fill, item_to_place, True)
itempool.remove(item_to_place)
fill_locations.remove(spot_to_fill)
unplaced = [item.name for item in itempool]
unfilled = [location.name for location in fill_locations]
if unplaced or unfilled:
logging.warning('Unplaced items: %s - Unfilled Locations: %s', unplaced, unfilled)
def fill_restrictive(world, base_state, locations, itempool, keys_in_itempool = None, single_player_placement = False):
def sweep_from_pool():
new_state = base_state.copy()
for item in itempool:
new_state.collect(item, True)
new_state.sweep_for_events()
return new_state
unplaced_items = []
no_access_checks = {}
reachable_items = {}
for item in itempool:
if world.accessibility[item.player] == 'none':
no_access_checks.setdefault(item.player, []).append(item)
else:
reachable_items.setdefault(item.player, []).append(item)
for player_items in [no_access_checks, reachable_items]:
while any(player_items.values()) and locations:
items_to_place = [[itempool.remove(items[-1]), items.pop()][-1] for items in player_items.values() if items]
maximum_exploration_state = sweep_from_pool()
has_beaten_game = world.has_beaten_game(maximum_exploration_state)
for item_to_place in items_to_place:
perform_access_check = True
if world.accessibility[item_to_place.player] == 'none':
perform_access_check = not world.has_beaten_game(maximum_exploration_state, item_to_place.player) if single_player_placement else not has_beaten_game
spot_to_fill = None
for location in locations:
if item_to_place.smallkey or item_to_place.bigkey: # a better test to see if a key can go there
location.item = item_to_place
test_state = maximum_exploration_state.copy()
test_state.stale[item_to_place.player] = True
else:
test_state = maximum_exploration_state
if (not single_player_placement or location.player == item_to_place.player)\
and location.can_fill(test_state, item_to_place, perform_access_check)\
and valid_key_placement(item_to_place, location, itempool if (keys_in_itempool and keys_in_itempool[item_to_place.player]) else world.itempool, world):
spot_to_fill = location
break
elif item_to_place.smallkey or item_to_place.bigkey:
location.item = None
if spot_to_fill is None:
# we filled all reachable spots. Maybe the game can be beaten anyway?
unplaced_items.insert(0, item_to_place)
if world.can_beat_game():
if world.accessibility[item_to_place.player] != 'none':
logging.getLogger('').warning('Not all items placed. Game beatable anyway. (Could not place %s)' % item_to_place)
continue
raise FillError('No more spots to place %s' % item_to_place)
world.push_item(spot_to_fill, item_to_place, False)
track_outside_keys(item_to_place, spot_to_fill, world)
locations.remove(spot_to_fill)
spot_to_fill.event = True
itempool.extend(unplaced_items)
def valid_key_placement(item, location, itempool, world):
if (not item.smallkey and not item.bigkey) or item.player != location.player or world.retro[item.player] or world.logic[item.player] == 'nologic':
return True
dungeon = location.parent_region.dungeon
if dungeon:
if dungeon.name not in item.name and (dungeon.name != 'Hyrule Castle' or 'Escape' not in item.name):
return True
key_logic = world.key_logic[item.player][dungeon.name]
unplaced_keys = len([x for x in itempool if x.name == key_logic.small_key_name and x.player == item.player])
return key_logic.check_placement(unplaced_keys, location if item.bigkey else None)
else:
inside_dungeon_item = ((item.smallkey and not world.keyshuffle[item.player])
or (item.bigkey and not world.bigkeyshuffle[item.player]))
return not inside_dungeon_item
def track_outside_keys(item, location, world):
if not item.smallkey:
return
item_dungeon = item.name.split('(')[1][:-1]
if item_dungeon == 'Escape':
item_dungeon = 'Hyrule Castle'
if location.player == item.player:
loc_dungeon = location.parent_region.dungeon
if loc_dungeon and loc_dungeon.name == item_dungeon:
return # this is an inside key
world.key_logic[item.player][item_dungeon].outside_keys += 1
def distribute_items_restrictive(world, gftower_trash=False, fill_locations=None):
# If not passed in, then get a shuffled list of locations to fill in
if not fill_locations:
fill_locations = world.get_unfilled_locations()
random.shuffle(fill_locations)
# get items to distribute
random.shuffle(world.itempool)
progitempool = [item for item in world.itempool if item.advancement]
prioitempool = [item for item in world.itempool if not item.advancement and item.priority]
restitempool = [item for item in world.itempool if not item.advancement and not item.priority]
# fill in gtower locations with trash first
for player in range(1, world.players + 1):
if not gftower_trash or not world.ganonstower_vanilla[player] or world.doorShuffle[player] == 'crossed':
continue
gftower_trash_count = (random.randint(15, 50) if world.goal[player] == 'triforcehunt' else random.randint(0, 15))
gtower_locations = [location for location in fill_locations if 'Ganons Tower' in location.name and location.player == player]
random.shuffle(gtower_locations)
trashcnt = 0
while gtower_locations and restitempool and trashcnt < gftower_trash_count:
spot_to_fill = gtower_locations.pop()
item_to_place = restitempool.pop()
world.push_item(spot_to_fill, item_to_place, False)
fill_locations.remove(spot_to_fill)
trashcnt += 1
random.shuffle(fill_locations)
fill_locations.reverse()
# Make sure the escape small key is placed first in standard with key shuffle to prevent running out of spots
# todo: crossed
progitempool.sort(key=lambda item: 1 if item.name == 'Small Key (Escape)' and world.keyshuffle[item.player] and world.mode[item.player] == 'standard' else 0)
fill_restrictive(world, world.state, fill_locations, progitempool,
keys_in_itempool={player: world.keyshuffle[player] for player in range(1, world.players + 1)})
random.shuffle(fill_locations)
fast_fill(world, prioitempool, fill_locations)
fast_fill(world, restitempool, fill_locations)
unplaced = [item.name for item in prioitempool + restitempool]
unfilled = [location.name for location in fill_locations]
if unplaced or unfilled:
logging.warning('Unplaced items: %s - Unfilled Locations: %s', unplaced, unfilled)
def fast_fill(world, item_pool, fill_locations):
while item_pool and fill_locations:
spot_to_fill = fill_locations.pop()
item_to_place = item_pool.pop()
world.push_item(spot_to_fill, item_to_place, False)
def flood_items(world):
# get items to distribute
random.shuffle(world.itempool)
itempool = world.itempool
progress_done = False
# sweep once to pick up preplaced items
world.state.sweep_for_events()
# fill world from top of itempool while we can
while not progress_done:
location_list = world.get_unfilled_locations()
random.shuffle(location_list)
spot_to_fill = None
for location in location_list:
if location.can_fill(world.state, itempool[0]):
spot_to_fill = location
break
if spot_to_fill:
item = itempool.pop(0)
world.push_item(spot_to_fill, item, True)
continue
# ran out of spots, check if we need to step in and correct things
if len(world.get_reachable_locations()) == len(world.get_locations()):
progress_done = True
continue
# need to place a progress item instead of an already placed item, find candidate
item_to_place = None
candidate_item_to_place = None
for item in itempool:
if item.advancement:
candidate_item_to_place = item
if world.unlocks_new_location(item):
item_to_place = item
break
# we might be in a situation where all new locations require multiple items to reach. If that is the case, just place any advancement item we've found and continue trying
if item_to_place is None:
if candidate_item_to_place is not None:
item_to_place = candidate_item_to_place
else:
raise FillError('No more progress items left to place.')
# find item to replace with progress item
location_list = world.get_reachable_locations()
random.shuffle(location_list)
for location in location_list:
if location.item is not None and not location.item.advancement and not location.item.priority and not location.item.smallkey and not location.item.bigkey:
# safe to replace
replace_item = location.item
replace_item.location = None
itempool.append(replace_item)
world.push_item(location, item_to_place, True)
itempool.remove(item_to_place)
break
def balance_multiworld_progression(world):
state = CollectionState(world)
checked_locations = []
unchecked_locations = world.get_locations().copy()
random.shuffle(unchecked_locations)
reachable_locations_count = {}
for player in range(1, world.players + 1):
reachable_locations_count[player] = 0
def get_sphere_locations(sphere_state, locations):
sphere_state.sweep_for_events(key_only=True, locations=locations)
return [loc for loc in locations if sphere_state.can_reach(loc) and sphere_state.not_flooding_a_key(sphere_state.world, loc)]
while True:
sphere_locations = get_sphere_locations(state, unchecked_locations)
for location in sphere_locations:
unchecked_locations.remove(location)
reachable_locations_count[location.player] += 1
if checked_locations:
threshold = max(reachable_locations_count.values()) - 20
balancing_players = [player for player, reachables in reachable_locations_count.items() if reachables < threshold]
if balancing_players is not None and len(balancing_players) > 0:
balancing_state = state.copy()
balancing_unchecked_locations = unchecked_locations.copy()
balancing_reachables = reachable_locations_count.copy()
balancing_sphere = sphere_locations.copy()
candidate_items = []
while True:
for location in balancing_sphere:
if location.event and (world.keyshuffle[location.item.player] or not location.item.smallkey) and (world.bigkeyshuffle[location.item.player] or not location.item.bigkey):
balancing_state.collect(location.item, True, location)
if location.item.player in balancing_players and not location.locked:
candidate_items.append(location)
balancing_sphere = get_sphere_locations(balancing_state, balancing_unchecked_locations)
for location in balancing_sphere:
balancing_unchecked_locations.remove(location)
balancing_reachables[location.player] += 1
if world.has_beaten_game(balancing_state) or all([reachables >= threshold for reachables in balancing_reachables.values()]):
break
elif not balancing_sphere:
raise RuntimeError('Not all required items reachable. Something went terribly wrong here.')
unlocked_locations = [l for l in unchecked_locations if l not in balancing_unchecked_locations]
items_to_replace = []
for player in balancing_players:
locations_to_test = [l for l in unlocked_locations if l.player == player]
# only replace items that end up in another player's world
items_to_test = [l for l in candidate_items if l.item.player == player and l.player != player]
while items_to_test:
testing = items_to_test.pop()
reducing_state = state.copy()
for location in [*[l for l in items_to_replace if l.item.player == player], *items_to_test]:
reducing_state.collect(location.item, True, location)
reducing_state.sweep_for_events(locations=locations_to_test)
if world.has_beaten_game(balancing_state):
if not world.has_beaten_game(reducing_state):
items_to_replace.append(testing)
else:
reduced_sphere = get_sphere_locations(reducing_state, locations_to_test)
if reachable_locations_count[player] + len(reduced_sphere) < threshold:
items_to_replace.append(testing)
replaced_items = False
replacement_locations = [l for l in checked_locations if not l.event and not l.locked]
while replacement_locations and items_to_replace:
new_location = replacement_locations.pop()
old_location = items_to_replace.pop()
while not new_location.can_fill(state, old_location.item, False) or (new_location.item and not old_location.can_fill(state, new_location.item, False)):
replacement_locations.insert(0, new_location)
new_location = replacement_locations.pop()
new_location.item, old_location.item = old_location.item, new_location.item
new_location.event, old_location.event = True, False
state.collect(new_location.item, True, new_location)
replaced_items = True
if replaced_items:
for location in get_sphere_locations(state, [l for l in unlocked_locations if l.player in balancing_players]):
unchecked_locations.remove(location)
reachable_locations_count[location.player] += 1
sphere_locations.append(location)
for location in sphere_locations:
if location.event and (world.keyshuffle[location.item.player] or not location.item.smallkey) and (world.bigkeyshuffle[location.item.player] or not location.item.bigkey):
state.collect(location.item, True, location)
checked_locations.extend(sphere_locations)
if world.has_beaten_game(state):
break
elif not sphere_locations:
raise RuntimeError('Not all required items reachable. Something went terribly wrong here.')
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,121
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/source/gui/randomize/generation.py
|
from tkinter import ttk, filedialog, StringVar, Button, Entry, Frame, Label, E, W, LEFT, X
import source.gui.widgets as widgets
import json
import os
from source.classes.Empty import Empty
def generation_page(parent,settings):
# Generation Setup
self = ttk.Frame(parent)
# Generation Setup options
self.widgets = {}
# Generation Setup option sections
self.frames = {}
self.frames["checkboxes"] = Frame(self)
self.frames["checkboxes"].pack(anchor=W)
# Load Generation Setup option widgets as defined by JSON file
# Defns include frame name, widget type, widget options, widget placement attributes
with open(os.path.join("resources","app","gui","randomize","generation","checkboxes.json")) as checkboxes:
myDict = json.load(checkboxes)
myDict = myDict["checkboxes"]
dictWidgets = widgets.make_widgets_from_dict(self, myDict, self.frames["checkboxes"])
for key in dictWidgets:
self.widgets[key] = dictWidgets[key]
self.widgets[key].pack(anchor=W)
self.frames["widgets"] = Frame(self)
self.frames["widgets"].pack(anchor=W)
# Load Generation Setup option widgets as defined by JSON file
# Defns include frame name, widget type, widget options, widget placement attributes
with open(os.path.join("resources","app","gui","randomize","generation","widgets.json")) as items:
myDict = json.load(items)
myDict = myDict["widgets"]
dictWidgets = widgets.make_widgets_from_dict(self, myDict, self.frames["widgets"])
for key in dictWidgets:
self.widgets[key] = dictWidgets[key]
self.widgets[key].pack(anchor=W)
self.frames["baserom"] = Frame(self)
self.frames["baserom"].pack(anchor=W, fill=X)
## Locate base ROM
# This one's more-complicated, build it and stuff it
# widget ID
widget = "rom"
# Empty object
self.widgets[widget] = Empty()
# pieces
self.widgets[widget].pieces = {}
# frame
self.widgets[widget].pieces["frame"] = Frame(self.frames["baserom"])
# frame: label
self.widgets[widget].pieces["frame"].label = Label(self.widgets[widget].pieces["frame"], text='Base Rom: ')
# storage var
self.widgets[widget].storageVar = StringVar()
# textbox
self.widgets[widget].pieces["textbox"] = Entry(self.widgets[widget].pieces["frame"], textvariable=self.widgets[widget].storageVar)
self.widgets[widget].storageVar.set(settings["rom"])
# FIXME: Translate these
def RomSelect():
rom = filedialog.askopenfilename(filetypes=[("Rom Files", (".sfc", ".smc")), ("All Files", "*")], initialdir=os.path.join("."))
self.widgets[widget].storageVar.set(rom)
# dialog button
self.widgets[widget].pieces["button"] = Button(self.widgets[widget].pieces["frame"], text='Select Rom', command=RomSelect)
# frame label: pack
self.widgets[widget].pieces["frame"].label.pack(side=LEFT)
# textbox: pack
self.widgets[widget].pieces["textbox"].pack(side=LEFT, fill=X, expand=True)
# button: pack
self.widgets[widget].pieces["button"].pack(side=LEFT)
# frame: pack
self.widgets[widget].pieces["frame"].pack(fill=X)
return self,settings
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,122
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/resources/ci/common/install.py
|
import common
import os # for env vars
import subprocess # do stuff at the shell level
env = common.prepare_env()
# get executables
# python
# linux/windows: python
# macosx: python3
# pip
# linux/macosx: pip3
# windows: pip
PYTHON_EXECUTABLE = "python3" if "osx" in env["OS_NAME"] else "python"
PIP_EXECUTABLE = "pip" if "windows" in env["OS_NAME"] else "pip3"
PIP_EXECUTABLE = "pip" if "osx" in env["OS_NAME"] and "actions" in env["CI_SYSTEM"] else PIP_EXECUTABLE
# upgrade pip
subprocess.check_call([PYTHON_EXECUTABLE,"-m","pip","install","--upgrade","pip"])
# pip version
subprocess.check_call([PIP_EXECUTABLE,"--version"])
# if pip3, install wheel
if PIP_EXECUTABLE == "pip3":
subprocess.check_call([PIP_EXECUTABLE,"install","-U","wheel"])
# install listed dependencies
subprocess.check_call([PIP_EXECUTABLE,"install","-r","./resources/app/meta/manifests/pip_requirements.txt"])
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,123
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/Rules.py
|
import logging
from collections import deque
from BaseClasses import CollectionState, RegionType, DoorType, Entrance
from Regions import key_only_locations
from RoomData import DoorKind
def set_rules(world, player):
if world.logic[player] == 'nologic':
logging.getLogger('').info('WARNING! Seeds generated under this logic often require major glitches and may be impossible!')
world.get_region('Menu', player).can_reach_private = lambda state: True
for exit in world.get_region('Menu', player).exits:
exit.hide_path = True
return
global_rules(world, player)
if world.mode[player] != 'inverted':
default_rules(world, player)
if world.mode[player] == 'open':
open_rules(world, player)
elif world.mode[player] == 'standard':
standard_rules(world, player)
elif world.mode[player] == 'inverted':
open_rules(world, player)
inverted_rules(world, player)
else:
raise NotImplementedError('Not implemented yet')
if world.logic[player] == 'noglitches':
no_glitches_rules(world, player)
elif world.logic[player] == 'minorglitches':
logging.getLogger('').info('Minor Glitches may be buggy still. No guarantee for proper logic checks.')
else:
raise NotImplementedError('Not implemented yet')
if world.goal[player] == 'dungeons':
# require all dungeons to beat ganon
add_rule(world.get_location('Ganon', player), lambda state: state.can_reach('Master Sword Pedestal', 'Location', player) and state.has('Beat Agahnim 1', player) and state.has('Beat Agahnim 2', player) and state.has_crystals(7, player))
elif world.goal[player] == 'ganon':
# require aga2 to beat ganon
add_rule(world.get_location('Ganon', player), lambda state: state.has('Beat Agahnim 2', player))
if world.mode[player] != 'inverted':
set_big_bomb_rules(world, player)
else:
set_inverted_big_bomb_rules(world, player)
# if swamp and dam have not been moved we require mirror for swamp palace
if not world.swamp_patch_required[player]:
add_rule(world.get_entrance('Swamp Lobby Moat', player), lambda state: state.has_Mirror(player))
if world.mode[player] != 'inverted':
set_bunny_rules(world, player)
else:
set_inverted_bunny_rules(world, player)
def set_rule(spot, rule):
spot.access_rule = rule
def set_defeat_dungeon_boss_rule(location):
# Lambda required to defer evaluation of dungeon.boss since it will change later if boos shuffle is used
set_rule(location, lambda state: location.parent_region.dungeon.boss.can_defeat(state))
def set_always_allow(spot, rule):
spot.always_allow = rule
def add_rule(spot, rule, combine='and'):
old_rule = spot.access_rule
if combine == 'or':
spot.access_rule = lambda state: rule(state) or old_rule(state)
else:
spot.access_rule = lambda state: rule(state) and old_rule(state)
def add_lamp_requirement(spot, player):
add_rule(spot, lambda state: state.has('Lamp', player, state.world.lamps_needed_for_dark_rooms))
def forbid_item(location, item, player):
old_rule = location.item_rule
location.item_rule = lambda i: (i.name != item or i.player != player) and old_rule(i)
def add_item_rule(location, rule):
old_rule = location.item_rule
location.item_rule = lambda item: rule(item) and old_rule(item)
def item_in_locations(state, item, player, locations):
for location in locations:
if item_name(state, location[0], location[1]) == (item, player):
return True
return False
def item_name(state, location, player):
location = state.world.get_location(location, player)
if location.item is None:
return None
return (location.item.name, location.item.player)
def global_rules(world, player):
# ganon can only carry triforce
add_item_rule(world.get_location('Ganon', player), lambda item: item.name == 'Triforce' and item.player == player)
# we can s&q to the old man house after we rescue him. This may be somewhere completely different if caves are shuffled!
world.get_region('Menu', player).can_reach_private = lambda state: True
for exit in world.get_region('Menu', player).exits:
exit.hide_path = True
set_rule(world.get_entrance('Old Man S&Q', player), lambda state: state.can_reach('Old Man', 'Location', player))
set_rule(world.get_location('Sunken Treasure', player), lambda state: state.has('Open Floodgate', player))
set_rule(world.get_location('Dark Blacksmith Ruins', player), lambda state: state.has('Return Smith', player))
set_rule(world.get_location('Purple Chest', player), lambda state: state.has('Pick Up Purple Chest', player)) # Can S&Q with chest
set_rule(world.get_location('Ether Tablet', player), lambda state: state.has('Book of Mudora', player) and state.has_beam_sword(player))
set_rule(world.get_location('Master Sword Pedestal', player), lambda state: state.has('Red Pendant', player) and state.has('Blue Pendant', player) and state.has('Green Pendant', player))
set_rule(world.get_location('Missing Smith', player), lambda state: state.has('Get Frog', player) and state.can_reach('Blacksmiths Hut', 'Region', player)) # Can't S&Q with smith
set_rule(world.get_location('Blacksmith', player), lambda state: state.has('Return Smith', player))
set_rule(world.get_location('Magic Bat', player), lambda state: state.has('Magic Powder', player))
set_rule(world.get_location('Sick Kid', player), lambda state: state.has_bottle(player))
set_rule(world.get_location('Library', player), lambda state: state.has_Boots(player))
set_rule(world.get_location('Mimic Cave', player), lambda state: state.has('Hammer', player))
set_rule(world.get_location('Sahasrahla', player), lambda state: state.has('Green Pendant', player))
set_rule(world.get_location('Spike Cave', player), lambda state:
state.has('Hammer', player) and state.can_lift_rocks(player) and
((state.has('Cape', player) and state.can_extend_magic(player, 16, True)) or
(state.has('Cane of Byrna', player) and
(state.can_extend_magic(player, 12, True) or
(state.world.can_take_damage and (state.has_Boots(player) or state.has_hearts(player, 4))))))
)
set_rule(world.get_location('Hookshot Cave - Top Right', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_location('Hookshot Cave - Top Left', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_location('Hookshot Cave - Bottom Right', player), lambda state: state.has('Hookshot', player) or state.has('Pegasus Boots', player))
set_rule(world.get_location('Hookshot Cave - Bottom Left', player), lambda state: state.has('Hookshot', player))
# Start of door rando rules
# TODO: Do these need to flag off when door rando is off? - some of them, yes
# Eastern Palace
# Eyegore room needs a bow
set_rule(world.get_entrance('Eastern Duo Eyegores NE', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('Eastern Single Eyegore NE', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('Eastern Map Balcony Hook Path', player), lambda state: state.has('Hookshot', player))
# Boss rules. Same as below but no BK or arrow requirement.
set_defeat_dungeon_boss_rule(world.get_location('Eastern Palace - Prize', player))
set_defeat_dungeon_boss_rule(world.get_location('Eastern Palace - Boss', player))
# Desert
set_rule(world.get_location('Desert Palace - Torch', player), lambda state: state.has_Boots(player))
set_rule(world.get_entrance('Desert Wall Slide NW', player), lambda state: state.has_fire_source(player))
set_defeat_dungeon_boss_rule(world.get_location('Desert Palace - Prize', player))
set_defeat_dungeon_boss_rule(world.get_location('Desert Palace - Boss', player))
# Tower of Hera
set_rule(world.get_location('Tower of Hera - Big Key Chest', player), lambda state: state.has_fire_source(player))
set_rule(world.get_entrance('Hera Big Chest Hook Path', player), lambda state: state.has('Hookshot', player))
set_defeat_dungeon_boss_rule(world.get_location('Tower of Hera - Boss', player))
set_defeat_dungeon_boss_rule(world.get_location('Tower of Hera - Prize', player))
# Castle Tower
set_rule(world.get_entrance('Tower Gold Knights SW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('Tower Gold Knights EN', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('Tower Dark Archers WN', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('Tower Red Spears WN', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('Tower Red Guards EN', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('Tower Red Guards SW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('Tower Altar NW', player), lambda state: state.has_sword(player))
set_defeat_dungeon_boss_rule(world.get_location('Agahnim 1', player))
set_rule(world.get_entrance('PoD Arena Bonk Path', player), lambda state: state.has_Boots(player))
set_rule(world.get_entrance('PoD Mimics 1 NW', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('PoD Mimics 2 NW', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('PoD Bow Statue Down Ladder', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('PoD Map Balcony Drop Down', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('PoD Dark Pegs WN', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('PoD Dark Pegs Up Ladder', player), lambda state: state.has('Hammer', player))
set_defeat_dungeon_boss_rule(world.get_location('Palace of Darkness - Boss', player))
set_defeat_dungeon_boss_rule(world.get_location('Palace of Darkness - Prize', player))
set_rule(world.get_entrance('Swamp Lobby Moat', player), lambda state: state.has('Flippers', player) and state.has('Open Floodgate', player))
set_rule(world.get_entrance('Swamp Trench 1 Approach Dry', player), lambda state: not state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Key Ledge Dry', player), lambda state: not state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Departure Dry', player), lambda state: not state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Approach Key', player), lambda state: state.has('Flippers', player) and state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Approach Swim Depart', player), lambda state: state.has('Flippers', player) and state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Key Approach', player), lambda state: state.has('Flippers', player) and state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Key Ledge Depart', player), lambda state: state.has('Flippers', player) and state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Departure Approach', player), lambda state: state.has('Flippers', player) and state.has('Trench 1 Filled', player))
set_rule(world.get_entrance('Swamp Trench 1 Departure Key', player), lambda state: state.has('Flippers', player) and state.has('Trench 1 Filled', player))
set_rule(world.get_location('Trench 1 Switch', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Swamp Hub Hook Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_location('Swamp Palace - Hookshot Pot Key', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Swamp Trench 2 Pots Dry', player), lambda state: not state.has('Trench 2 Filled', player))
set_rule(world.get_entrance('Swamp Trench 2 Pots Wet', player), lambda state: state.has('Flippers', player) and state.has('Trench 2 Filled', player))
set_rule(world.get_entrance('Swamp Trench 2 Departure Wet', player), lambda state: state.has('Flippers', player) and state.has('Trench 2 Filled', player))
set_rule(world.get_entrance('Swamp West Ledge Hook Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Swamp Barrier Ledge Hook Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Swamp Drain Right Switch', player), lambda state: state.has('Drained Swamp', player))
set_rule(world.get_entrance('Swamp Drain WN', player), lambda state: state.has('Drained Swamp', player))
set_rule(world.get_entrance('Swamp Flooded Room WS', player), lambda state: state.has('Drained Swamp', player))
set_rule(world.get_entrance('Swamp Flooded Room Ladder', player), lambda state: state.has('Drained Swamp', player))
set_rule(world.get_location('Swamp Palace - Flooded Room - Left', player), lambda state: state.has('Drained Swamp', player))
set_rule(world.get_location('Swamp Palace - Flooded Room - Right', player), lambda state: state.has('Drained Swamp', player))
set_rule(world.get_entrance('Swamp Flooded Spot Ladder', player), lambda state: state.has('Flippers', player) or state.has('Drained Swamp', player))
set_rule(world.get_entrance('Swamp Drain Left Up Stairs', player), lambda state: state.has('Flippers', player) or state.has('Drained Swamp', player))
set_rule(world.get_entrance('Swamp Waterway NW', player), lambda state: state.has('Flippers', player))
set_rule(world.get_entrance('Swamp Waterway N', player), lambda state: state.has('Flippers', player))
set_rule(world.get_entrance('Swamp Waterway NE', player), lambda state: state.has('Flippers', player))
set_rule(world.get_location('Swamp Palace - Waterway Pot Key', player), lambda state: state.has('Flippers', player))
set_defeat_dungeon_boss_rule(world.get_location('Swamp Palace - Boss', player))
set_defeat_dungeon_boss_rule(world.get_location('Swamp Palace - Prize', player))
set_rule(world.get_entrance('Skull Big Chest Hookpath', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Skull Torch Room WN', player), lambda state: state.has('Fire Rod', player))
set_rule(world.get_entrance('Skull Vines NW', player), lambda state: state.has_sword(player))
set_defeat_dungeon_boss_rule(world.get_location('Skull Woods - Boss', player))
set_defeat_dungeon_boss_rule(world.get_location('Skull Woods - Prize', player))
# blind can't have the small key? - not necessarily true anymore - but likely still
set_rule(world.get_location('Thieves\' Town - Big Chest', player), lambda state: state.has('Hammer', player))
for entrance in ['Thieves Basement Block Path', 'Thieves Blocked Entry Path', 'Thieves Conveyor Block Path', 'Thieves Conveyor Bridge Block Path']:
set_rule(world.get_entrance(entrance, player), lambda state: state.can_lift_rocks(player))
for location in ['Thieves\' Town - Blind\'s Cell', 'Thieves\' Town - Boss']:
forbid_item(world.get_location(location, player), 'Big Key (Thieves Town)', player)
forbid_item(world.get_location('Thieves\' Town - Blind\'s Cell', player), 'Big Key (Thieves Town)', player)
for location in ['Suspicious Maiden', 'Thieves\' Town - Blind\'s Cell']:
set_rule(world.get_location(location, player), lambda state: state.has('Big Key (Thieves Town)', player))
set_rule(world.get_location('Revealing Light', player), lambda state: state.has('Shining Light', player) and state.has('Maiden Rescued', player))
set_rule(world.get_location('Thieves\' Town - Boss', player), lambda state: state.has('Maiden Unmasked', player) and world.get_location('Thieves\' Town - Boss', player).parent_region.dungeon.boss.can_defeat(state))
set_rule(world.get_location('Thieves\' Town - Prize', player), lambda state: state.has('Maiden Unmasked', player) and world.get_location('Thieves\' Town - Prize', player).parent_region.dungeon.boss.can_defeat(state))
set_rule(world.get_entrance('Ice Lobby WS', player), lambda state: state.can_melt_things(player))
set_rule(world.get_entrance('Ice Hammer Block ES', player), lambda state: state.can_lift_rocks(player) and state.has('Hammer', player))
set_rule(world.get_location('Ice Palace - Hammer Block Key Drop', player), lambda state: state.can_lift_rocks(player) and state.has('Hammer', player))
set_rule(world.get_location('Ice Palace - Map Chest', player), lambda state: state.can_lift_rocks(player) and state.has('Hammer', player))
set_rule(world.get_entrance('Ice Antechamber Hole', player), lambda state: state.can_lift_rocks(player) and state.has('Hammer', player))
# todo: ohko rules for spike room - could split into two regions instead of these, but can_take_damage is usually true
set_rule(world.get_entrance('Ice Spike Room WS', player), lambda state: state.world.can_take_damage or state.has('Hookshot', player) or state.has('Cape', player) or state.has('Cane of Byrna', player))
set_rule(world.get_entrance('Ice Spike Room Up Stairs', player), lambda state: state.world.can_take_damage or state.has('Hookshot', player) or state.has('Cape', player) or state.has('Cane of Byrna', player))
set_rule(world.get_entrance('Ice Spike Room Down Stairs', player), lambda state: state.world.can_take_damage or state.has('Hookshot', player) or state.has('Cape', player) or state.has('Cane of Byrna', player))
set_rule(world.get_location('Ice Palace - Spike Room', player), lambda state: state.world.can_take_damage or state.has('Hookshot', player) or state.has('Cape', player) or state.has('Cane of Byrna', player))
set_rule(world.get_location('Ice Palace - Freezor Chest', player), lambda state: state.can_melt_things(player))
set_rule(world.get_entrance('Ice Hookshot Ledge Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Ice Hookshot Balcony Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Ice Switch Room SE', player), lambda state: state.has('Cane of Somaria', player) or state.has('Convenient Block', player))
set_defeat_dungeon_boss_rule(world.get_location('Ice Palace - Boss', player))
set_defeat_dungeon_boss_rule(world.get_location('Ice Palace - Prize', player))
set_rule(world.get_entrance('Mire Lobby Gap', player), lambda state: state.has_Boots(player) or state.has('Hookshot', player))
set_rule(world.get_entrance('Mire Post-Gap Gap', player), lambda state: state.has_Boots(player) or state.has('Hookshot', player))
set_rule(world.get_entrance('Mire Falling Bridge WN', player), lambda state: state.has_Boots(player) or state.has('Hookshot', player)) # this is due to the fact the the door opposite is blocked
set_rule(world.get_entrance('Mire 2 NE', player), lambda state: state.has_sword(player) or state.has('Fire Rod', player) or state.has('Ice Rod', player) or state.has('Hammer', player) or state.has('Cane of Somaria', player) or state.can_shoot_arrows(player)) # need to defeat wizzrobes, bombs don't work ...
set_rule(world.get_location('Misery Mire - Spike Chest', player), lambda state: (state.world.can_take_damage and state.has_hearts(player, 4)) or state.has('Cane of Byrna', player) or state.has('Cape', player))
set_rule(world.get_entrance('Mire Left Bridge Hook Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Mire Tile Room NW', player), lambda state: state.has_fire_source(player))
set_rule(world.get_entrance('Mire Attic Hint Hole', player), lambda state: state.has_fire_source(player))
set_rule(world.get_entrance('Mire Dark Shooters SW', player), lambda state: state.has('Cane of Somaria', player))
set_defeat_dungeon_boss_rule(world.get_location('Misery Mire - Boss', player))
set_defeat_dungeon_boss_rule(world.get_location('Misery Mire - Prize', player))
set_rule(world.get_entrance('TR Main Lobby Gap', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Lobby Ledge Gap', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Hub SW', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Hub SE', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Hub ES', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Hub EN', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Hub NW', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Hub NE', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Torches NW', player), lambda state: state.has('Cane of Somaria', player) and state.has('Fire Rod', player))
set_rule(world.get_entrance('TR Big Chest Entrance Gap', player), lambda state: state.has('Cane of Somaria', player) or state.has('Hookshot', player))
set_rule(world.get_entrance('TR Big Chest Gap', player), lambda state: state.has('Cane of Somaria', player) or state.has_Boots(player))
set_rule(world.get_entrance('TR Dark Ride Up Stairs', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Dark Ride SW', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Crystal Maze Cane Path', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Final Abyss South Stairs', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('TR Final Abyss NW', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_location('Turtle Rock - Eye Bridge - Bottom Left', player), lambda state: state.has('Cane of Byrna', player) or state.has('Cape', player) or state.has('Mirror Shield', player))
set_rule(world.get_location('Turtle Rock - Eye Bridge - Bottom Right', player), lambda state: state.has('Cane of Byrna', player) or state.has('Cape', player) or state.has('Mirror Shield', player))
set_rule(world.get_location('Turtle Rock - Eye Bridge - Top Left', player), lambda state: state.has('Cane of Byrna', player) or state.has('Cape', player) or state.has('Mirror Shield', player))
set_rule(world.get_location('Turtle Rock - Eye Bridge - Top Right', player), lambda state: state.has('Cane of Byrna', player) or state.has('Cape', player) or state.has('Mirror Shield', player))
set_defeat_dungeon_boss_rule(world.get_location('Turtle Rock - Boss', player))
set_defeat_dungeon_boss_rule(world.get_location('Turtle Rock - Prize', player))
set_rule(world.get_location('Ganons Tower - Bob\'s Torch', player), lambda state: state.has_Boots(player))
set_rule(world.get_entrance('GT Hope Room EN', player), lambda state: state.has('Cane of Somaria', player))
set_rule(world.get_entrance('GT Conveyor Cross WN', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('GT Conveyor Cross EN', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('GT Speed Torch SE', player), lambda state: state.has('Fire Rod', player))
set_rule(world.get_entrance('GT Hookshot East-North Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('GT Hookshot South-East Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('GT Hookshot South-North Path', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('GT Hookshot East-South Path', player), lambda state: state.has('Hookshot', player) or state.has_Boots(player))
set_rule(world.get_entrance('GT Hookshot North-East Path', player), lambda state: state.has('Hookshot', player) or state.has_Boots(player))
set_rule(world.get_entrance('GT Hookshot North-South Path', player), lambda state: state.has('Hookshot', player) or state.has_Boots(player))
set_rule(world.get_entrance('GT Firesnake Room Hook Path', player), lambda state: state.has('Hookshot', player))
# I am tempted to stick an invincibility rule for getting across falling bridge
set_rule(world.get_entrance('GT Ice Armos NE', player), lambda state: world.get_region('GT Ice Armos', player).dungeon.bosses['bottom'].can_defeat(state))
set_rule(world.get_entrance('GT Ice Armos WS', player), lambda state: world.get_region('GT Ice Armos', player).dungeon.bosses['bottom'].can_defeat(state))
set_rule(world.get_entrance('GT Mimics 1 NW', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('GT Mimics 1 ES', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('GT Mimics 2 WS', player), lambda state: state.can_shoot_arrows(player))
set_rule(world.get_entrance('GT Mimics 2 NE', player), lambda state: state.can_shoot_arrows(player))
# consider access to refill room
set_rule(world.get_entrance('GT Gauntlet 1 WN', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 2 EN', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 2 SW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 3 NW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 3 SW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 4 NW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 4 SW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 5 NW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Gauntlet 5 WS', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Wizzrobes 1 SW', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Wizzrobes 2 SE', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Wizzrobes 2 NE', player), lambda state: state.can_kill_most_things(player))
set_rule(world.get_entrance('GT Lanmolas 2 ES', player), lambda state: world.get_region('GT Lanmolas 2', player).dungeon.bosses['middle'].can_defeat(state))
set_rule(world.get_entrance('GT Lanmolas 2 NW', player), lambda state: world.get_region('GT Lanmolas 2', player).dungeon.bosses['middle'].can_defeat(state))
set_rule(world.get_entrance('GT Torch Cross ES', player), lambda state: state.has_fire_source(player))
set_rule(world.get_entrance('GT Falling Torches NE', player), lambda state: state.has_fire_source(player))
set_rule(world.get_entrance('GT Moldorm Gap', player), lambda state: state.has('Hookshot', player) and world.get_region('GT Moldorm', player).dungeon.bosses['top'].can_defeat(state))
set_defeat_dungeon_boss_rule(world.get_location('Agahnim 2', player))
# crystal switch rules
set_rule(world.get_entrance('PoD Arena Crystal Path', player), lambda state: state.can_reach_blue(world.get_region('PoD Arena Crystal', player), player))
set_rule(world.get_entrance('Swamp Trench 2 Pots Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Swamp Trench 2 Pots', player), player))
set_rule(world.get_entrance('Swamp Shortcut Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Swamp Shortcut', player), player))
set_rule(world.get_entrance('Thieves Attic ES', player), lambda state: state.can_reach_blue(world.get_region('Thieves Attic', player), player))
set_rule(world.get_entrance('Thieves Hellway Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Thieves Hellway', player), player))
set_rule(world.get_entrance('Thieves Hellway Crystal Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Thieves Hellway N Crystal', player), player))
set_rule(world.get_entrance('Thieves Triple Bypass SE', player), lambda state: state.can_reach_blue(world.get_region('Thieves Triple Bypass', player), player))
set_rule(world.get_entrance('Thieves Triple Bypass WN', player), lambda state: state.can_reach_blue(world.get_region('Thieves Triple Bypass', player), player))
set_rule(world.get_entrance('Thieves Triple Bypass EN', player), lambda state: state.can_reach_blue(world.get_region('Thieves Triple Bypass', player), player))
set_rule(world.get_entrance('Ice Crystal Right Blue Hole', player), lambda state: state.can_reach_blue(world.get_region('Ice Crystal Right', player), player))
set_rule(world.get_entrance('Ice Crystal Left Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Ice Crystal Left', player), player))
set_rule(world.get_entrance('Ice Backwards Room Hole', player), lambda state: state.can_reach_blue(world.get_region('Ice Backwards Room', player), player))
set_rule(world.get_entrance('Mire Hub Upper Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Hub', player), player))
set_rule(world.get_entrance('Mire Hub Lower Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Hub', player), player))
set_rule(world.get_entrance('Mire Hub Right Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Hub Right', player), player))
set_rule(world.get_entrance('Mire Hub Top Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Hub Top', player), player))
set_rule(world.get_entrance('Mire Hub Switch Blue Barrier N', player), lambda state: state.can_reach_blue(world.get_region('Mire Hub Switch', player), player))
set_rule(world.get_entrance('Mire Hub Switch Blue Barrier S', player), lambda state: state.can_reach_blue(world.get_region('Mire Hub Switch', player), player))
set_rule(world.get_entrance('Mire Map Spike Side Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Map Spike Side', player), player))
set_rule(world.get_entrance('Mire Map Spot Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Map Spot', player), player))
set_rule(world.get_entrance('Mire Crystal Dead End Left Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Crystal Dead End', player), player))
set_rule(world.get_entrance('Mire Crystal Dead End Right Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Crystal Dead End', player), player))
set_rule(world.get_entrance('Mire South Fish Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire South Fish', player), player))
set_rule(world.get_entrance('Mire Compass Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Compass Room', player), player))
set_rule(world.get_entrance('Mire Crystal Mid Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Crystal Mid', player), player))
set_rule(world.get_entrance('Mire Crystal Left Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('Mire Crystal Left', player), player))
set_rule(world.get_entrance('TR Crystal Maze Blue Path', player), lambda state: state.can_reach_blue(world.get_region('TR Crystal Maze End', player), player))
set_rule(world.get_entrance('GT Hookshot Entry Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('GT Hookshot South Entry', player), player))
set_rule(world.get_entrance('GT Double Switch Key Blue Path', player), lambda state: state.can_reach_blue(world.get_region('GT Double Switch Key Spot', player), player))
set_rule(world.get_entrance('GT Double Switch Blue Barrier', player), lambda state: state.can_reach_blue(world.get_region('GT Double Switch Switches', player), player))
set_rule(world.get_entrance('GT Double Switch Transition Blue', player), lambda state: state.can_reach_blue(world.get_region('GT Double Switch Transition', player), player))
set_rule(world.get_entrance('Swamp Barrier Ledge - Orange', player), lambda state: state.can_reach_orange(world.get_region('Swamp Barrier Ledge', player), player))
set_rule(world.get_entrance('Swamp Barrier - Orange', player), lambda state: state.can_reach_orange(world.get_region('Swamp Barrier', player), player))
set_rule(world.get_entrance('Thieves Hellway Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Thieves Hellway', player), player))
set_rule(world.get_entrance('Thieves Hellway Crystal Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Thieves Hellway S Crystal', player), player))
set_rule(world.get_entrance('Ice Bomb Jump Ledge Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Ice Bomb Jump Ledge', player), player))
set_rule(world.get_entrance('Ice Bomb Jump Catwalk Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Ice Bomb Jump Catwalk', player), player))
set_rule(world.get_entrance('Ice Crystal Right Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Ice Crystal Right', player), player))
set_rule(world.get_entrance('Ice Crystal Left Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Ice Crystal Left', player), player))
set_rule(world.get_entrance('Mire Crystal Right Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Mire Crystal Right', player), player))
set_rule(world.get_entrance('Mire Crystal Mid Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Mire Crystal Mid', player), player))
set_rule(world.get_entrance('Mire Firesnake Skip Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Mire Firesnake Skip', player), player))
set_rule(world.get_entrance('Mire Antechamber Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('Mire Antechamber', player), player))
set_rule(world.get_entrance('GT Double Switch Orange Barrier', player), lambda state: state.can_reach_orange(world.get_region('GT Double Switch Entry', player), player))
set_rule(world.get_entrance('GT Double Switch Orange Barrier 2', player), lambda state: state.can_reach_orange(world.get_region('GT Double Switch Entry', player), player))
set_rule(world.get_entrance('GT Double Switch Orange Path', player), lambda state: state.can_reach_orange(world.get_region('GT Double Switch Switches', player), player))
set_rule(world.get_entrance('GT Double Switch Key Orange Path', player), lambda state: state.can_reach_orange(world.get_region('GT Double Switch Key Spot', player), player))
add_key_logic_rules(world, player)
# End of door rando rules.
add_rule(world.get_location('Sunken Treasure', player), lambda state: state.has('Open Floodgate', player))
set_rule(world.get_location('Ganon', player), lambda state: state.has_beam_sword(player) and state.has_fire_source(player) and state.has_crystals(world.crystals_needed_for_ganon[player], player)
and (state.has('Tempered Sword', player) or state.has('Golden Sword', player) or (state.has('Silver Arrows', player) and state.can_shoot_arrows(player)) or state.has('Lamp', player) or state.can_extend_magic(player, 12))) # need to light torch a sufficient amount of times
set_rule(world.get_entrance('Ganon Drop', player), lambda state: state.has_beam_sword(player)) # need to damage ganon to get tiles to drop
def default_rules(world, player):
# overworld requirements
set_rule(world.get_entrance('Kings Grave', player), lambda state: state.has_Boots(player))
set_rule(world.get_entrance('Kings Grave Outer Rocks', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Kings Grave Inner Rocks', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Kings Grave Mirror Spot', player), lambda state: state.has_Pearl(player) and state.has_Mirror(player))
# Caution: If king's grave is releaxed at all to account for reaching it via a two way cave's exit in insanity mode, then the bomb shop logic will need to be updated (that would involve create a small ledge-like Region for it)
set_rule(world.get_entrance('Bonk Fairy (Light)', player), lambda state: state.has_Boots(player))
set_rule(world.get_entrance('Bat Cave Drop Ledge', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Lumberjack Tree Tree', player), lambda state: state.has_Boots(player) and state.has('Beat Agahnim 1', player))
set_rule(world.get_entrance('Bonk Rock Cave', player), lambda state: state.has_Boots(player))
set_rule(world.get_entrance('Desert Palace Stairs', player), lambda state: state.has('Book of Mudora', player))
set_rule(world.get_entrance('Sanctuary Grave', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('20 Rupee Cave', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('50 Rupee Cave', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('Death Mountain Entrance Rock', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('Bumper Cave Entrance Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Flute Spot 1', player), lambda state: state.has('Ocarina', player))
set_rule(world.get_entrance('Lake Hylia Central Island Teleporter', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Dark Desert Teleporter', player), lambda state: state.has('Ocarina', player) and state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('East Hyrule Teleporter', player), lambda state: state.has('Hammer', player) and state.can_lift_rocks(player) and state.has_Pearl(player)) # bunny cannot use hammer
set_rule(world.get_entrance('South Hyrule Teleporter', player), lambda state: state.has('Hammer', player) and state.can_lift_rocks(player) and state.has_Pearl(player)) # bunny cannot use hammer
set_rule(world.get_entrance('Kakariko Teleporter', player), lambda state: ((state.has('Hammer', player) and state.can_lift_rocks(player)) or state.can_lift_heavy_rocks(player)) and state.has_Pearl(player)) # bunny cannot lift bushes
set_rule(world.get_location('Flute Spot', player), lambda state: state.has('Shovel', player))
set_rule(world.get_location('Zora\'s Ledge', player), lambda state: state.has('Flippers', player))
set_rule(world.get_entrance('Waterfall of Wishing', player), lambda state: state.has('Flippers', player)) # can be fake flippered into, but is in weird state inside that might prevent you from doing things. Can be improved in future Todo
set_rule(world.get_location('Frog', player), lambda state: state.can_lift_heavy_rocks(player)) # will get automatic moon pearl requirement
set_rule(world.get_location('Potion Shop', player), lambda state: state.has('Mushroom', player))
set_rule(world.get_entrance('Desert Palace Entrance (North) Rocks', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('Desert Ledge Return Rocks', player), lambda state: state.can_lift_rocks(player)) # should we decide to place something that is not a dungeon end up there at some point
set_rule(world.get_entrance('Checkerboard Cave', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('Agahnims Tower', player), lambda state: state.has('Cape', player) or state.has_beam_sword(player) or state.has('Beat Agahnim 1', player)) # barrier gets removed after killing agahnim, relevant for entrance shuffle
set_rule(world.get_entrance('Top of Pyramid', player), lambda state: state.has('Beat Agahnim 1', player))
set_rule(world.get_entrance('Old Man Cave Exit (West)', player), lambda state: False) # drop cannot be climbed up
set_rule(world.get_entrance('Broken Bridge (West)', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Broken Bridge (East)', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('East Death Mountain Teleporter', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Fairy Ascension Rocks', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Paradox Cave Push Block Reverse', player), lambda state: state.has('Mirror', player)) # can erase block
set_rule(world.get_entrance('Death Mountain (Top)', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Turtle Rock Teleporter', player), lambda state: state.can_lift_heavy_rocks(player) and state.has('Hammer', player))
set_rule(world.get_entrance('East Death Mountain (Top)', player), lambda state: state.has('Hammer', player))
set_rule(world.get_location('Catfish', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('Northeast Dark World Broken Bridge Pass', player), lambda state: state.has_Pearl(player) and (state.can_lift_rocks(player) or state.has('Hammer', player) or state.has('Flippers', player)))
set_rule(world.get_entrance('East Dark World Broken Bridge Pass', player), lambda state: state.has_Pearl(player) and (state.can_lift_rocks(player) or state.has('Hammer', player)))
set_rule(world.get_entrance('South Dark World Bridge', player), lambda state: state.has('Hammer', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Bonk Fairy (Dark)', player), lambda state: state.has_Pearl(player) and state.has_Boots(player))
set_rule(world.get_entrance('West Dark World Gap', player), lambda state: state.has_Pearl(player) and state.has('Hookshot', player))
set_rule(world.get_entrance('Palace of Darkness', player), lambda state: state.has_Pearl(player)) # kiki needs pearl
set_rule(world.get_entrance('Hyrule Castle Ledge Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Hyrule Castle Main Gate', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Dark Lake Hylia Drop (East)', player), lambda state: (state.has_Pearl(player) and state.has('Flippers', player) or state.has_Mirror(player))) # Overworld Bunny Revival
set_rule(world.get_location('Bombos Tablet', player), lambda state: state.has('Book of Mudora', player) and state.has_beam_sword(player) and state.has_Mirror(player))
set_rule(world.get_entrance('Dark Lake Hylia Drop (South)', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player)) # ToDo any fake flipper set up?
set_rule(world.get_entrance('Dark Lake Hylia Ledge Fairy', player), lambda state: state.has_Pearl(player)) # bomb required
set_rule(world.get_entrance('Dark Lake Hylia Ledge Spike Cave', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Dark Lake Hylia Teleporter', player), lambda state: state.has_Pearl(player) and (state.has('Hammer', player) or state.can_lift_rocks(player))) # Fake Flippers
set_rule(world.get_entrance('Village of Outcasts Heavy Rock', player), lambda state: state.has_Pearl(player) and state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Hype Cave', player), lambda state: state.has_Pearl(player)) # bomb required
set_rule(world.get_entrance('Brewery', player), lambda state: state.has_Pearl(player)) # bomb required
set_rule(world.get_entrance('Thieves Town', player), lambda state: state.has_Pearl(player)) # bunny cannot pull
set_rule(world.get_entrance('Skull Woods First Section Hole (North)', player), lambda state: state.has_Pearl(player)) # bunny cannot lift bush
set_rule(world.get_entrance('Skull Woods Second Section Hole', player), lambda state: state.has_Pearl(player)) # bunny cannot lift bush
set_rule(world.get_entrance('Maze Race Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Cave 45 Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('East Dark World Bridge', player), lambda state: state.has_Pearl(player) and state.has('Hammer', player))
set_rule(world.get_entrance('Lake Hylia Island Mirror Spot', player), lambda state: state.has_Pearl(player) and state.has_Mirror(player) and state.has('Flippers', player))
set_rule(world.get_entrance('Lake Hylia Central Island Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('East Dark World River Pier', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player)) # ToDo any fake flipper set up?
set_rule(world.get_entrance('Graveyard Ledge Mirror Spot', player), lambda state: state.has_Pearl(player) and state.has_Mirror(player))
set_rule(world.get_entrance('Bumper Cave Entrance Rock', player), lambda state: state.has_Pearl(player) and state.can_lift_rocks(player))
set_rule(world.get_entrance('Bumper Cave Ledge Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Bat Cave Drop Ledge Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Dark World Hammer Peg Cave', player), lambda state: state.has_Pearl(player) and state.has('Hammer', player))
set_rule(world.get_entrance('Village of Outcasts Eastern Rocks', player), lambda state: state.has_Pearl(player) and state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Peg Area Rocks', player), lambda state: state.has_Pearl(player) and state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Village of Outcasts Pegs', player), lambda state: state.has_Pearl(player) and state.has('Hammer', player))
set_rule(world.get_entrance('Grassy Lawn Pegs', player), lambda state: state.has_Pearl(player) and state.has('Hammer', player))
set_rule(world.get_entrance('Bumper Cave Exit (Top)', player), lambda state: state.has('Cape', player))
set_rule(world.get_entrance('Bumper Cave Exit (Bottom)', player), lambda state: state.has('Cape', player) or state.has('Hookshot', player))
set_rule(world.get_entrance('Skull Woods Final Section', player), lambda state: state.has('Fire Rod', player) and state.has_Pearl(player)) # bunny cannot use fire rod
set_rule(world.get_entrance('Misery Mire', player), lambda state: state.has_Pearl(player) and state.has_sword(player) and state.has_misery_mire_medallion(player)) # sword required to cast magic (!)
set_rule(world.get_entrance('Desert Ledge (Northeast) Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Desert Ledge Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Desert Palace Stairs Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Desert Palace Entrance (North) Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Spectacle Rock Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Hookshot Cave', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('East Death Mountain (Top) Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Mimic Cave Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Spiral Cave Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Fairy Ascension Mirror Spot', player), lambda state: state.has_Mirror(player) and state.has_Pearl(player)) # need to lift flowers
set_rule(world.get_entrance('Isolated Ledge Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Superbunny Cave Exit (Bottom)', player), lambda state: False) # Cannot get to bottom exit from top. Just exists for shuffling
set_rule(world.get_entrance('Floating Island Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Turtle Rock', player), lambda state: state.has_Pearl(player) and state.has_sword(player) and state.has_turtle_rock_medallion(player) and state.can_reach('Turtle Rock (Top)', 'Region', player)) # sword required to cast magic (!)
set_rule(world.get_entrance('Pyramid Hole', player), lambda state: state.has('Beat Agahnim 2', player) or world.open_pyramid[player])
set_rule(world.get_entrance('Ganons Tower', player), lambda state: False) # This is a safety for the TR function below to not require GT entrance in its key logic.
if world.swords[player] == 'swordless':
swordless_rules(world, player)
set_rule(world.get_entrance('Ganons Tower', player), lambda state: state.has_crystals(world.crystals_needed_for_gt[player], player))
def inverted_rules(world, player):
# s&q regions. link's house entrance is set to true so the filler knows the chest inside can always be reached
set_rule(world.get_entrance('Castle Ledge S&Q', player), lambda state: state.has_Mirror(player) and state.has('Beat Agahnim 1', player))
# overworld requirements
set_rule(world.get_location('Maze Race', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Mini Moldorm Cave', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Light Hype Fairy', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Potion Shop Pier', player), lambda state: state.has('Flippers', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Light World Pier', player), lambda state: state.has('Flippers', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Kings Grave', player), lambda state: state.has_Boots(player) and state.can_lift_heavy_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Kings Grave Outer Rocks', player), lambda state: state.can_lift_heavy_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Kings Grave Inner Rocks', player), lambda state: state.can_lift_heavy_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Potion Shop Inner Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Potion Shop Outer Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Potion Shop Outer Rock', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Potion Shop Inner Rock', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Graveyard Cave Inner Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Graveyard Cave Outer Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Secret Passage Inner Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Secret Passage Outer Bushes', player), lambda state: state.has_Pearl(player))
# Caution: If king's grave is releaxed at all to account for reaching it via a two way cave's exit in insanity mode, then the bomb shop logic will need to be updated (that would involve create a small ledge-like Region for it)
set_rule(world.get_entrance('Bonk Fairy (Light)', player), lambda state: state.has_Boots(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Bat Cave Drop Ledge', player), lambda state: state.has('Hammer', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Lumberjack Tree Tree', player), lambda state: state.has_Boots(player) and state.has_Pearl(player) and state.has('Beat Agahnim 1', player))
set_rule(world.get_entrance('Bonk Rock Cave', player), lambda state: state.has_Boots(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Desert Palace Stairs', player), lambda state: state.has('Book of Mudora', player)) # bunny can use book
set_rule(world.get_entrance('Sanctuary Grave', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('20 Rupee Cave', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('50 Rupee Cave', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Death Mountain Entrance Rock', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Bumper Cave Entrance Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Lake Hylia Central Island Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Dark Lake Hylia Central Island Teleporter', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Dark Desert Teleporter', player), lambda state: state.can_flute(player) and state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('East Dark World Teleporter', player), lambda state: state.has('Hammer', player) and state.can_lift_rocks(player) and state.has_Pearl(player)) # bunny cannot use hammer
set_rule(world.get_entrance('South Dark World Teleporter', player), lambda state: state.has('Hammer', player) and state.can_lift_rocks(player) and state.has_Pearl(player)) # bunny cannot use hammer
set_rule(world.get_entrance('West Dark World Teleporter', player), lambda state: ((state.has('Hammer', player) and state.can_lift_rocks(player)) or state.can_lift_heavy_rocks(player)) and state.has_Pearl(player))
set_rule(world.get_location('Flute Spot', player), lambda state: state.has('Shovel', player) and state.has_Pearl(player))
set_rule(world.get_location('Zora\'s Ledge', player), lambda state: state.has('Flippers', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Waterfall of Wishing', player), lambda state: state.has('Flippers', player) and state.has_Pearl(player)) # can be fake flippered into, but is in weird state inside that might prevent you from doing things. Can be improved in future Todo
set_rule(world.get_location('Frog', player), lambda state: state.can_lift_heavy_rocks(player) or (state.can_reach('Light World', 'Region', player) and state.has_Mirror(player)))
set_rule(world.get_location('Mushroom', player), lambda state: state.has_Pearl(player)) # need pearl to pick up bushes
set_rule(world.get_entrance('Bush Covered Lawn Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Bush Covered Lawn Inner Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Bush Covered Lawn Outer Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Bomb Hut Inner Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Bomb Hut Outer Bushes', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('North Fairy Cave Drop', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Lost Woods Hideout Drop', player), lambda state: state.has_Pearl(player))
set_rule(world.get_location('Potion Shop', player), lambda state: state.has('Mushroom', player) and (state.can_reach('Potion Shop Area', 'Region', player))) # new inverted region, need pearl for bushes or access to potion shop door/waterfall fairy
set_rule(world.get_entrance('Desert Palace Entrance (North) Rocks', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Desert Ledge Return Rocks', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player)) # should we decide to place something that is not a dungeon end up there at some point
set_rule(world.get_entrance('Checkerboard Cave', player), lambda state: state.can_lift_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Hyrule Castle Secret Entrance Drop', player), lambda state: state.has_Pearl(player))
set_rule(world.get_entrance('Old Man Cave Exit (West)', player), lambda state: False) # drop cannot be climbed up
set_rule(world.get_entrance('Broken Bridge (West)', player), lambda state: state.has('Hookshot', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Broken Bridge (East)', player), lambda state: state.has('Hookshot', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Dark Death Mountain Teleporter (East Bottom)', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Fairy Ascension Rocks', player), lambda state: state.can_lift_heavy_rocks(player) and state.has_Pearl(player))
set_rule(world.get_entrance('Paradox Cave Push Block Reverse', player), lambda state: state.has('Mirror', player)) # can erase block
set_rule(world.get_entrance('Death Mountain (Top)', player), lambda state: state.has('Hammer', player) and state.has_Pearl(player))
set_rule(world.get_entrance('Dark Death Mountain Teleporter (East)', player), lambda state: state.can_lift_heavy_rocks(player) and state.has('Hammer', player) and state.has_Pearl(player)) # bunny cannot use hammer
set_rule(world.get_entrance('East Death Mountain (Top)', player), lambda state: state.has('Hammer', player) and state.has_Pearl(player)) # bunny can not use hammer
set_rule(world.get_location('Catfish', player), lambda state: state.can_lift_rocks(player) or (state.has('Flippers', player) and state.has_Mirror(player) and state.has_Pearl(player) and state.can_reach('Light World', 'Region', player)))
set_rule(world.get_entrance('Northeast Dark World Broken Bridge Pass', player), lambda state: ((state.can_lift_rocks(player) or state.has('Hammer', player)) or state.has('Flippers', player)))
set_rule(world.get_entrance('East Dark World Broken Bridge Pass', player), lambda state: (state.can_lift_rocks(player) or state.has('Hammer', player)))
set_rule(world.get_entrance('South Dark World Bridge', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Bonk Fairy (Dark)', player), lambda state: state.has_Boots(player))
set_rule(world.get_entrance('West Dark World Gap', player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Dark Lake Hylia Drop (East)', player), lambda state: state.has('Flippers', player))
set_rule(world.get_location('Bombos Tablet', player), lambda state: state.has('Book of Mudora', player) and state.has_beam_sword(player))
set_rule(world.get_entrance('Dark Lake Hylia Drop (South)', player), lambda state: state.has('Flippers', player)) # ToDo any fake flipper set up?
set_rule(world.get_entrance('Dark Lake Hylia Ledge Pier', player), lambda state: state.has('Flippers', player))
set_rule(world.get_entrance('Dark Lake Hylia Ledge Spike Cave', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('Dark Lake Hylia Teleporter', player), lambda state: state.has('Flippers', player) and (state.has('Hammer', player) or state.can_lift_rocks(player))) # Fake Flippers
set_rule(world.get_entrance('Village of Outcasts Heavy Rock', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('East Dark World Bridge', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Lake Hylia Central Island Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('East Dark World River Pier', player), lambda state: state.has('Flippers', player)) # ToDo any fake flipper set up? (Qirn Jump)
set_rule(world.get_entrance('Bumper Cave Entrance Rock', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('Bumper Cave Ledge Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Hammer Peg Area Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Dark World Hammer Peg Cave', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Village of Outcasts Eastern Rocks', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Peg Area Rocks', player), lambda state: state.can_lift_heavy_rocks(player))
set_rule(world.get_entrance('Village of Outcasts Pegs', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Grassy Lawn Pegs', player), lambda state: state.has('Hammer', player))
set_rule(world.get_entrance('Bumper Cave Exit (Top)', player), lambda state: state.has('Cape', player))
set_rule(world.get_entrance('Bumper Cave Exit (Bottom)', player), lambda state: state.has('Cape', player) or state.has('Hookshot', player))
set_rule(world.get_entrance('Skull Woods Final Section', player), lambda state: state.has('Fire Rod', player))
set_rule(world.get_entrance('Misery Mire', player), lambda state: state.has_sword(player) and state.has_misery_mire_medallion(player)) # sword required to cast magic (!)
set_rule(world.get_entrance('Hookshot Cave', player), lambda state: state.can_lift_rocks(player))
set_rule(world.get_entrance('East Death Mountain Mirror Spot (Top)', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Death Mountain (Top) Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('East Death Mountain Mirror Spot (Bottom)', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Dark Death Mountain Ledge Mirror Spot (East)', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Dark Death Mountain Ledge Mirror Spot (West)', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Laser Bridge Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Superbunny Cave Exit (Bottom)', player), lambda state: False) # Cannot get to bottom exit from top. Just exists for shuffling
set_rule(world.get_entrance('Floating Island Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Turtle Rock', player), lambda state: state.has_sword(player) and state.has_turtle_rock_medallion(player) and state.can_reach('Turtle Rock (Top)', 'Region', player)) # sword required to cast magic (!)
# new inverted spots
set_rule(world.get_entrance('Post Aga Teleporter', player), lambda state: state.has('Beat Agahnim 1', player))
set_rule(world.get_entrance('Mire Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Desert Palace Stairs Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Death Mountain Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('East Dark World Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('West Dark World Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('South Dark World Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Northeast Dark World Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Potion Shop Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Shopping Mall Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Maze Race Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Desert Palace North Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Death Mountain (Top) Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Graveyard Cave Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Bomb Hut Mirror Spot', player), lambda state: state.has_Mirror(player))
set_rule(world.get_entrance('Skull Woods Mirror Spot', player), lambda state: state.has_Mirror(player))
# inverted flute spots
set_rule(world.get_entrance('DDM Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('NEDW Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('WDW Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('SDW Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('EDW Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('DLHL Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('DD Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('EDDM Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('Dark Grassy Lawn Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('Hammer Peg Area Flute', player), lambda state: state.can_flute(player))
set_rule(world.get_entrance('Inverted Pyramid Hole', player), lambda state: state.has('Beat Agahnim 2', player) or world.open_pyramid[player])
set_rule(world.get_entrance('Inverted Ganons Tower', player), lambda state: False) # This is a safety for the TR function below to not require GT entrance in its key logic.
if world.swords[player] == 'swordless':
swordless_rules(world, player)
set_rule(world.get_entrance('Inverted Ganons Tower', player), lambda state: state.has_crystals(world.crystals_needed_for_gt[player], player))
def no_glitches_rules(world, player):
if world.mode[player] != 'inverted':
add_rule(world.get_entrance('Zoras River', player), lambda state: state.has('Flippers', player) or state.can_lift_rocks(player))
add_rule(world.get_entrance('Lake Hylia Central Island Pier', player), lambda state: state.has('Flippers', player)) # can be fake flippered to
add_rule(world.get_entrance('Hobo Bridge', player), lambda state: state.has('Flippers', player))
add_rule(world.get_entrance('Dark Lake Hylia Drop (East)', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player))
add_rule(world.get_entrance('Dark Lake Hylia Teleporter', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player) and (state.has('Hammer', player) or state.can_lift_rocks(player)))
add_rule(world.get_entrance('Dark Lake Hylia Ledge Drop', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player))
else:
add_rule(world.get_entrance('Zoras River', player), lambda state: state.has_Pearl(player) and (state.has('Flippers', player) or state.can_lift_rocks(player)))
add_rule(world.get_entrance('Lake Hylia Central Island Pier', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player)) # can be fake flippered to
add_rule(world.get_entrance('Lake Hylia Island', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player))
add_rule(world.get_entrance('Hobo Bridge', player), lambda state: state.has_Pearl(player) and state.has('Flippers', player))
add_rule(world.get_entrance('Dark Lake Hylia Drop (East)', player), lambda state: state.has('Flippers', player))
add_rule(world.get_entrance('Dark Lake Hylia Teleporter', player), lambda state: state.has('Flippers', player) and (state.has('Hammer', player) or state.can_lift_rocks(player)))
add_rule(world.get_entrance('Dark Lake Hylia Ledge Drop', player), lambda state: state.has('Flippers', player))
add_rule(world.get_entrance('East Dark World Pier', player), lambda state: state.has('Flippers', player))
# todo: move some dungeon rules to no glictes logic - see these for examples
# add_rule(world.get_entrance('Ganons Tower (Hookshot Room)', player), lambda state: state.has('Hookshot', player) or state.has_Boots(player))
# add_rule(world.get_entrance('Ganons Tower (Double Switch Room)', player), lambda state: state.has('Hookshot', player))
# DMs_room_chests = ['Ganons Tower - DMs Room - Top Left', 'Ganons Tower - DMs Room - Top Right', 'Ganons Tower - DMs Room - Bottom Left', 'Ganons Tower - DMs Room - Bottom Right']
# for location in DMs_room_chests:
# add_rule(world.get_location(location, player), lambda state: state.has('Hookshot', player))
set_rule(world.get_entrance('Paradox Cave Push Block Reverse', player), lambda state: False) # no glitches does not require block override
set_rule(world.get_entrance('Paradox Cave Bomb Jump', player), lambda state: False)
# Light cones in standard depend on which world we actually are in, not which one the location would normally be
# We add Lamp requirements only to those locations which lie in the dark world (or everything if open
DW_Entrances = ['Bumper Cave (Bottom)', 'Superbunny Cave (Top)', 'Superbunny Cave (Bottom)', 'Hookshot Cave', 'Bumper Cave (Top)', 'Hookshot Cave Back Entrance', 'Dark Death Mountain Ledge (East)',
'Turtle Rock Isolated Ledge Entrance', 'Thieves Town', 'Skull Woods Final Section', 'Ice Palace', 'Misery Mire', 'Palace of Darkness', 'Swamp Palace', 'Turtle Rock', 'Dark Death Mountain Ledge (West)']
def check_is_dark_world(region):
for entrance in region.entrances:
if entrance.name in DW_Entrances:
return True
return False
def add_conditional_lamp(spot, region, spottype='Location'):
if spottype == 'Location':
spot = world.get_location(spot, player)
else:
spot = world.get_entrance(spot, player)
if (not world.dark_world_light_cone and check_is_dark_world(world.get_region(region, player))) or (not world.light_world_light_cone and not check_is_dark_world(world.get_region(region, player))):
add_lamp_requirement(spot, player)
dark_rooms = {
'TR Dark Ride': {'sewer': False, 'entrances': ['TR Dark Ride Up Stairs', 'TR Dark Ride SW'], 'locations': []},
'Mire Dark Shooters': {'sewer': False, 'entrances': ['Mire Dark Shooters Up Stairs', 'Mire Dark Shooters SW', 'Mire Dark Shooters SE'], 'locations': []},
'Mire Key Rupees': {'sewer': False, 'entrances': ['Mire Key Rupees NE'], 'locations': []},
'Mire Block X': {'sewer': False, 'entrances': ['Mire Block X NW', 'Mire Block X WS'], 'locations': []},
'Mire Tall Dark and Roomy': {'sewer': False, 'entrances': ['Mire Tall Dark and Roomy ES', 'Mire Tall Dark and Roomy WS', 'Mire Tall Dark and Roomy WN'], 'locations': []},
'Mire Crystal Right': {'sewer': False, 'entrances': ['Mire Crystal Right ES'], 'locations': []},
'Mire Crystal Mid': {'sewer': False, 'entrances': ['Mire Crystal Mid NW'], 'locations': []},
'Mire Crystal Left': {'sewer': False, 'entrances': ['Mire Crystal Left WS'], 'locations': []},
'Mire Crystal Top': {'sewer': False, 'entrances': ['Mire Crystal Top SW'], 'locations': []},
'Mire Shooter Rupees': {'sewer': False, 'entrances': ['Mire Shooter Rupees EN'], 'locations': []},
'PoD Dark Alley': {'sewer': False, 'entrances': ['PoD Dark Alley NE'], 'locations': []},
'PoD Callback': {'sewer': False, 'entrances': ['PoD Callback WS', 'PoD Callback Warp'], 'locations': []},
'PoD Turtle Party': {'sewer': False, 'entrances': ['PoD Turtle Party ES', 'PoD Turtle Party NW'], 'locations': []},
'PoD Lonely Turtle': {'sewer': False, 'entrances': ['PoD Lonely Turtle SW', 'PoD Lonely Turtle EN'], 'locations': []},
'PoD Dark Pegs': {'sewer': False, 'entrances': ['PoD Dark Pegs Up Ladder', 'PoD Dark Pegs WN'], 'locations': []},
'PoD Dark Basement': {'sewer': False, 'entrances': ['PoD Dark Basement W Up Stairs', 'PoD Dark Basement E Up Stairs'], 'locations': ['Palace of Darkness - Dark Basement - Left', 'Palace of Darkness - Dark Basement - Right']},
'PoD Dark Maze': {'sewer': False, 'entrances': ['PoD Dark Maze EN', 'PoD Dark Maze E'], 'locations': ['Palace of Darkness - Dark Maze - Top', 'Palace of Darkness - Dark Maze - Bottom']},
'Eastern Dark Square': {'sewer': False, 'entrances': ['Eastern Dark Square NW', 'Eastern Dark Square Key Door WN', 'Eastern Dark Square EN'], 'locations': []},
'Eastern Dark Pots': {'sewer': False, 'entrances': ['Eastern Dark Pots WN'], 'locations': ['Eastern Palace - Dark Square Pot Key']},
'Eastern Darkness': {'sewer': False, 'entrances': ['Eastern Darkness S', 'Eastern Darkness Up Stairs', 'Eastern Darkness NE'], 'locations': ['Eastern Palace - Dark Eyegore Key Drop']},
'Eastern Rupees': {'sewer': False, 'entrances': ['Eastern Rupees SE'], 'locations': []},
'Tower Lone Statue': {'sewer': False, 'entrances': ['Tower Lone Statue Down Stairs', 'Tower Lone Statue WN'], 'locations': []},
'Tower Dark Maze': {'sewer': False, 'entrances': ['Tower Dark Maze EN', 'Tower Dark Maze ES'], 'locations': ['Castle Tower - Dark Maze']},
'Tower Dark Chargers': {'sewer': False, 'entrances': ['Tower Dark Chargers WS', 'Tower Dark Chargers Up Stairs'], 'locations': []},
'Tower Dual Statues': {'sewer': False, 'entrances': ['Tower Dual Statues Down Stairs', 'Tower Dual Statues WS'], 'locations': []},
'Tower Dark Pits': {'sewer': False, 'entrances': ['Tower Dark Pits ES', 'Tower Dark Pits EN'], 'locations': []},
'Tower Dark Archers': {'sewer': False, 'entrances': ['Tower Dark Archers WN', 'Tower Dark Archers Up Stairs'], 'locations': ['Castle Tower - Dark Archer Key Drop']},
'Sewers Dark Cross': {'sewer': True, 'entrances': ['Sewers Dark Cross Key Door N', 'Sewers Dark Cross South Stairs'], 'locations': ['Sewers - Dark Cross']},
'Sewers Behind Tapestry': {'sewer': True, 'entrances': ['Sewers Behind Tapestry S', 'Sewers Behind Tapestry Down Stairs'], 'locations': []},
'Sewers Rope Room': {'sewer': True, 'entrances': ['Sewers Rope Room Up Stairs', 'Sewers Rope Room North Stairs'], 'locations': []},
'Sewers Water': {'sewer': True, 'entrances': ['Sewers Water S', 'Sewers Water W'], 'locations': []},
'Sewers Key Rat': {'sewer': True, 'entrances': ['Sewers Key Rat E', 'Sewers Key Rat Key Door N'], 'locations': ['Hyrule Castle - Key Rat Key Drop']},
}
dark_debug_set = set()
for region, info in dark_rooms.items():
is_dark = False
if not world.sewer_light_cone[player]:
is_dark = True
elif world.doorShuffle[player] != 'crossed' and not info['sewer']:
is_dark = True
elif world.doorShuffle[player] == 'crossed':
sewer_builder = world.dungeon_layouts[player]['Hyrule Castle']
is_dark = region not in sewer_builder.master_sector.region_set()
if is_dark:
dark_debug_set.add(region)
for ent in info['entrances']:
add_conditional_lamp(ent, region, 'Entrance')
for loc in info['locations']:
add_conditional_lamp(loc, region, 'Location')
logging.getLogger('').debug('Non Dark Regions: ' + ', '.join(set(dark_rooms.keys()).difference(dark_debug_set)))
add_conditional_lamp('Old Man', 'Old Man Cave', 'Location')
add_conditional_lamp('Old Man Cave Exit (East)', 'Old Man Cave', 'Entrance')
add_conditional_lamp('Death Mountain Return Cave Exit (East)', 'Death Mountain Return Cave', 'Entrance')
add_conditional_lamp('Death Mountain Return Cave Exit (West)', 'Death Mountain Return Cave', 'Entrance')
add_conditional_lamp('Old Man House Front to Back', 'Old Man House', 'Entrance')
add_conditional_lamp('Old Man House Back to Front', 'Old Man House', 'Entrance')
def open_rules(world, player):
# softlock protection as you can reach the sewers small key door with a guard drop key
set_rule(world.get_location('Hyrule Castle - Boomerang Chest', player), lambda state: state.has_key('Small Key (Escape)', player))
set_rule(world.get_location('Hyrule Castle - Zelda\'s Chest', player), lambda state: state.has_key('Small Key (Escape)', player))
def swordless_rules(world, player):
set_rule(world.get_entrance('Tower Altar NW', player), lambda state: True)
set_rule(world.get_entrance('Skull Vines NW', player), lambda state: True)
set_rule(world.get_entrance('Ice Lobby WS', player), lambda state: state.has('Fire Rod', player) or state.has('Bombos', player))
set_rule(world.get_location('Ice Palace - Freezor Chest', player), lambda state: state.has('Fire Rod', player) or state.has('Bombos', player))
set_rule(world.get_location('Ether Tablet', player), lambda state: state.has('Book of Mudora', player) and state.has('Hammer', player))
set_rule(world.get_location('Ganon', player), lambda state: state.has('Hammer', player) and state.has_fire_source(player) and state.has('Silver Arrows', player) and state.can_shoot_arrows(player) and state.has_crystals(world.crystals_needed_for_ganon[player], player))
set_rule(world.get_entrance('Ganon Drop', player), lambda state: state.has('Hammer', player)) # need to damage ganon to get tiles to drop
if world.mode[player] != 'inverted':
set_rule(world.get_entrance('Agahnims Tower', player), lambda state: state.has('Cape', player) or state.has('Hammer', player) or state.has('Beat Agahnim 1', player)) # barrier gets removed after killing agahnim, relevant for entrance shuffle
set_rule(world.get_entrance('Turtle Rock', player), lambda state: state.has_Pearl(player) and state.has_turtle_rock_medallion(player) and state.can_reach('Turtle Rock (Top)', 'Region', player)) # sword not required to use medallion for opening in swordless (!)
set_rule(world.get_entrance('Misery Mire', player), lambda state: state.has_Pearl(player) and state.has_misery_mire_medallion(player)) # sword not required to use medallion for opening in swordless (!)
set_rule(world.get_location('Bombos Tablet', player), lambda state: state.has('Book of Mudora', player) and state.has('Hammer', player) and state.has_Mirror(player))
else:
# only need ddm access for aga tower in inverted
set_rule(world.get_entrance('Turtle Rock', player), lambda state: state.has_turtle_rock_medallion(player) and state.can_reach('Turtle Rock (Top)', 'Region', player)) # sword not required to use medallion for opening in swordless (!)
set_rule(world.get_entrance('Misery Mire', player), lambda state: state.has_misery_mire_medallion(player)) # sword not required to use medallion for opening in swordless (!)
set_rule(world.get_location('Bombos Tablet', player), lambda state: state.has('Book of Mudora', player) and state.has('Hammer', player))
std_kill_rooms = {
'Hyrule Dungeon Armory Main': ['Hyrule Dungeon Armory S'],
'Hyrule Dungeon Armory Boomerang': ['Hyrule Dungeon Armory Boomerang WS'],
'Eastern Stalfos Spawn': ['Eastern Stalfos Spawn ES', 'Eastern Stalfos Spawn NW'],
'Desert Compass Room': ['Desert Compass NW'],
'Desert Four Statues': ['Desert Four Statues NW', 'Desert Four Statues ES'],
'Hera Beetles': ['Hera Beetles WS'],
'Tower Gold Knights': ['Tower Gold Knights SW', 'Tower Gold Knights EN'],
'Tower Dark Archers': ['Tower Dark Archers WN'],
'Tower Red Spears': ['Tower Red Spears WN'],
'Tower Red Guards': ['Tower Red Guards EN', 'Tower Red Guards SW'],
'Tower Circle of Pots': ['Tower Circle of Pots NW'],
'PoD Turtle Party': ['PoD Turtle Party ES', 'PoD Turtle Party NW'], # todo: hammer req. in main rules
'Thieves Basement Block': ['Thieves Basement Block WN'],
'Ice Stalfos Hint': ['Ice Stalfos Hint SE'],
'Ice Pengator Trap': ['Ice Pengator Trap NE'],
'Mire 2': ['Mire 2 NE'],
'Mire Cross': ['Mire Cross ES'],
'TR Twin Pokeys': ['TR Twin Pokeys EN', 'TR Twin Pokeys SW'],
'GT Petting Zoo': ['GT Petting Zoo SE'],
'GT DMs Room': ['GT DMs Room SW'],
'GT Gauntlet 1': ['GT Gauntlet 1 WN'],
'GT Gauntlet 2': ['GT Gauntlet 2 EN', 'GT Gauntlet 2 SW'],
'GT Gauntlet 3': ['GT Gauntlet 3 NW', 'GT Gauntlet 3 SW'],
'GT Gauntlet 4': ['GT Gauntlet 4 NW', 'GT Gauntlet 4 SW'],
'GT Gauntlet 5': ['GT Gauntlet 5 NW', 'GT Gauntlet 5 WS'],
'GT Wizzrobes 1': ['GT Wizzrobes 1 SW'],
'GT Wizzrobes 2': ['GT Wizzrobes 2 SE', 'GT Wizzrobes 2 NE']
} # all trap rooms?
def add_connection(parent_name, target_name, entrance_name, world, player):
parent = world.get_region(parent_name, player)
target = world.get_region(target_name, player)
connection = Entrance(player, entrance_name, parent)
parent.exits.append(connection)
connection.connect(target)
def standard_rules(world, player):
add_connection('Menu', 'Hyrule Castle Secret Entrance', 'Uncle S&Q', world, player)
world.get_entrance('Uncle S&Q', player).hide_path = True
set_rule(world.get_entrance('Links House S&Q', player), lambda state: state.can_reach('Sanctuary', 'Region', player))
set_rule(world.get_entrance('Sanctuary S&Q', player), lambda state: state.can_reach('Sanctuary', 'Region', player))
# these are because of rails
if world.shuffle[player] != 'vanilla':
set_rule(world.get_entrance('Hyrule Castle Exit (East)', player), lambda state: state.has('Zelda Delivered', player))
set_rule(world.get_entrance('Hyrule Castle Exit (West)', player), lambda state: state.has('Zelda Delivered', player))
# too restrictive for crossed?
def uncle_item_rule(item):
copy_state = CollectionState(world)
copy_state.collect(item)
copy_state.sweep_for_events()
return copy_state.has('Zelda Delivered', player)
def bomb_escape_rule():
loc = world.get_location("Link's Uncle", player)
return loc.item and loc.item.name == 'Bombs (10)'
def standard_escape_rule(state):
return state.can_kill_most_things(player) or bomb_escape_rule()
add_item_rule(world.get_location('Link\'s Uncle', player), uncle_item_rule)
# ensures the required weapon for escape lands on uncle (unless player has it pre-equipped)
for location in ['Link\'s House', 'Sanctuary', 'Sewers - Secret Room - Left', 'Sewers - Secret Room - Middle',
'Sewers - Secret Room - Right']:
add_rule(world.get_location(location, player), lambda state: standard_escape_rule(state))
add_rule(world.get_location('Secret Passage', player), lambda state: standard_escape_rule(state))
escape_builder = world.dungeon_layouts[player]['Hyrule Castle']
for region in escape_builder.master_sector.regions:
for loc in region.locations:
add_rule(loc, lambda state: standard_escape_rule(state))
if region.name in std_kill_rooms:
for ent in std_kill_rooms[region.name]:
add_rule(world.get_entrance(ent, player), lambda state: standard_escape_rule(state))
set_rule(world.get_location('Zelda Pickup', player), lambda state: state.has('Big Key (Escape)', player))
set_rule(world.get_entrance('Hyrule Castle Throne Room Tapestry', player), lambda state: state.has('Zelda Herself', player))
set_rule(world.get_entrance('Hyrule Castle Tapestry Backwards', player), lambda state: state.has('Zelda Herself', player))
def check_rule_list(state, r_list):
return True if len(r_list) <= 0 else r_list[0](state) and check_rule_list(state, r_list[1:])
rule_list, debug_path = find_rules_for_zelda_delivery(world, player)
set_rule(world.get_location('Zelda Drop Off', player), lambda state: state.has('Zelda Herself', player) and check_rule_list(state, rule_list))
for location in ['Mushroom', 'Bottle Merchant', 'Flute Spot', 'Sunken Treasure', 'Purple Chest']:
add_rule(world.get_location(location, player), lambda state: state.has('Zelda Delivered', player))
# Bonk Fairy (Light) is a notable omission in ER shuffles/Retro
for entrance in ['Blinds Hideout', 'Zoras River', 'Kings Grave Outer Rocks', 'Dam', 'Tavern North', 'Chicken House',
'Aginahs Cave', 'Sahasrahlas Hut', 'Kakariko Well Drop', 'Kakariko Well Cave', 'Blacksmiths Hut',
'Bat Cave Drop Ledge', 'Bat Cave Cave', 'Sick Kids House', 'Hobo Bridge',
'Lost Woods Hideout Drop', 'Lost Woods Hideout Stump', 'Lumberjack Tree Tree',
'Lumberjack Tree Cave', 'Mini Moldorm Cave', 'Ice Rod Cave', 'Lake Hylia Central Island Pier',
'Bonk Rock Cave', 'Library', 'Potion Shop', 'Two Brothers House (East)', 'Desert Palace Stairs',
'Eastern Palace', 'Master Sword Meadow', 'Sanctuary', 'Sanctuary Grave',
'Death Mountain Entrance Rock', 'Flute Spot 1', 'Dark Desert Teleporter', 'East Hyrule Teleporter',
'South Hyrule Teleporter', 'Kakariko Teleporter', 'Elder House (East)', 'Elder House (West)',
'North Fairy Cave', 'North Fairy Cave Drop', 'Lost Woods Gamble', 'Snitch Lady (East)',
'Snitch Lady (West)', 'Tavern (Front)', 'Bush Covered House', 'Light World Bomb Hut',
'Kakariko Shop', 'Long Fairy Cave', 'Good Bee Cave', '20 Rupee Cave', 'Cave Shop (Lake Hylia)',
'Waterfall of Wishing', 'Hyrule Castle Main Gate', '50 Rupee Cave',
'Fortune Teller (Light)', 'Lake Hylia Fairy', 'Light Hype Fairy', 'Desert Fairy',
'Lumberjack House', 'Lake Hylia Fortune Teller', 'Kakariko Gamble Game', 'Top of Pyramid']:
add_rule(world.get_entrance(entrance, player), lambda state: state.has('Zelda Delivered', player))
def find_rules_for_zelda_delivery(world, player):
# path rules for backtracking
start_region = world.get_region('Hyrule Dungeon Cellblock', player)
queue = deque([(start_region, [], [])])
visited = {start_region}
blank_state = CollectionState(world)
while len(queue) > 0:
region, path_rules, path = queue.popleft()
for ext in region.exits:
connect = ext.connected_region
if connect and connect.type == RegionType.Dungeon and connect not in visited:
rule = ext.access_rule
rule_list = list(path_rules)
next_path = list(path)
if not rule(blank_state):
rule_list.append(rule)
next_path.append(ext.name)
if connect.name == 'Sanctuary':
return rule_list, next_path
else:
visited.add(connect)
queue.append((connect, rule_list, next_path))
raise Exception('No path to Sanctuary found')
def set_big_bomb_rules(world, player):
# this is a mess
bombshop_entrance = world.get_region('Big Bomb Shop', player).entrances[0]
Normal_LW_entrances = ['Blinds Hideout',
'Bonk Fairy (Light)',
'Lake Hylia Fairy',
'Light Hype Fairy',
'Desert Fairy',
'Chicken House',
'Aginahs Cave',
'Sahasrahlas Hut',
'Cave Shop (Lake Hylia)',
'Blacksmiths Hut',
'Sick Kids House',
'Lost Woods Gamble',
'Fortune Teller (Light)',
'Snitch Lady (East)',
'Snitch Lady (West)',
'Bush Covered House',
'Tavern (Front)',
'Light World Bomb Hut',
'Kakariko Shop',
'Mini Moldorm Cave',
'Long Fairy Cave',
'Good Bee Cave',
'20 Rupee Cave',
'50 Rupee Cave',
'Ice Rod Cave',
'Bonk Rock Cave',
'Library',
'Potion Shop',
'Dam',
'Lumberjack House',
'Lake Hylia Fortune Teller',
'Eastern Palace',
'Kakariko Gamble Game',
'Kakariko Well Cave',
'Bat Cave Cave',
'Elder House (East)',
'Elder House (West)',
'North Fairy Cave',
'Lost Woods Hideout Stump',
'Lumberjack Tree Cave',
'Two Brothers House (East)',
'Sanctuary',
'Hyrule Castle Entrance (South)',
'Hyrule Castle Secret Entrance Stairs']
LW_walkable_entrances = ['Dark Lake Hylia Ledge Fairy',
'Dark Lake Hylia Ledge Spike Cave',
'Dark Lake Hylia Ledge Hint',
'Mire Shed',
'Dark Desert Hint',
'Dark Desert Fairy',
'Misery Mire']
Northern_DW_entrances = ['Brewery',
'C-Shaped House',
'Chest Game',
'Dark World Hammer Peg Cave',
'Red Shield Shop',
'Dark Sanctuary Hint',
'Fortune Teller (Dark)',
'Dark World Shop',
'Dark World Lumberjack Shop',
'Thieves Town',
'Skull Woods First Section Door',
'Skull Woods Second Section Door (East)']
Southern_DW_entrances = ['Hype Cave',
'Bonk Fairy (Dark)',
'Archery Game',
'Big Bomb Shop',
'Dark Lake Hylia Shop',
'Swamp Palace']
Isolated_DW_entrances = ['Spike Cave',
'Cave Shop (Dark Death Mountain)',
'Dark Death Mountain Fairy',
'Mimic Cave',
'Skull Woods Second Section Door (West)',
'Skull Woods Final Section',
'Ice Palace',
'Turtle Rock',
'Dark Death Mountain Ledge (West)',
'Dark Death Mountain Ledge (East)',
'Bumper Cave (Top)',
'Superbunny Cave (Top)',
'Superbunny Cave (Bottom)',
'Hookshot Cave',
'Ganons Tower',
'Turtle Rock Isolated Ledge Entrance',
'Hookshot Cave Back Entrance']
Isolated_LW_entrances = ['Capacity Upgrade',
'Tower of Hera',
'Death Mountain Return Cave (West)',
'Paradox Cave (Top)',
'Fairy Ascension Cave (Top)',
'Spiral Cave',
'Desert Palace Entrance (East)']
West_LW_DM_entrances = ['Old Man Cave (East)',
'Old Man House (Bottom)',
'Old Man House (Top)',
'Death Mountain Return Cave (East)',
'Spectacle Rock Cave Peak',
'Spectacle Rock Cave',
'Spectacle Rock Cave (Bottom)']
East_LW_DM_entrances = ['Paradox Cave (Bottom)',
'Paradox Cave (Middle)',
'Hookshot Fairy',
'Spiral Cave (Bottom)']
Mirror_from_SDW_entrances = ['Two Brothers House (West)',
'Cave 45']
Castle_ledge_entrances = ['Hyrule Castle Entrance (West)',
'Hyrule Castle Entrance (East)',
'Agahnims Tower']
Desert_mirrorable_ledge_entrances = ['Desert Palace Entrance (West)',
'Desert Palace Entrance (North)',
'Desert Palace Entrance (South)',
'Checkerboard Cave']
set_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.can_reach('East Dark World', 'Region', player) and state.can_reach('Big Bomb Shop', 'Region', player) and state.has('Crystal 5', player) and state.has('Crystal 6', player))
#crossing peg bridge starting from the southern dark world
def cross_peg_bridge(state):
return state.has('Hammer', player) and state.has_Pearl(player)
# returning via the eastern and southern teleporters needs the same items, so we use the southern teleporter for out routing.
# crossing preg bridge already requires hammer so we just add the gloves to the requirement
def southern_teleporter(state):
return state.can_lift_rocks(player) and cross_peg_bridge(state)
# the basic routes assume you can reach eastern light world with the bomb.
# you can then use the southern teleporter, or (if you have beaten Aga1) the hyrule castle gate warp
def basic_routes(state):
return southern_teleporter(state) or state.has('Beat Agahnim 1', player)
# Key for below abbreviations:
# P = pearl
# A = Aga1
# H = hammer
# M = Mirror
# G = Glove
if bombshop_entrance.name in Normal_LW_entrances:
#1. basic routes
#2. Can reach Eastern dark world some other way, mirror, get bomb, return to mirror spot, walk to pyramid: Needs mirror
# -> M or BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: basic_routes(state) or state.has_Mirror(player))
elif bombshop_entrance.name in LW_walkable_entrances:
#1. Mirror then basic routes
# -> M and BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has_Mirror(player) and basic_routes(state))
elif bombshop_entrance.name in Northern_DW_entrances:
#1. Mirror and basic routes
#2. Go to south DW and then cross peg bridge: Need Mitts and hammer and moon pearl
# -> (Mitts and CPB) or (M and BR)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.can_lift_heavy_rocks(player) and cross_peg_bridge(state)) or (state.has_Mirror(player) and basic_routes(state)))
elif bombshop_entrance.name == 'Bumper Cave (Bottom)':
#1. Mirror and Lift rock and basic_routes
#2. Mirror and Flute and basic routes (can make difference if accessed via insanity or w/ mirror from connector, and then via hyrule castle gate, because no gloves are needed in that case)
#3. Go to south DW and then cross peg bridge: Need Mitts and hammer and moon pearl
# -> (Mitts and CPB) or (((G or Flute) and M) and BR))
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.can_lift_heavy_rocks(player) and cross_peg_bridge(state)) or (((state.can_lift_rocks(player) or state.has('Ocarina', player)) and state.has_Mirror(player)) and basic_routes(state)))
elif bombshop_entrance.name in Southern_DW_entrances:
#1. Mirror and enter via gate: Need mirror and Aga1
#2. cross peg bridge: Need hammer and moon pearl
# -> CPB or (M and A)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: cross_peg_bridge(state) or (state.has_Mirror(player) and state.has('Beat Agahnim 1', player)))
elif bombshop_entrance.name in Isolated_DW_entrances:
# 1. mirror then flute then basic routes
# -> M and Flute and BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has_Mirror(player) and state.has('Ocarina', player) and basic_routes(state))
elif bombshop_entrance.name in Isolated_LW_entrances:
# 1. flute then basic routes
# Prexisting mirror spot is not permitted, because mirror might have been needed to reach these isolated locations.
# -> Flute and BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has('Ocarina', player) and basic_routes(state))
elif bombshop_entrance.name in West_LW_DM_entrances:
# 1. flute then basic routes or mirror
# Prexisting mirror spot is permitted, because flute can be used to reach west DM directly.
# -> Flute and (M or BR)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has('Ocarina', player) and (state.has_Mirror(player) or basic_routes(state)))
elif bombshop_entrance.name in East_LW_DM_entrances:
# 1. flute then basic routes or mirror and hookshot
# Prexisting mirror spot is permitted, because flute can be used to reach west DM directly and then east DM via Hookshot
# -> Flute and ((M and Hookshot) or BR)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has('Ocarina', player) and ((state.has_Mirror(player) and state.has('Hookshot', player)) or basic_routes(state)))
elif bombshop_entrance.name == 'Fairy Ascension Cave (Bottom)':
# Same as East_LW_DM_entrances except navigation without BR requires Mitts
# -> Flute and ((M and Hookshot and Mitts) or BR)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has('Ocarina', player) and ((state.has_Mirror(player) and state.has('Hookshot', player) and state.can_lift_heavy_rocks(player)) or basic_routes(state)))
elif bombshop_entrance.name in Castle_ledge_entrances:
# 1. mirror on pyramid to castle ledge, grab bomb, return through mirror spot: Needs mirror
# 2. flute then basic routes
# -> M or (Flute and BR)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has_Mirror(player) or (state.has('Ocarina', player) and basic_routes(state)))
elif bombshop_entrance.name in Desert_mirrorable_ledge_entrances:
# Cases when you have mire access: Mirror to reach locations, return via mirror spot, move to center of desert, mirror anagin and:
# 1. Have mire access, Mirror to reach locations, return via mirror spot, move to center of desert, mirror again and then basic routes
# 2. flute then basic routes
# -> (Mire access and M) or Flute) and BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: ((state.can_reach('Dark Desert', 'Region', player) and state.has_Mirror(player)) or state.has('Ocarina', player)) and basic_routes(state))
elif bombshop_entrance.name == 'Old Man Cave (West)':
# 1. Lift rock then basic_routes
# 2. flute then basic_routes
# -> (Flute or G) and BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.has('Ocarina', player) or state.can_lift_rocks(player)) and basic_routes(state))
elif bombshop_entrance.name == 'Graveyard Cave':
# 1. flute then basic routes
# 2. (has west dark world access) use existing mirror spot (required Pearl), mirror again off ledge
# -> (Flute or (M and P and West Dark World access) and BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.has('Ocarina', player) or (state.can_reach('West Dark World', 'Region', player) and state.has_Pearl(player) and state.has_Mirror(player))) and basic_routes(state))
elif bombshop_entrance.name in Mirror_from_SDW_entrances:
# 1. flute then basic routes
# 2. (has South dark world access) use existing mirror spot, mirror again off ledge
# -> (Flute or (M and South Dark World access) and BR
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.has('Ocarina', player) or (state.can_reach('South Dark World', 'Region', player) and state.has_Mirror(player))) and basic_routes(state))
elif bombshop_entrance.name == 'Dark World Potion Shop':
# 1. walk down by lifting rock: needs gloves and pearl`
# 2. walk down by hammering peg: needs hammer and pearl
# 3. mirror and basic routes
# -> (P and (H or Gloves)) or (M and BR)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.has_Pearl(player) and (state.has('Hammer', player) or state.can_lift_rocks(player))) or (state.has_Mirror(player) and basic_routes(state)))
elif bombshop_entrance.name == 'Kings Grave':
# same as the Normal_LW_entrances case except that the pre-existing mirror is only possible if you have mitts
# (because otherwise mirror was used to reach the grave, so would cancel a pre-existing mirror spot)
# to account for insanity, must consider a way to escape without a cave for basic_routes
# -> (M and Mitts) or ((Mitts or Flute or (M and P and West Dark World access)) and BR)
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.can_lift_heavy_rocks(player) and state.has_Mirror(player)) or ((state.can_lift_heavy_rocks(player) or state.has('Ocarina', player) or (state.can_reach('West Dark World', 'Region', player) and state.has_Pearl(player) and state.has_Mirror(player))) and basic_routes(state)))
elif bombshop_entrance.name == 'Waterfall of Wishing':
# same as the Normal_LW_entrances case except in insanity it's possible you could be here without Flippers which
# means you need an escape route of either Flippers or Flute
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.has('Flippers', player) or state.has('Ocarina', player)) and (basic_routes(state) or state.has_Mirror(player)))
def set_inverted_big_bomb_rules(world, player):
bombshop_entrance = world.get_region('Inverted Big Bomb Shop', player).entrances[0]
Normal_LW_entrances = ['Blinds Hideout',
'Bonk Fairy (Light)',
'Lake Hylia Fairy',
'Light Hype Fairy',
'Desert Fairy',
'Chicken House',
'Aginahs Cave',
'Sahasrahlas Hut',
'Cave Shop (Lake Hylia)',
'Blacksmiths Hut',
'Sick Kids House',
'Lost Woods Gamble',
'Fortune Teller (Light)',
'Snitch Lady (East)',
'Snitch Lady (West)',
'Tavern (Front)',
'Kakariko Shop',
'Mini Moldorm Cave',
'Long Fairy Cave',
'Good Bee Cave',
'20 Rupee Cave',
'50 Rupee Cave',
'Ice Rod Cave',
'Bonk Rock Cave',
'Library',
'Potion Shop',
'Dam',
'Lumberjack House',
'Lake Hylia Fortune Teller',
'Eastern Palace',
'Kakariko Gamble Game',
'Kakariko Well Cave',
'Bat Cave Cave',
'Elder House (East)',
'Elder House (West)',
'North Fairy Cave',
'Lost Woods Hideout Stump',
'Lumberjack Tree Cave',
'Two Brothers House (East)',
'Sanctuary',
'Hyrule Castle Entrance (South)',
'Hyrule Castle Secret Entrance Stairs',
'Hyrule Castle Entrance (West)',
'Hyrule Castle Entrance (East)',
'Inverted Ganons Tower',
'Cave 45',
'Checkerboard Cave',
'Inverted Big Bomb Shop']
LW_DM_entrances = ['Old Man Cave (East)',
'Old Man House (Bottom)',
'Old Man House (Top)',
'Death Mountain Return Cave (East)',
'Spectacle Rock Cave Peak',
'Tower of Hera',
'Death Mountain Return Cave (West)',
'Paradox Cave (Top)',
'Fairy Ascension Cave (Top)',
'Spiral Cave',
'Paradox Cave (Bottom)',
'Paradox Cave (Middle)',
'Hookshot Fairy',
'Spiral Cave (Bottom)',
'Mimic Cave',
'Fairy Ascension Cave (Bottom)',
'Desert Palace Entrance (West)',
'Desert Palace Entrance (North)',
'Desert Palace Entrance (South)']
Northern_DW_entrances = ['Brewery',
'C-Shaped House',
'Chest Game',
'Dark World Hammer Peg Cave',
'Red Shield Shop',
'Inverted Dark Sanctuary',
'Fortune Teller (Dark)',
'Dark World Shop',
'Dark World Lumberjack Shop',
'Thieves Town',
'Skull Woods First Section Door',
'Skull Woods Second Section Door (East)']
Southern_DW_entrances = ['Hype Cave',
'Bonk Fairy (Dark)',
'Archery Game',
'Inverted Links House',
'Dark Lake Hylia Shop',
'Swamp Palace']
Isolated_DW_entrances = ['Spike Cave',
'Cave Shop (Dark Death Mountain)',
'Dark Death Mountain Fairy',
'Skull Woods Second Section Door (West)',
'Skull Woods Final Section',
'Turtle Rock',
'Dark Death Mountain Ledge (West)',
'Dark Death Mountain Ledge (East)',
'Bumper Cave (Top)',
'Superbunny Cave (Top)',
'Superbunny Cave (Bottom)',
'Hookshot Cave',
'Turtle Rock Isolated Ledge Entrance',
'Hookshot Cave Back Entrance',
'Inverted Agahnims Tower',
'Dark Lake Hylia Ledge Fairy',
'Dark Lake Hylia Ledge Spike Cave',
'Dark Lake Hylia Ledge Hint',
'Mire Shed',
'Dark Desert Hint',
'Dark Desert Fairy',
'Misery Mire']
LW_bush_entrances = ['Bush Covered House',
'Light World Bomb Hut',
'Graveyard Cave']
set_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.can_reach('East Dark World', 'Region', player) and state.can_reach('Inverted Big Bomb Shop', 'Region', player) and state.has('Crystal 5', player) and state.has('Crystal 6', player))
# crossing peg bridge starting from the southern dark world
def cross_peg_bridge(state):
return state.has('Hammer', player)
# Key for below abbreviations:
# P = pearl
# A = Aga1
# H = hammer
# M = Mirror
# G = Glove
if bombshop_entrance.name in Normal_LW_entrances:
# Just walk to the castle and mirror.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has_Mirror(player))
elif bombshop_entrance.name in LW_DM_entrances:
# For these entrances, you cannot walk to the castle/pyramid and thus must use Mirror and then Flute.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.can_flute(player) and state.has_Mirror(player))
elif bombshop_entrance.name in Northern_DW_entrances:
# You can just fly with the Flute, you can take a long walk with Mitts and Hammer,
# or you can leave a Mirror portal nearby and then walk to the castle to Mirror again.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.can_flute or (state.can_lift_heavy_rocks(player) and cross_peg_bridge(state)) or (state.has_Mirror(player) and state.can_reach('Light World', 'Region', player)))
elif bombshop_entrance.name in Southern_DW_entrances:
# This is the same as north DW without the Mitts rock present.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: cross_peg_bridge(state) or state.can_flute(player) or (state.has_Mirror(player) and state.can_reach('Light World', 'Region', player)))
elif bombshop_entrance.name in Isolated_DW_entrances:
# There's just no way to escape these places with the bomb and no Flute.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.can_flute(player))
elif bombshop_entrance.name in LW_bush_entrances:
# These entrances are behind bushes in LW so you need either Pearl or the tools to solve NDW bomb shop locations.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has_Mirror(player) and (state.can_flute(player) or state.has_Pearl(player) or (state.can_lift_heavy_rocks(player) and cross_peg_bridge(state))))
elif bombshop_entrance.name == 'Bumper Cave (Bottom)':
# This is mostly the same as NDW but the Mirror path requires being able to lift a rock.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.can_flute or (state.can_lift_heavy_rocks(player) and cross_peg_bridge(state)) or (state.has_Mirror(player) and state.can_lift_rocks(player) and state.can_reach('Light World', 'Region', player)))
elif bombshop_entrance.name == 'Old Man Cave (West)':
# The three paths back are Mirror and DW walk, Mirror and Flute, or LW walk and then Mirror.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has_Mirror(player) and ((state.can_lift_heavy_rocks(player) and cross_peg_bridge(state)) or (state.can_lift_rocks(player) and state.has_Pearl(player)) or state.can_flute(player)))
elif bombshop_entrance.name == 'Dark World Potion Shop':
# You either need to Flute to 5 or cross the rock/hammer choice pass to the south.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.can_flute(player) or state.has('Hammer', player) or state.can_lift_rocks(player))
elif bombshop_entrance.name == 'Kings Grave':
# Either lift the rock and walk to the castle to Mirror or Mirror immediately and Flute.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.can_flute(player) or state.can_lift_heavy_rocks(player)) and state.has_Mirror(player))
elif bombshop_entrance.name == 'Two Brothers House (West)':
# First you must Mirror. Then you can either Flute, cross the peg bridge, or use the Agah 1 portal to Mirror again.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.can_flute(player) or cross_peg_bridge(state) or state.has('Beat Agahnim 1', player)) and state.has_Mirror(player))
elif bombshop_entrance.name == 'Waterfall of Wishing':
# You absolutely must be able to swim to return it from here.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has('Flippers', player) and state.has_Pearl(player) and state.has_Mirror(player))
elif bombshop_entrance.name == 'Ice Palace':
# You can swim to the dock or use the Flute to get off the island.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: state.has('Flippers', player) or state.can_flute(player))
elif bombshop_entrance.name == 'Capacity Upgrade':
# You must Mirror but then can use either Ice Palace return path.
add_rule(world.get_entrance('Pyramid Fairy', player), lambda state: (state.has('Flippers', player) or state.can_flute(player)) and state.has_Mirror(player))
def set_bunny_rules(world, player):
# regions for the exits of multi-entrace caves/drops that bunny cannot pass
# Note spiral cave may be technically passible, but it would be too absurd to require since OHKO mode is a thing.
bunny_impassable_caves = ['Bumper Cave', 'Two Brothers House', 'Hookshot Cave',
'Pyramid', 'Spiral Cave (Top)', 'Fairy Ascension Cave (Drop)']
bunny_accessible_locations = ['Link\'s Uncle', 'Sahasrahla', 'Sick Kid', 'Lost Woods Hideout', 'Lumberjack Tree',
'Checkerboard Cave', 'Potion Shop', 'Spectacle Rock Cave', 'Pyramid',
'Hype Cave - Generous Guy', 'Peg Cave', 'Bumper Cave Ledge', 'Dark Blacksmith Ruins']
def path_to_access_rule(path, entrance):
return lambda state: state.can_reach(entrance) and all(rule_func(state) for rule_func in path)
def options_to_access_rule(options):
return lambda state: any(rule_func(state) for rule_func in options)
def get_rule_to_add(start_region):
if not start_region.is_light_world:
return lambda state: state.has_Pearl(player)
# in this case we are mixed region.
# we collect possible options.
# The base option is having the moon pearl
possible_options = [lambda state: state.has_Pearl(player)]
# We will search entrances recursively until we find
# one that leads to an exclusively light world region
# for each such entrance a new option is added that consist of:
# a) being able to reach it, and
# b) being able to access all entrances from there to `region`
seen = {start_region}
queue = deque([(start_region, [])])
while queue:
(current, path) = queue.popleft()
for entrance in current.entrances:
new_region = entrance.parent_region
if new_region in seen:
continue
new_path = path + [entrance.access_rule]
seen.add(new_region)
if not new_region.is_light_world:
continue # we don't care about pure dark world entrances
if new_region.is_dark_world:
queue.append((new_region, new_path))
else:
# we have reached pure light world, so we have a new possible option
possible_options.append(path_to_access_rule(new_path, entrance))
return options_to_access_rule(possible_options)
# Add requirements for bunny-impassible caves if they occur in the dark world
for region in [world.get_region(name, player) for name in bunny_impassable_caves]:
if not region.is_dark_world:
continue
rule = get_rule_to_add(region)
for ext in region.exits:
add_rule(ext, rule)
paradox_shop = world.get_region('Light World Death Mountain Shop', player)
if paradox_shop.is_dark_world:
add_rule(paradox_shop.entrances[0], get_rule_to_add(paradox_shop))
for ent_name in bunny_impassible_doors:
bunny_exit = world.get_entrance(ent_name, player)
if bunny_exit.parent_region.is_dark_world:
add_rule(bunny_exit, get_rule_to_add(bunny_exit.parent_region))
doors_to_check = [x for x in world.doors if x.player == player and x not in bunny_impassible_doors]
doors_to_check = [x for x in doors_to_check if x.type in [DoorType.Normal, DoorType.Interior] and not x.blocked]
for door in doors_to_check:
room = world.get_room(door.roomIndex, player)
if door.entrance.parent_region.is_dark_world and room.kind(door) in [DoorKind.Dashable, DoorKind.Bombable, DoorKind.Hidden]:
add_rule(door.entrance, get_rule_to_add(door.entrance.parent_region))
# Add requirements for all locations that are actually in the dark world, except those available to the bunny
for location in world.get_locations():
if location.player == player and location.parent_region.is_dark_world:
if location.name in bunny_accessible_locations:
continue
add_rule(location, get_rule_to_add(location.parent_region))
def set_inverted_bunny_rules(world, player):
# regions for the exits of multi-entrace caves/drops that bunny cannot pass
# Note spiral cave may be technically passible, but it would be too absurd to require since OHKO mode is a thing.
bunny_impassable_caves = ['Bumper Cave', 'Two Brothers House', 'Hookshot Cave',
'Pyramid', 'Spiral Cave (Top)', 'Fairy Ascension Cave (Drop)', 'The Sky']
bunny_accessible_locations = ['Link\'s Uncle', 'Sahasrahla', 'Sick Kid', 'Lost Woods Hideout', 'Lumberjack Tree',
'Checkerboard Cave', 'Potion Shop', 'Spectacle Rock Cave', 'Pyramid',
'Hype Cave - Generous Guy', 'Peg Cave', 'Bumper Cave Ledge', 'Dark Blacksmith Ruins',
'Bombos Tablet', 'Ether Tablet', 'Purple Chest']
def path_to_access_rule(path, entrance):
return lambda state: state.can_reach(entrance) and all(rule_func(state) for rule_func in path)
def options_to_access_rule(options):
return lambda state: any(rule_func(state) for rule_func in options)
def get_rule_to_add(start_region):
if not start_region.is_dark_world:
return lambda state: state.has_Pearl(player)
# in this case we are mixed region.
# we collect possible options.
# The base option is having the moon pearl
possible_options = [lambda state: state.has_Pearl(player)]
# We will search entrances recursively until we find
# one that leads to an exclusively dark world region
# for each such entrance a new option is added that consist of:
# a) being able to reach it, and
# b) being able to access all entrances from there to `region`
seen = {start_region}
queue = deque([(start_region, [])])
while queue:
(current, path) = queue.popleft()
for entrance in current.entrances:
new_region = entrance.parent_region
if new_region in seen:
continue
new_path = path + [entrance.access_rule]
seen.add(new_region)
if not new_region.is_dark_world:
continue # we don't care about pure light world entrances
if new_region.is_light_world:
queue.append((new_region, new_path))
else:
# we have reached pure dark world, so we have a new possible option
possible_options.append(path_to_access_rule(new_path, entrance))
return options_to_access_rule(possible_options)
# Add requirements for bunny-impassible caves if they occur in the light world
for region in [world.get_region(name, player) for name in bunny_impassable_caves]:
if not region.is_light_world:
continue
rule = get_rule_to_add(region)
for ext in region.exits:
add_rule(ext, rule)
paradox_shop = world.get_region('Light World Death Mountain Shop', player)
if paradox_shop.is_light_world:
add_rule(paradox_shop.entrances[0], get_rule_to_add(paradox_shop))
for ent_name in bunny_impassible_doors:
bunny_exit = world.get_entrance(ent_name, player)
if bunny_exit.parent_region.is_light_world:
add_rule(bunny_exit, get_rule_to_add(bunny_exit.parent_region))
doors_to_check = [x for x in world.doors if x.player == player and x not in bunny_impassible_doors]
doors_to_check = [x for x in doors_to_check if x.type in [DoorType.Normal, DoorType.Interior] and not x.blocked]
for door in doors_to_check:
room = world.get_room(door.roomIndex, player)
if door.entrance.parent_region.is_light_world and room.kind(door) in [DoorKind.Dashable, DoorKind.Bombable, DoorKind.Hidden]:
add_rule(door.entrance, get_rule_to_add(door.entrance.parent_region))
# Add requirements for all locations that are actually in the light world, except those available to the bunny
for location in world.get_locations():
if location.player == player and location.parent_region.is_light_world:
if location.name in bunny_accessible_locations:
continue
add_rule(location, get_rule_to_add(location.parent_region))
bunny_impassible_doors = {
'Hyrule Dungeon Armory S', 'Hyrule Dungeon Armory ES', 'Sewers Secret Room Push Block', 'Sewers Pull Switch S',
'Eastern Lobby N', 'Eastern Courtyard Ledge W', 'Eastern Courtyard Ledge E', 'Eastern Pot Switch SE',
'Eastern Map Balcony Hook Path', 'Eastern Stalfos Spawn ES', 'Eastern Stalfos Spawn NW',
'Eastern Hint Tile Push Block', 'Eastern Darkness S', 'Eastern Darkness NE', 'Eastern Darkness Up Stairs',
'Eastern Attic Start WS', 'Eastern Single Eyegore NE', 'Eastern Duo Eyegores NE', 'Desert Main Lobby Left Path',
'Desert Main Lobby Right Path', 'Desert Left Alcove Path', 'Desert Right Alcove Path', 'Desert Compass NW',
'Desert West Lobby NW', 'Desert Back Lobby NW', 'Desert Four Statues NW', 'Desert Four Statues ES',
'Desert Beamos Hall WS', 'Desert Beamos Hall NE', 'Desert Wall Slide NW', 'Hera Lobby Down Stairs',
'Hera Lobby Key Stairs', 'Hera Lobby Up Stairs', 'Hera Tile Room EN', 'Hera Tridorm SE', 'Hera Beetles WS',
'Hera 4F Down Stairs', 'Tower Gold Knights SW', 'Tower Dark Maze EN', 'Tower Dark Pits ES', 'Tower Dark Archers WN',
'Tower Red Spears WN', 'Tower Red Guards EN', 'Tower Red Guards SW', 'Tower Circle of Pots NW', 'Tower Altar NW',
'PoD Left Cage SW', 'PoD Middle Cage SE', 'PoD Pit Room Bomb Hole', 'PoD Pit Room Block Path N',
'PoD Pit Room Block Path S', 'PoD Stalfos Basement Warp', 'PoD Arena Main SW', 'PoD Arena Main Crystal Path',
'PoD Arena Bonk Path', 'PoD Arena Crystal Path', 'PoD Sexy Statue NW', 'PoD Map Balcony Drop Down',
'PoD Mimics 1 NW', 'PoD Warp Hint Warp', 'PoD Falling Bridge Path N', 'PoD Falling Bridge Path S',
'PoD Mimics 2 NW', 'PoD Bow Statue Down Ladder', 'PoD Dark Pegs Up Ladder', 'PoD Dark Pegs WN',
'PoD Turtle Party ES', 'PoD Turtle Party NW', 'PoD Callback Warp', 'Swamp Lobby Moat', 'Swamp Entrance Moat',
'Swamp Trench 1 Approach Swim Depart', 'Swamp Trench 1 Approach Key', 'Swamp Trench 1 Key Approach',
'Swamp Trench 1 Key Ledge Depart', 'Swamp Trench 1 Departure Approach', 'Swamp Trench 1 Departure Key',
'Swamp Hub Hook Path', 'Swamp Compass Donut Push Block',
'Swamp Shortcut Blue Barrier', 'Swamp Trench 2 Pots Blue Barrier', 'Swamp Trench 2 Pots Wet',
'Swamp Trench 2 Departure Wet', 'Swamp West Shallows Push Blocks', 'Swamp West Ledge Hook Path',
'Swamp Barrier Ledge Hook Path', 'Swamp Attic Left Pit', 'Swamp Attic Right Pit', 'Swamp Push Statue NW',
'Swamp Push Statue NE', 'Swamp Drain Right Switch', 'Swamp Waterway NE', 'Swamp Waterway N', 'Swamp Waterway NW',
'Skull Pot Circle WN', 'Skull Pot Circle Star Path', 'Skull Pull Switch S', 'Skull Big Chest N',
'Skull Big Chest Hookpath', 'Skull 2 East Lobby NW', 'Skull Back Drop Star Path', 'Skull 2 West Lobby NW',
'Skull 3 Lobby EN', 'Skull Star Pits SW', 'Skull Star Pits ES', 'Skull Torch Room WN', 'Skull Vines NW',
'Thieves Conveyor Maze EN', 'Thieves Triple Bypass EN', 'Thieves Triple Bypass SE', 'Thieves Triple Bypass WN',
'Thieves Hellway Blue Barrier', 'Thieves Hellway Crystal Blue Barrier', 'Thieves Attic ES',
'Thieves Basement Block Path', 'Thieves Blocked Entry Path', 'Thieves Conveyor Bridge Block Path',
'Thieves Conveyor Block Path', 'Ice Lobby WS', 'Ice Cross Left Push Block', 'Ice Cross Bottom Push Block Left',
'Ice Cross Bottom Push Block Right', 'Ice Cross Right Push Block Top', 'Ice Cross Right Push Block Bottom',
'Ice Cross Top Push Block Bottom', 'Ice Cross Top Push Block Right', 'Ice Bomb Drop Hole', 'Ice Pengator Switch WS',
'Ice Pengator Switch ES', 'Ice Big Key Push Block', 'Ice Stalfos Hint SE', 'Ice Bomb Jump EN',
'Ice Pengator Trap NE', 'Ice Hammer Block ES', 'Ice Tongue Pull WS', 'Ice Freezors Bomb Hole', 'Ice Tall Hint WS',
'Ice Hookshot Ledge Path', 'Ice Hookshot Balcony Path', 'Ice Many Pots SW', 'Ice Many Pots WS',
'Ice Crystal Right Blue Hole', 'Ice Crystal Left Blue Barrier', 'Ice Big Chest Landing Push Blocks',
'Ice Backwards Room Hole', 'Ice Switch Room SE', 'Ice Antechamber NE', 'Ice Antechamber Hole', 'Mire Lobby Gap',
'Mire Post-Gap Gap', 'Mire 2 NE', 'Mire Hub Upper Blue Barrier', 'Mire Hub Lower Blue Barrier',
'Mire Hub Right Blue Barrier', 'Mire Hub Top Blue Barrier', 'Mire Hub Switch Blue Barrier N',
'Mire Hub Switch Blue Barrier S', 'Mire Falling Bridge WN',
'Mire Map Spike Side Blue Barrier', 'Mire Map Spot Blue Barrier', 'Mire Crystal Dead End Left Barrier',
'Mire Crystal Dead End Right Barrier', 'Mire Cross ES', 'Mire Hidden Shooters Block Path S',
'Mire Hidden Shooters Block Path N', 'Mire Left Bridge Hook Path', 'Mire Fishbone Blue Barrier',
'Mire South Fish Blue Barrier', 'Mire Tile Room NW', 'Mire Compass Blue Barrier', 'Mire Attic Hint Hole',
'Mire Dark Shooters SW', 'Mire Crystal Mid Blue Barrier', 'Mire Crystal Left Blue Barrier', 'TR Main Lobby Gap',
'TR Lobby Ledge Gap', 'TR Hub SW', 'TR Hub SE', 'TR Hub ES', 'TR Hub EN', 'TR Hub NW', 'TR Hub NE', 'TR Torches NW',
'TR Pokey 2 EN', 'TR Pokey 2 ES', 'TR Twin Pokeys SW', 'TR Twin Pokeys EN', 'TR Big Chest Gap',
'TR Big Chest Entrance Gap', 'TR Lazy Eyes ES', 'TR Tongue Pull WS', 'TR Tongue Pull NE', 'TR Dark Ride Up Stairs',
'TR Dark Ride SW', 'TR Crystal Maze Forwards Path', 'TR Crystal Maze Blue Path', 'TR Crystal Maze Cane Path',
'TR Final Abyss South Stairs', 'TR Final Abyss NW', 'GT Hope Room EN', 'GT Blocked Stairs Block Path',
'GT Bob\'s Room Hole', 'GT Speed Torch SE', 'GT Speed Torch South Path', 'GT Speed Torch North Path',
'GT Crystal Conveyor NE', 'GT Crystal Conveyor WN', 'GT Conveyor Cross EN', 'GT Conveyor Cross WN',
'GT Hookshot East-North Path', 'GT Hookshot East-South Path', 'GT Hookshot North-East Path',
'GT Hookshot North-South Path', 'GT Hookshot South-East Path', 'GT Hookshot South-North Path',
'GT Hookshot Platform Blue Barrier', 'GT Hookshot Entry Blue Barrier', 'GT Double Switch Blue Path',
'GT Double Switch Key Blue Path', 'GT Double Switch Blue Barrier', 'GT Double Switch Transition Blue',
'GT Firesnake Room Hook Path', 'GT Falling Bridge WN', 'GT Falling Bridge WS', 'GT Ice Armos NE', 'GT Ice Armos WS',
'GT Crystal Paths SW', 'GT Mimics 1 NW', 'GT Mimics 1 ES', 'GT Mimics 2 WS', 'GT Mimics 2 NE',
'GT Hidden Spikes EN', 'GT Cannonball Bridge SE', 'GT Gauntlet 1 WN', 'GT Gauntlet 2 EN', 'GT Gauntlet 2 SW',
'GT Gauntlet 3 NW', 'GT Gauntlet 3 SW', 'GT Gauntlet 4 NW', 'GT Gauntlet 4 SW', 'GT Gauntlet 5 NW',
'GT Gauntlet 5 WS', 'GT Lanmolas 2 ES', 'GT Lanmolas 2 NW', 'GT Wizzrobes 1 SW', 'GT Wizzrobes 2 SE',
'GT Wizzrobes 2 NE', 'GT Torch Cross ES', 'GT Falling Torches NE', 'GT Moldorm Gap', 'GT Validation Block Path'
}
def add_key_logic_rules(world, player):
key_logic = world.key_logic[player]
for d_name, d_logic in key_logic.items():
for door_name, keys in d_logic.door_rules.items():
spot = world.get_entrance(door_name, player)
add_rule(spot, create_advanced_key_rule(d_logic, player, keys))
if keys.opposite:
add_rule(spot, create_advanced_key_rule(d_logic, player, keys.opposite), 'or')
for location in d_logic.bk_restricted:
if location.name not in key_only_locations.keys():
forbid_item(location, d_logic.bk_name, player)
for location in d_logic.sm_restricted:
forbid_item(location, d_logic.small_key_name, player)
for door in d_logic.bk_doors:
add_rule(world.get_entrance(door.name, player), create_rule(d_logic.bk_name, player))
for chest in d_logic.bk_chests:
add_rule(world.get_location(chest.name, player), create_rule(d_logic.bk_name, player))
def create_rule(item_name, player):
return lambda state: state.has(item_name, player)
def create_key_rule(small_key_name, player, keys):
return lambda state: state.has_key(small_key_name, player, keys)
def create_key_rule_allow_small(small_key_name, player, keys, location):
loc = location.name
return lambda state: state.has_key(small_key_name, player, keys) or (item_name(state, loc, player) in [(small_key_name, player)] and state.has_key(small_key_name, player, keys-1))
def create_key_rule_bk_exception(small_key_name, big_key_name, player, keys, bk_keys, bk_locs):
chest_names = [x.name for x in bk_locs]
return lambda state: (state.has_key(small_key_name, player, keys) and not item_in_locations(state, big_key_name, player, zip(chest_names, [player] * len(chest_names)))) or (item_in_locations(state, big_key_name, player, zip(chest_names, [player] * len(chest_names))) and state.has_key(small_key_name, player, bk_keys))
def create_key_rule_bk_exception_or_allow(small_key_name, big_key_name, player, keys, location, bk_keys, bk_locs):
loc = location.name
chest_names = [x.name for x in bk_locs]
return lambda state: (state.has_key(small_key_name, player, keys) and not item_in_locations(state, big_key_name, player, zip(chest_names, [player] * len(chest_names)))) or (item_name(state, loc, player) in [(small_key_name, player)] and state.has_key(small_key_name, player, keys-1)) or (item_in_locations(state, big_key_name, player, zip(chest_names, [player] * len(chest_names))) and state.has_key(small_key_name, player, bk_keys))
def create_advanced_key_rule(key_logic, player, rule):
if not rule.allow_small and rule.alternate_small_key is None:
return create_key_rule(key_logic.small_key_name, player, rule.small_key_num)
if rule.allow_small and rule.alternate_small_key is None:
return create_key_rule_allow_small(key_logic.small_key_name, player, rule.small_key_num, rule.small_location)
if not rule.allow_small and rule.alternate_small_key is not None:
return create_key_rule_bk_exception(key_logic.small_key_name, key_logic.bk_name, player, rule.small_key_num,
rule.alternate_small_key, rule.alternate_big_key_loc)
if rule.allow_small and rule.alternate_small_key is not None:
return create_key_rule_bk_exception_or_allow(key_logic.small_key_name, key_logic.bk_name, player,
rule.small_key_num, rule.small_location, rule.alternate_small_key,
rule.alternate_big_key_loc)
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,189,124
|
codemann8/ALttPDoorRandomizer
|
refs/heads/DoorDev
|
/Main.py
|
from collections import OrderedDict
import copy
from itertools import zip_longest
import json
import logging
import os
import random
import time
import zlib
from BaseClasses import World, CollectionState, Item, Region, Location, Shop, Entrance
from Items import ItemFactory
from KeyDoorShuffle import validate_key_placement
from Regions import create_regions, create_shops, mark_light_world_regions, create_dungeon_regions
from InvertedRegions import create_inverted_regions, mark_dark_world_regions
from EntranceShuffle import link_entrances, link_inverted_entrances
from Rom import patch_rom, patch_race_rom, patch_enemizer, apply_rom_settings, LocalRom, JsonRom, get_hash_string
from Doors import create_doors
from DoorShuffle import link_doors
from RoomData import create_rooms
from Rules import set_rules
from Dungeons import create_dungeons, fill_dungeons, fill_dungeons_restrictive
from Fill import distribute_items_cutoff, distribute_items_staleness, distribute_items_restrictive, flood_items, balance_multiworld_progression
from ItemList import generate_itempool, difficulties, fill_prizes
from Utils import output_path, parse_player_names
__version__ = '0.1.1-dev'
class EnemizerError(RuntimeError):
pass
def main(args, seed=None, fish=None):
if args.outputpath:
os.makedirs(args.outputpath, exist_ok=True)
output_path.cached_path = args.outputpath
start = time.perf_counter()
# initialize the world
world = World(args.multi, args.shuffle, args.door_shuffle, args.logic, args.mode, args.swords,
args.difficulty, args.item_functionality, args.timer, args.progressive, args.goal, args.algorithm,
args.accessibility, args.shuffleganon, args.retro, args.custom, args.customitemarray, args.hints)
logger = logging.getLogger('')
if seed is None:
random.seed(None)
world.seed = random.randint(0, 999999999)
else:
world.seed = int(seed)
random.seed(world.seed)
world.remote_items = args.remote_items.copy()
world.mapshuffle = args.mapshuffle.copy()
world.compassshuffle = args.compassshuffle.copy()
world.keyshuffle = args.keyshuffle.copy()
world.bigkeyshuffle = args.bigkeyshuffle.copy()
world.crystals_needed_for_ganon = {player: random.randint(0, 7) if args.crystals_ganon[player] == 'random' else int(args.crystals_ganon[player]) for player in range(1, world.players + 1)}
world.crystals_needed_for_gt = {player: random.randint(0, 7) if args.crystals_gt[player] == 'random' else int(args.crystals_gt[player]) for player in range(1, world.players + 1)}
world.open_pyramid = args.openpyramid.copy()
world.boss_shuffle = args.shufflebosses.copy()
world.enemy_shuffle = args.shuffleenemies.copy()
world.enemy_health = args.enemy_health.copy()
world.enemy_damage = args.enemy_damage.copy()
world.beemizer = args.beemizer.copy()
world.intensity = {player: random.randint(1, 3) if args.intensity[player] == 'random' else int(args.intensity[player]) for player in range(1, world.players + 1)}
world.experimental = args.experimental.copy()
world.dungeon_counters = args.dungeon_counters.copy()
world.fish = fish
world.rom_seeds = {player: random.randint(0, 999999999) for player in range(1, world.players + 1)}
logger.info(
world.fish.translate("cli","cli","app.title") + "\n",
__version__,
world.seed
)
parsed_names = parse_player_names(args.names, world.players, args.teams)
world.teams = len(parsed_names)
for i, team in enumerate(parsed_names, 1):
if world.players > 1:
logger.info('%s%s', 'Team%d: ' % i if world.teams > 1 else 'Players: ', ', '.join(team))
for player, name in enumerate(team, 1):
world.player_names[player].append(name)
logger.info('')
for player in range(1, world.players + 1):
world.difficulty_requirements[player] = difficulties[world.difficulty[player]]
if world.mode[player] == 'standard' and world.enemy_shuffle[player] != 'none':
if hasattr(world,"escape_assist") and player in world.escape_assist:
world.escape_assist[player].append('bombs') # enemized escape assumes infinite bombs available and will likely be unbeatable without it
for tok in filter(None, args.startinventory[player].split(',')):
item = ItemFactory(tok.strip(), player)
if item:
world.push_precollected(item)
if world.mode[player] != 'inverted':
create_regions(world, player)
else:
create_inverted_regions(world, player)
create_dungeon_regions(world, player)
create_shops(world, player)
create_doors(world, player)
create_rooms(world, player)
create_dungeons(world, player)
logger.info(world.fish.translate("cli","cli","shuffling.world"))
for player in range(1, world.players + 1):
if world.mode[player] != 'inverted':
link_entrances(world, player)
else:
link_inverted_entrances(world, player)
logger.info(world.fish.translate("cli","cli","shuffling.dungeons"))
for player in range(1, world.players + 1):
link_doors(world, player)
if world.mode[player] != 'inverted':
mark_light_world_regions(world, player)
else:
mark_dark_world_regions(world, player)
logger.info(world.fish.translate("cli","cli","generating.itempool"))
for player in range(1, world.players + 1):
generate_itempool(world, player)
logger.info(world.fish.translate("cli","cli","calc.access.rules"))
for player in range(1, world.players + 1):
set_rules(world, player)
logger.info(world.fish.translate("cli","cli","placing.dungeon.prizes"))
fill_prizes(world)
logger.info(world.fish.translate("cli","cli","placing.dungeon.items"))
shuffled_locations = None
if args.algorithm in ['balanced', 'vt26'] or any(list(args.mapshuffle.values()) + list(args.compassshuffle.values()) +
list(args.keyshuffle.values()) + list(args.bigkeyshuffle.values())):
shuffled_locations = world.get_unfilled_locations()
random.shuffle(shuffled_locations)
fill_dungeons_restrictive(world, shuffled_locations)
else:
fill_dungeons(world)
for player in range(1, world.players+1):
if world.logic[player] != 'nologic':
for key_layout in world.key_layout[player].values():
if not validate_key_placement(key_layout, world, player):
raise RuntimeError(
"%s: %s (%s %d)" %
(
world.fish.translate("cli", "cli", "keylock.detected"),
key_layout.sector.name,
world.fish.translate("cli", "cli", "player"),
player
)
)
logger.info(world.fish.translate("cli","cli","fill.world"))
if args.algorithm == 'flood':
flood_items(world) # different algo, biased towards early game progress items
elif args.algorithm == 'vt21':
distribute_items_cutoff(world, 1)
elif args.algorithm == 'vt22':
distribute_items_cutoff(world, 0.66)
elif args.algorithm == 'freshness':
distribute_items_staleness(world)
elif args.algorithm == 'vt25':
distribute_items_restrictive(world, False)
elif args.algorithm == 'vt26':
distribute_items_restrictive(world, True, shuffled_locations)
elif args.algorithm == 'balanced':
distribute_items_restrictive(world, True)
if world.players > 1:
logger.info(world.fish.translate("cli","cli","balance.multiworld"))
balance_multiworld_progression(world)
# if we only check for beatable, we can do this sanity check first before creating the rom
if not world.can_beat_game():
raise RuntimeError(world.fish.translate("cli","cli","cannot.beat.game"))
outfilebase = 'DR_%s' % (args.outputname if args.outputname else world.seed)
rom_names = []
jsonout = {}
enemized = False
if not args.suppress_rom:
logger.info(world.fish.translate("cli","cli","patching.rom"))
for team in range(world.teams):
for player in range(1, world.players + 1):
sprite_random_on_hit = type(args.sprite[player]) is str and args.sprite[player].lower() == 'randomonhit'
use_enemizer = (world.boss_shuffle[player] != 'none' or world.enemy_shuffle[player] != 'none'
or world.enemy_health[player] != 'default' or world.enemy_damage[player] != 'default'
or args.shufflepots[player] or sprite_random_on_hit)
rom = JsonRom() if args.jsonout or use_enemizer else LocalRom(args.rom)
if use_enemizer and (args.enemizercli or not args.jsonout):
if args.rom and not(os.path.isfile(args.rom)):
raise RuntimeError("Could not find valid base rom for enemizing at expected path %s." % args.rom)
if os.path.exists(args.enemizercli):
patch_enemizer(world, player, rom, args.rom, args.enemizercli, args.shufflepots[player], sprite_random_on_hit)
enemized = True
if not args.jsonout:
rom = LocalRom.fromJsonRom(rom, args.rom, 0x400000)
else:
enemizerMsg = world.fish.translate("cli","cli","enemizer.not.found") + ': ' + args.enemizercli + "\n"
enemizerMsg += world.fish.translate("cli","cli","enemizer.nothing.applied")
logging.warning(enemizerMsg)
raise EnemizerError(enemizerMsg)
patch_rom(world, rom, player, team, enemized)
if args.race:
patch_race_rom(rom)
rom_names.append((player, team, list(rom.name)))
world.spoiler.hashes[(player, team)] = get_hash_string(rom.hash)
apply_rom_settings(rom, args.heartbeep[player], args.heartcolor[player], args.quickswap[player], args.fastmenu[player], args.disablemusic[player], args.sprite[player], args.ow_palettes[player], args.uw_palettes[player])
if args.jsonout:
jsonout[f'patch_t{team}_p{player}'] = rom.patches
else:
mcsb_name = ''
if all([world.mapshuffle[player], world.compassshuffle[player], world.keyshuffle[player], world.bigkeyshuffle[player]]):
mcsb_name = '-keysanity'
elif [world.mapshuffle[player], world.compassshuffle[player], world.keyshuffle[player], world.bigkeyshuffle[player]].count(True) == 1:
mcsb_name = '-mapshuffle' if world.mapshuffle[player] else '-compassshuffle' if world.compassshuffle[player] else '-keyshuffle' if world.keyshuffle[player] else '-bigkeyshuffle'
elif any([world.mapshuffle[player], world.compassshuffle[player], world.keyshuffle[player], world.bigkeyshuffle[player]]):
mcsb_name = '-%s%s%s%sshuffle' % (
'M' if world.mapshuffle[player] else '', 'C' if world.compassshuffle[player] else '',
'S' if world.keyshuffle[player] else '', 'B' if world.bigkeyshuffle[player] else '')
outfilepname = f'_T{team+1}' if world.teams > 1 else ''
if world.players > 1:
outfilepname += f'_P{player}'
if world.players > 1 or world.teams > 1:
outfilepname += f"_{world.player_names[player][team].replace(' ', '_')}" if world.player_names[player][team] != 'Player %d' % player else ''
outfilestuffs = {
"logic": world.logic[player], # 0
"difficulty": world.difficulty[player], # 1
"difficulty_adjustments": world.difficulty_adjustments[player], # 2
"mode": world.mode[player], # 3
"goal": world.goal[player], # 4
"timer": str(world.timer), # 5
"shuffle": world.shuffle[player], # 6
"doorShuffle": world.doorShuffle[player], # 7
"algorithm": world.algorithm, # 8
"mscb": mcsb_name, # 9
"retro": world.retro[player], # A
"progressive": world.progressive, # B
"hints": 'True' if world.hints[player] else 'False' # C
}
# 0 1 2 3 4 5 6 7 8 9 A B C
outfilesuffix = ('_%s_%s-%s-%s-%s%s_%s_%s-%s%s%s%s%s' % (
# 0 1 2 3 4 5 6 7 8 9 A B C
# _noglitches_normal-normal-open-ganon-ohko_simple_basic-balanced-keysanity-retro-prog_swords-nohints
# _noglitches_normal-normal-open-ganon _simple_basic-balanced-keysanity-retro
# _noglitches_normal-normal-open-ganon _simple_basic-balanced-keysanity -prog_swords
# _noglitches_normal-normal-open-ganon _simple_basic-balanced-keysanity -nohints
outfilestuffs["logic"], # 0
outfilestuffs["difficulty"], # 1
outfilestuffs["difficulty_adjustments"], # 2
outfilestuffs["mode"], # 3
outfilestuffs["goal"], # 4
"" if outfilestuffs["timer"] in ['False', 'none', 'display'] else "-" + outfilestuffs["timer"], # 5
outfilestuffs["shuffle"], # 6
outfilestuffs["doorShuffle"], # 7
outfilestuffs["algorithm"], # 8
outfilestuffs["mscb"], # 9
"-retro" if outfilestuffs["retro"] == "True" else "", # A
"-prog_" + outfilestuffs["progressive"] if outfilestuffs["progressive"] in ['off', 'random'] else "", # B
"-nohints" if not outfilestuffs["hints"] == "True" else "")) if not args.outputname else '' # C
rom.write_to_file(output_path(f'{outfilebase}{outfilepname}{outfilesuffix}.sfc'))
if world.players > 1:
multidata = zlib.compress(json.dumps({"names": parsed_names,
"roms": rom_names,
"remote_items": [player for player in range(1, world.players + 1) if world.remote_items[player]],
"locations": [((location.address, location.player), (location.item.code, location.item.player))
for location in world.get_filled_locations() if type(location.address) is int],
"tags" : ["DR"]
}).encode("utf-8"))
if args.jsonout:
jsonout["multidata"] = list(multidata)
else:
with open(output_path('%s_multidata' % outfilebase), 'wb') as f:
f.write(multidata)
if not args.skip_playthrough:
logger.info(world.fish.translate("cli","cli","calc.playthrough"))
create_playthrough(world)
if args.jsonout:
print(json.dumps({**jsonout, 'spoiler': world.spoiler.to_json()}))
elif args.create_spoiler:
logger.info(world.fish.translate("cli","cli","patching.spoiler"))
if args.jsonout:
with open(output_path('%s_Spoiler.json' % outfilebase), 'w') as outfile:
outfile.write(world.spoiler.to_json())
else:
world.spoiler.to_file(output_path('%s_Spoiler.txt' % outfilebase))
YES = world.fish.translate("cli","cli","yes")
NO = world.fish.translate("cli","cli","no")
logger.info("")
logger.info(world.fish.translate("cli","cli","done"))
logger.info("")
logger.info(world.fish.translate("cli","cli","made.rom") % (YES if (args.create_rom) else NO))
logger.info(world.fish.translate("cli","cli","made.playthrough") % (YES if (args.calc_playthrough) else NO))
logger.info(world.fish.translate("cli","cli","made.spoiler") % (YES if (not args.jsonout and args.create_spoiler) else NO))
logger.info(world.fish.translate("cli","cli","used.enemizer") % (YES if enemized else NO))
logger.info(world.fish.translate("cli","cli","seed") + ": %d", world.seed)
logger.info(world.fish.translate("cli","cli","total.time"), time.perf_counter() - start)
# print_wiki_doors_by_room(dungeon_regions,world,1)
# print_wiki_doors_by_region(dungeon_regions,world,1)
return world
def copy_world(world):
# ToDo: Not good yet
ret = World(world.players, world.shuffle, world.doorShuffle, world.logic, world.mode, world.swords,
world.difficulty, world.difficulty_adjustments, world.timer, world.progressive, world.goal, world.algorithm,
world.accessibility, world.shuffle_ganon, world.retro, world.custom, world.customitemarray, world.hints)
ret.teams = world.teams
ret.player_names = copy.deepcopy(world.player_names)
ret.remote_items = world.remote_items.copy()
ret.required_medallions = world.required_medallions.copy()
ret.swamp_patch_required = world.swamp_patch_required.copy()
ret.ganon_at_pyramid = world.ganon_at_pyramid.copy()
ret.powder_patch_required = world.powder_patch_required.copy()
ret.ganonstower_vanilla = world.ganonstower_vanilla.copy()
ret.treasure_hunt_count = world.treasure_hunt_count.copy()
ret.treasure_hunt_icon = world.treasure_hunt_icon.copy()
ret.sewer_light_cone = world.sewer_light_cone.copy()
ret.light_world_light_cone = world.light_world_light_cone
ret.dark_world_light_cone = world.dark_world_light_cone
ret.seed = world.seed
ret.can_access_trock_eyebridge = world.can_access_trock_eyebridge.copy()
ret.can_access_trock_front = world.can_access_trock_front.copy()
ret.can_access_trock_big_chest = world.can_access_trock_big_chest.copy()
ret.can_access_trock_middle = world.can_access_trock_middle.copy()
ret.can_take_damage = world.can_take_damage
ret.difficulty_requirements = world.difficulty_requirements.copy()
ret.fix_fake_world = world.fix_fake_world.copy()
ret.lamps_needed_for_dark_rooms = world.lamps_needed_for_dark_rooms
ret.mapshuffle = world.mapshuffle.copy()
ret.compassshuffle = world.compassshuffle.copy()
ret.keyshuffle = world.keyshuffle.copy()
ret.bigkeyshuffle = world.bigkeyshuffle.copy()
ret.crystals_needed_for_ganon = world.crystals_needed_for_ganon.copy()
ret.crystals_needed_for_gt = world.crystals_needed_for_gt.copy()
ret.open_pyramid = world.open_pyramid.copy()
ret.boss_shuffle = world.boss_shuffle.copy()
ret.enemy_shuffle = world.enemy_shuffle.copy()
ret.enemy_health = world.enemy_health.copy()
ret.enemy_damage = world.enemy_damage.copy()
ret.beemizer = world.beemizer.copy()
ret.intensity = world.intensity.copy()
ret.experimental = world.experimental.copy()
for player in range(1, world.players + 1):
if world.mode[player] != 'inverted':
create_regions(ret, player)
else:
create_inverted_regions(ret, player)
create_dungeon_regions(ret, player)
create_shops(ret, player)
create_rooms(ret, player)
create_dungeons(ret, player)
copy_dynamic_regions_and_locations(world, ret)
for player in range(1, world.players + 1):
if world.mode[player] == 'standard':
parent = ret.get_region('Menu', player)
target = ret.get_region('Hyrule Castle Secret Entrance', player)
connection = Entrance(player, 'Uncle S&Q', parent)
parent.exits.append(connection)
connection.connect(target)
# copy bosses
for dungeon in world.dungeons:
for level, boss in dungeon.bosses.items():
ret.get_dungeon(dungeon.name, dungeon.player).bosses[level] = boss
for shop in world.shops:
copied_shop = ret.get_region(shop.region.name, shop.region.player).shop
copied_shop.inventory = copy.copy(shop.inventory)
# connect copied world
for region in world.regions:
copied_region = ret.get_region(region.name, region.player)
copied_region.is_light_world = region.is_light_world
copied_region.is_dark_world = region.is_dark_world
for entrance in region.entrances:
ret.get_entrance(entrance.name, entrance.player).connect(copied_region)
# fill locations
for location in world.get_locations():
if location.item is not None:
item = Item(location.item.name, location.item.advancement, location.item.priority, location.item.type, player = location.item.player)
ret.get_location(location.name, location.player).item = item
item.location = ret.get_location(location.name, location.player)
item.world = ret
if location.event:
ret.get_location(location.name, location.player).event = True
if location.locked:
ret.get_location(location.name, location.player).locked = True
# copy remaining itempool. No item in itempool should have an assigned location
for item in world.itempool:
ret.itempool.append(Item(item.name, item.advancement, item.priority, item.type, player = item.player))
for item in world.precollected_items:
ret.push_precollected(ItemFactory(item.name, item.player))
# copy progress items in state
ret.state.prog_items = world.state.prog_items.copy()
ret.state.stale = {player: True for player in range(1, world.players + 1)}
ret.doors = world.doors
for door in ret.doors:
entrance = ret.check_for_entrance(door.name, door.player)
if entrance is not None:
entrance.door = door
ret.paired_doors = world.paired_doors
ret.rooms = world.rooms
ret.inaccessible_regions = world.inaccessible_regions
ret.dungeon_layouts = world.dungeon_layouts
ret.key_logic = world.key_logic
for player in range(1, world.players + 1):
set_rules(ret, player)
return ret
def copy_dynamic_regions_and_locations(world, ret):
for region in world.dynamic_regions:
new_reg = Region(region.name, region.type, region.hint_text, region.player)
ret.regions.append(new_reg)
ret.initialize_regions([new_reg])
ret.dynamic_regions.append(new_reg)
# Note: ideally exits should be copied here, but the current use case (Take anys) do not require this
if region.shop:
new_reg.shop = Shop(new_reg, region.shop.room_id, region.shop.type, region.shop.shopkeeper_config, region.shop.custom, region.shop.locked)
ret.shops.append(new_reg.shop)
for location in world.dynamic_locations:
new_reg = ret.get_region(location.parent_region.name, location.parent_region.player)
new_loc = Location(location.player, location.name, location.address, location.crystal, location.hint_text, new_reg)
# todo: this is potentially dangerous. later refactor so we
# can apply dynamic region rules on top of copied world like other rules
new_loc.access_rule = location.access_rule
new_loc.always_allow = location.always_allow
new_loc.item_rule = location.item_rule
new_reg.locations.append(new_loc)
ret.clear_location_cache()
def create_playthrough(world):
# create a copy as we will modify it
old_world = world
world = copy_world(world)
# get locations containing progress items
prog_locations = [location for location in world.get_filled_locations() if location.item.advancement]
state_cache = [None]
collection_spheres = []
state = CollectionState(world)
sphere_candidates = list(prog_locations)
logging.getLogger('').debug(world.fish.translate("cli","cli","building.collection.spheres"))
while sphere_candidates:
state.sweep_for_events(key_only=True)
sphere = []
# build up spheres of collection radius. Everything in each sphere is independent from each other in dependencies and only depends on lower spheres
for location in sphere_candidates:
if state.can_reach(location) and state.not_flooding_a_key(world, location):
sphere.append(location)
for location in sphere:
sphere_candidates.remove(location)
state.collect(location.item, True, location)
collection_spheres.append(sphere)
state_cache.append(state.copy())
logging.getLogger('').debug(world.fish.translate("cli","cli","building.calculating.spheres"), len(collection_spheres), len(sphere), len(prog_locations))
if not sphere:
logging.getLogger('').error(world.fish.translate("cli","cli","cannot.reach.items"), [world.fish.translate("cli","cli","cannot.reach.item") % (location.item.name, location.item.player, location.name, location.player) for location in sphere_candidates])
if any([world.accessibility[location.item.player] != 'none' for location in sphere_candidates]):
raise RuntimeError(world.fish.translate("cli","cli","cannot.reach.progression"))
else:
old_world.spoiler.unreachables = sphere_candidates.copy()
break
# in the second phase, we cull each sphere such that the game is still beatable, reducing each range of influence to the bare minimum required inside it
for num, sphere in reversed(list(enumerate(collection_spheres))):
to_delete = []
for location in sphere:
# we remove the item at location and check if game is still beatable
logging.getLogger('').debug('Checking if %s (Player %d) is required to beat the game.', location.item.name, location.item.player)
old_item = location.item
location.item = None
if world.can_beat_game(state_cache[num]):
to_delete.append(location)
else:
# still required, got to keep it around
location.item = old_item
# cull entries in spheres for spoiler walkthrough at end
for location in to_delete:
sphere.remove(location)
# second phase, sphere 0
for item in [i for i in world.precollected_items if i.advancement]:
logging.getLogger('').debug('Checking if %s (Player %d) is required to beat the game.', item.name, item.player)
world.precollected_items.remove(item)
world.state.remove(item)
if not world.can_beat_game():
world.push_precollected(item)
# we are now down to just the required progress items in collection_spheres. Unfortunately
# the previous pruning stage could potentially have made certain items dependant on others
# in the same or later sphere (because the location had 2 ways to access but the item originally
# used to access it was deemed not required.) So we need to do one final sphere collection pass
# to build up the correct spheres
required_locations = [item for sphere in collection_spheres for item in sphere]
state = CollectionState(world)
collection_spheres = []
while required_locations:
state.sweep_for_events(key_only=True)
sphere = list(filter(lambda loc: state.can_reach(loc) and state.not_flooding_a_key(world, loc), required_locations))
for location in sphere:
required_locations.remove(location)
state.collect(location.item, True, location)
collection_spheres.append(sphere)
logging.getLogger('').debug(world.fish.translate("cli","cli","building.final.spheres"), len(collection_spheres), len(sphere), len(required_locations))
if not sphere:
raise RuntimeError(world.fish.translate("cli","cli","cannot.reach.required"))
# store the required locations for statistical analysis
old_world.required_locations = [(location.name, location.player) for sphere in collection_spheres for location in sphere]
def flist_to_iter(node):
while node:
value, node = node
yield value
def get_path(state, region):
reversed_path_as_flist = state.path.get(region, (region, None))
string_path_flat = reversed(list(map(str, flist_to_iter(reversed_path_as_flist))))
# Now we combine the flat string list into (region, exit) pairs
pathsiter = iter(string_path_flat)
pathpairs = zip_longest(pathsiter, pathsiter)
return list(pathpairs)
old_world.spoiler.paths = dict()
for player in range(1, world.players + 1):
old_world.spoiler.paths.update({ str(location) : get_path(state, location.parent_region) for sphere in collection_spheres for location in sphere if location.player == player})
for _, path in dict(old_world.spoiler.paths).items():
if any(exit == 'Pyramid Fairy' for (_, exit) in path):
if world.mode[player] != 'inverted':
old_world.spoiler.paths[str(world.get_region('Big Bomb Shop', player))] = get_path(state, world.get_region('Big Bomb Shop', player))
else:
old_world.spoiler.paths[str(world.get_region('Inverted Big Bomb Shop', player))] = get_path(state, world.get_region('Inverted Big Bomb Shop', player))
# we can finally output our playthrough
old_world.spoiler.playthrough = OrderedDict([("0", [str(item) for item in world.precollected_items if item.advancement])])
for i, sphere in enumerate(collection_spheres):
old_world.spoiler.playthrough[str(i + 1)] = {str(location): str(location.item) for location in sphere}
|
{"/OverworldShuffle.py": ["/OWEdges.py", "/OverworldGlitchRules.py", "/Utils.py", "/Main.py", "/EntranceShuffle.py"], "/EntranceShuffle.py": ["/OverworldShuffle.py", "/DoorShuffle.py", "/OWEdges.py", "/Utils.py", "/Main.py"], "/OWEdges.py": ["/Utils.py"], "/Rules.py": ["/OverworldGlitchRules.py", "/OWEdges.py"], "/source/classes/CustomSettings.py": ["/Utils.py", "/source/tools/MysteryUtils.py"], "/test/stats/EntranceShuffleStats.py": ["/source/overworld/EntranceShuffle2.py", "/EntranceShuffle.py"], "/ItemList.py": ["/EntranceShuffle.py", "/Fill.py", "/Rules.py"], "/OverworldGlitchRules.py": ["/OWEdges.py"], "/Mystery.py": ["/Main.py", "/source/tools/MysteryUtils.py"], "/source/overworld/EntranceShuffle2.py": ["/OverworldShuffle.py", "/OWEdges.py", "/Main.py", "/EntranceShuffle.py", "/DoorShuffle.py", "/OverworldGlitchRules.py"], "/source/item/District.py": ["/OWEdges.py"], "/AdjusterMain.py": ["/Utils.py"], "/Main.py": ["/EntranceShuffle.py", "/Doors.py", "/DoorShuffle.py", "/Rules.py", "/Fill.py", "/ItemList.py", "/Utils.py"]}
|
20,287,721
|
Devishlydashing/HMM_50007
|
refs/heads/master
|
/part3_d.py
|
import pandas as pd
from pandas import DataFrame
import numpy as np
from numpy import genfromtxt
import copy
import sys
# Global Variables ---
# Nested list of sentences and its words
x = []
# Corresponding labels matching the sentence
y = []
small = sys.float_info.min
label_count = pd.DataFrame
# ---
# To generate lists of X and Y. Splitting each sentence into a seperate sub-list ---
# Input: File Path
# Output: List of x. List of y.
def inputGenXY(path):
global x
global y
f = open(path)
f_content = f.read()
# Nested list of sentences and its words
x = []
# Corresponding labels matching the sentence
y = []
xi = []
yi = []
for data_pair in f_content.split('\n'):
if data_pair == '':
if (xi != []):
x.append(xi)
y.append(yi)
xi = []
yi = []
else:
xij,yij = data_pair.split(' ')
xi.append(xij)
yi.append(yij)
return (x,y)
# ---
# To generate lists of X. Splitting each sentence into a seperate sub-list ---
# Input: File Path
# Output: List of x.
def inputGenX(path):
global x
f = open(path)
f_content = f.read()
# Nested list of sentences and its words
x = []
xi = []
for data in f_content.split('\n'):
if data == '':
# Sentence completed
if (xi != []):
x.append(xi)
xi = []
else:
xi.append(data)
return x
# ---
# ---
# Helper function - returns unique list of elements from d
def flatten(d):
return {i for b in [[i] if not isinstance(i, list) else flatten(i) for i in d] for i in b}
# Helper function - similar to flatten function but for 2D.
def flatten2D(list2D):
flatList = []
for element in list2D:
if type(element) is list:
for item in element:
flatList.append(item)
else:
flatList.append(element)
return flatList
# ---
# Calculate transition parameters matrix ---
# Input: global variable y will be called
# Output: Transition Parameters matrix
def transitionParameters():
global y
labels = flatten(y)
transition_matrix = pd.DataFrame(index = labels, columns = labels)
transition_matrix.fillna(small,inplace=True)
for i in range(len(y)):
for j in range(len(y[i])-1):
first_word = y[i][j]
second_word = y[i][j+1]
transition_matrix.at[str(second_word),str(first_word)] +=1
for i in labels:
count = flatten2D(y).count(i)
transition_matrix[i] = transition_matrix[i].div(count)
(transition_matrix.sort_index()).to_pickle('transition_matrix')
return transition_matrix
# ---
# Emission Parameters function
# Input: Global variables x and y will be called
# Output: Emission Parameters matrix
def emissionParameters():
global x
global y
global label_count
words = flatten(x)
labels = flatten(y)
emission_matrix = pd.DataFrame(index = words, columns = labels)
emission_matrix.fillna(small,inplace=True)
for i in range(len(x)):
xi = x[i]
yi = y[i]
pairs = []
# Creation of word-label pairs for each sentence
pairs = list(zip(*[xi,yi]))
for j in pairs:
# Increment Count(y -> x)
emission_matrix.at[str(j[0]),str(j[1])] +=1
# Count(y)
label_count = emission_matrix.sum(axis=0)
print(label_count)
for i in labels:
# Count(y -> x) / Count(x). Probability of x|y
emission_matrix[i] = emission_matrix[i].div(label_count[i])
(label_count).to_pickle('label_count')
(emission_matrix).to_pickle('emission_matrix')
return (emission_matrix)
# ---
# Get a specific transition probability---
# Input: label and nextlabel (where label -> nextlabel). transition_matrix
# Output: transition probability
def transitionProbability(label, nextlabel, transition_matrix):
# if (label in transition_matrix.index) and (nextlabel in transition_matrix.columns):
return transition_matrix.at[label,nextlabel]
# else:
# return 0
# ---
# Get a specific emission probability---
# Input: label and word (where label -> word) and k-value. emission_matrix
# Output: emission probability
def emissionProbability(label, word, emission_matrix, k=0.5):
#print(emission_matrix.index.str.contains("compensation").any())
if not(word in list(emission_matrix.index)):
return (k / (label_count[label] + k))
elif word in list(emission_matrix.index):
return emission_matrix.at[word,label]
# ---
# To produce the labels for Viterbi algo
# Input: x, y, emission matrix and transition matrix
# Output: Sequence
def Viterbi(x,y,em,tm):
# Number of sentences
n = len(x)
sequence = []
# Initialization of pi matrix
start = [[1]]
t_square = [ [ 0 for i in range(len(y)) ] for j in range(n) ]
stop = [[0]]
pi = start + t_square + stop
# Perform Viterbi Algo to gather the predicted labels
for j in range(n):
pairs = []
for u in range(0, len(pi[j+1])):
# Pick maximum score for each entry in pi matrix
pi[j+1][u] = max([pi[j][v]*emissionProbability(y[u],x[j],em)*transitionProbability(y[v],y[u],tm) for v in range(len(pi[j]))])
# Gather corresponding label for the maximum score
pairs.append((u,pi[j+1][u]))
# Conduct backtracking
index = max(pairs,key=lambda item:item[1])[0]
sequence.append(y[index])
print(sequence)
seq = pd.DataFrame(sequence)
seq.to_pickle('sequence')
print(" --- ")
print(sequence)
#print(x)
# ---
# import numpy as np
# def fastViterbi(X,Y,em,tm):
# n = len(X)
# res_y = []
# #initialization
# t_square = np.zeros(shape=(n,len(Y)))
# for j in range(n):
# if j == 0:
# pairs = []
# for u in range(len(t_square[0])):
# t_square[0,u] = np.max([emissionProbability(Y[u],X[j],em)*transitionProbability(Y[0],Y[u],tm)])
# pairs.append((u,t_square[0][u]))
# index = max(pairs,key=lambda item:item[1])[0]
# res_y.append(Y[index])
# else:
# # j = 1 onwards
# pairs = []
# for u in range(len(t_square[j])):
# t_square[j,u] = np.max([t_square[j-1][v]*emissionProbability(Y[u],X[j],em)*transitionProbability(Y[v],Y[u],tm) for v in range(len(t_square[j-1]))])
# pairs.append((u,t_square[j][u]))
# index = max(pairs,key=lambda item:item[1])[0]
# res_y.append(Y[index])
# #print(pi)
# print(res_y)
# Execution Script ---
# RUN ONCE FOR FILE CREATION. THEN COMMENT OUT.
x,y = inputGenXY('./Data/EN/train')
# transitionParameters()
# emissionParameters()
# Comment the following for the first run. Then uncomment it for all following runs.
# x = inputGenX('./Data/EN/dev.in')
emission_matrix = pd.read_pickle('emission_matrix')
transition_matrix = pd.read_pickle('transition_matrix')
label_count = pd.read_pickle('label_count')
unique_words =sorted(list(flatten(y)))
unique_words.remove('O')
# Since each sentence starts with a prior state of 'O'
unique_words = ['O'] + unique_words
print('start')
Viterbi(x[30],unique_words,emission_matrix,transition_matrix)
#print(list(emission_matrix.index))
# emissionProbability("B-PP", "compensation", emission_matrix, k=0.5)
# print(len(x))
#y = sorted(list(flatten(y)))
#y = pd.DataFrame(y)
#print(y)
# ---
|
{"/part3_deprecated.py": ["/part2.py"]}
|
20,287,722
|
Devishlydashing/HMM_50007
|
refs/heads/master
|
/try.py
|
import numpy as np
import os
from pathlib import Path
from collections import Counter, defaultdict
import warnings
warnings.filterwarnings('ignore')
# SETTLED
def get_train_data(filename):
with open(filename) as f:
lines = f.readlines()
# print(lines)
x, y = [], []
temp_x, temp_y = [], []
for l in lines:
if len(l) == 1: # if l == '\n': #marking end of sentence
# assert(len(temp_x) == len(temp_y))
x.append(temp_x) # adds whole sentence(tempx) into x list
y.append(temp_y)
# print(x)
# print(y)
temp_x, temp_y = [], [] # resets new sentence
continue
xx, yy = l.split()
temp_x.append(xx) # adds word(x) into sentence(tempx)
temp_y.append(yy)
# print(temp_x)
# print(temp_y)
if len(temp_x) != 0:
x.append(temp_x)
y.append(temp_y)
# print(x)
# assert(len(x) == len(y))
return x, y
def get_index_index(argmax, index, k):
count = 0
for o in argmax:
if o == index:
return count
if o//k == index//k:
count += 1
def get_test_data(filename, word2index):
"""Return:
x: nested list of string
x_int: nested list of integer"""
with open(filename) as f:
lines = f.readlines()
x = []
temp_x = []
for l in lines:
if len(l.strip()) == 0:
x.append(temp_x)
temp_x = []
continue
xx = l.split()
# print(xx)
temp_x.append(xx[0])
if len(temp_x) != 0:
x.append(temp_x)
x_int = [[word2index[oo] for oo in o] for o in x]
return x, x_int
class HMM:
def __init__(self, train_file):
# read data
self.words, self.labels = get_train_data(train_file)
# create vocabulary
self.tags = list(
set([oo for o in self.labels for oo in o])) + ['START', 'STOP'] # list of all unique labels with START and STOP
self.tag2index = {o: i for i, o in enumerate(
self.tags)} # gives an index to each label
#print(self.tag2index)
vocab_count = Counter([oo for o in self.words for oo in o])
#
self.vocab = [o for o, v in dict(
vocab_count).items() if v >= 5] + ['#UNK#']
#
self.word2index = defaultdict(int)
for i, o in enumerate(self.vocab):
self.word2index[o] = i+1
# text to int
self.x = [[self.word2index[oo] for oo in o] for o in self.words]
self.y = [[self.tag2index[oo] for oo in o] for o in self.labels]
# print(self.tags)
def train_emission(self):
emission = np.zeros((len(self.vocab), len(self.tags)))
flat_y = [oo for o in self.y for oo in o]
flat_x = [oo for o in self.x for oo in o]
for xx, yy in zip(flat_x, flat_y):
emission[xx, yy] += 1
y_count = np.zeros(len(self.tags))
for yy in flat_y:
y_count[yy] += 1
emission = emission / y_count[None, :]
np.nan_to_num(emission, 0)
# emission_matrix += 1e-5 # Adding this smoothing will increase performance
self.emission = emission
# print(self.emission.shape)
def train_transition(self):
transition = np.zeros((len(self.tags)-1, len(self.tags)-1))
for yy in self.y:
transition[-1, yy[0]] += 1 # START transition
for i in range(len(yy)-1): # tags transition from position 0 to len(yy)-2
transition[yy[i], yy[i+1]] += 1
transition[yy[-1], -1] += 1 # STOP transition
transition = transition/np.sum(transition, axis=1)
self.transition = transition
# print(self.transition.shape)
def train(self):
self.train_emission()
self.train_transition()
def viterbi_top_k(self, x, k=3):
# Create a 3D numpy array of zeros. For score. + 2 for START STOP and + 1 for #UNK#
score = np.zeros((len(x)+2, len(self.tags)-2, k))
# Create a 3D numpy array of zeros with data type integer. For index of argmax.
argmax = np.zeros((len(x)+2, len(self.tags)-2, k), dtype=np.int)
# Log trained parameters
transition, emission = np.log(self.transition), np.log(self.emission)
# initialization at j=1
# Populate initial transition and emission values in score table
score[1, :, 0] = (transition[-1, :-1] + emission[x[0], :-2])
# Populate score table with - infinity values for all unfilled values
score[1, :, 1:] = -np.inf
# j=2, ..., n
for j in range(2, len(x)+1):
for t in range(len(self.tags)-2):
# Load prev word score
pi = score[j-1, :] # (num_of_tags-2, 3)
# Load transmission value
a = transition[:-1, t] # (num_of_tags-2,)
# Load emission value
b = emission[x[j-1], t] # (1,)
previous_all_scores = ((pi + a[:, None])).flatten()
topk = previous_all_scores.argsort()[-k:][::-1] # big to small
# big: 0, small: -1 # topk // k is the real argument
argmax[j, t] = topk
# Calculate one plane of scores
score[j, t] = previous_all_scores[topk] + b
# j=n+1 step STOP
pi = score[len(x)] # (num_of_tags-2, 7)
a = transition[:-1, -1]
# big to small
argmax_stop = (pi + a[:, None]).flatten().argsort()[-k:][::-1]
log_likelihood = np.min(pi+a[:, None])
argmax = argmax[2:-1] # (len(x)-1, num_of_tags-2, 7)
# decoding
# Backtracking
# Initialize the last pointer backward
temp_index = argmax_stop[-1] # range from 0 ~ k * ( len(tags) - 1 )
# range from 0 ~ k-1, next index in next tag
temp_index_index = get_index_index(argmax_stop, temp_index, k)
temp_arg = temp_index // k # range from 0 ~ k-1, next tag index
path = [argmax_stop[-1]//k] # initialize path as an array
for i in range(len(argmax)-1, -1, -1):
temp_index = argmax[i, temp_arg, temp_index_index]
temp_index_index = get_index_index(
argmax[i, temp_arg], temp_index, k)
temp_arg = temp_index // k
path.append(temp_arg)
return path[::-1], log_likelihood
def predict_top_k(self, dev_x_filename, output_filename, k=3):
with open(output_filename, 'w') as f:
words, dev_x = get_test_data(dev_x_filename, self.word2index)
score_list = []
for i, (ws, o) in enumerate(zip(words, dev_x)):
path, log_max_score = self.viterbi_top_k(o, k)
score_list.append(log_max_score)
for w, p in zip(ws, path):
f.write(w + ' ' + self.tags[p] + '\n')
f.write('\n')
#print(score_list)
return
AL_dev_x = 'Data/EN/dev.in'
AL_dev_y = 'Data/EN/dev.out'
AL_out_4 = 'Data/EN/dev.p4.out'
hmm = HMM('Data/EN/train')
hmm.train()
# print(hmm.tags)
hmm.predict_top_k(AL_dev_x, AL_out_4, k=3)
# print("success")
|
{"/part3_deprecated.py": ["/part2.py"]}
|
20,287,723
|
Devishlydashing/HMM_50007
|
refs/heads/master
|
/part3_deprecated.py
|
import pandas as pd
from pandas import DataFrame
import numpy as np
from numpy import genfromtxt
import copy
from part2 import EmissionParams
# Global Variables ---
#list of x(words) and y(labels)
x = []
y = []
lengthDataSet = 0
lsStates = []
lengthStates = 0
viterbiScoreTable = pd.DataFrame()
viterbiStateTable = pd.DataFrame()
transParamsTable = pd.DataFrame()
stopScore = 0
stopState = ''
sequence = []
df = pd.DataFrame()
# ---
# Import training data ---
def df_train(path):
global x
global y
global lengthDataSet
global lsStates
global lengthStates
global df
trainingdata = open(path).read().split('\n')
#list of x(words) and y(labels)
# x.append('')
# y.append("START")
for i in range(len(trainingdata)):
if trainingdata[i] != '':
word = trainingdata[i].split(' ')[0]
label = trainingdata[i].split(' ')[1]
x.append(word)
y.append(label)
# x.append('')
# y.append("STOP")
#creates dataframe of unique x rows and unique y columns
df = pd.DataFrame(index = flatten(x), columns = flatten(y)).fillna(0)
# Aggregate the counts
for w,lbl in zip(x,y):
df.at[w,lbl] = df.at[w,lbl] + 1
#print(w,lbl)
#print(df.at[w,lbl])
# Sort output in ascending order
df = df.sort_index(ascending=True)
print("--- Data ingested into df ---")
# Store list of uniqe states (y)
lsStates = sorted(list(flatten(y)))
#print(lsStates)
lengthStates = len(lsStates)
temp = pd.DataFrame(lsStates)
temp.to_pickle('lsStates')
lengthDataSet = len(x)
return df , x , y
# ---
# Import test data ---
def df_test(path):
global x
global lengthDataSet
global lengthStates
lsStates = pd.read_pickle('lsStates')
lsStates = sorted(list(flatten(lsStates.values.tolist())))
lengthStates = len(lsStates)
#print(lsStates)
trainingdata = open(path).read().split('\n')
#list of x(words) and y(labels)
for i in range(len(trainingdata)):
if trainingdata[i] != '':
word = trainingdata[i].split(' ')[0]
x.append(word)
#creates dataframe of unique x rows and unique y columns
df = pd.DataFrame(index = flatten(x), columns = lsStates).fillna(0)
# Aggregate the counts
for w,lbl in zip(x,y):
df.at[w,lbl] = df.at[w,lbl] + 1
# Sort output in ascending order
df = df.sort_index(ascending=True)
print("--- Data ingested into df ---")
lengthDataSet = len(x)
return df , x , y
# ---
# Helper function - returns unique list of elements from d ---
def flatten(d):
return {i for b in [[i] if not isinstance(i, list) else flatten(i) for i in d] for i in b}
# ---
# Populate the Transition Params Table ---
# Input: No input. But need to run df first.
# Output: transParamsTable stored in a pickle
def transParamsTable():
global transParamsTable
#rows = ['START']
rows = []
columns = []
for label in flatten(y):
rows.append(label)
columns.append(label)
transitionParamsTable = pd.DataFrame(index = rows, columns = columns).fillna(0)
print(transitionParamsTable)
labels = copy.deepcopy(y)
#labels.append('STOP')
#labels.insert(0,'START')
nextLabel = 0
for i in range(len(labels)):
if nextLabel != 'START':
label = labels[i]
nextLabel = labels[i+1]
transitionParamsTable.at[label,nextLabel] = transitionParamsTable.at[label,nextLabel] + 1
#print(nextLabel)
summation = transitionParamsTable.sum()
summation = summation.sort_index(ascending=True)
#print(summation)
for col in transitionParamsTable.columns:
transitionParamsTable[col] = transitionParamsTable[col] / summation[col]
print("--- Transition Parameters Table populated ---")
print(transitionParamsTable.sort_index())
(transitionParamsTable.sort_index()).to_pickle('transitionParamsTable')
# ---
# Pre-processing for Pi function. Creation of viterbi Tables
# Input: NONE
# Output: viterbiScoreTable & viterbiStateTable
def preProc():
global viterbiScoreTable
global viterbiStateTable
lsStates = pd.read_pickle('lsStates')
lsStates = sorted(list(flatten(lsStates.values.tolist())))
# Creation of Score Table
viterbiScoreTable = pd.DataFrame(index = lsStates, columns = x).fillna(0)
# Creation of State Table
viterbiStateTable = pd.DataFrame(index = lsStates, columns = x).fillna(0)
print("--- Preprocessing Completed ---")
# Find score of specific node ---
# Input: j - column number (int), u - row number(int), n - length of data y
# Output: Changes made to viterbiScoreTable and viterbiStateTable
def pi(j,u,n):
global viterbiScoreTable
global viterbiStateTable
global stopScore
global stopState
global lengthStates
lsStates = pd.read_pickle('lsStates')
lsStates = sorted(list(flatten(lsStates.values.tolist())))
# To load pre-process transParamsTable
transitionParamsTable = pd.read_pickle('transitionParamsTable')
#print(transitionParamsTable)
u_label = lsStates[u]
j_label = x[j]
print("-----------------------")
print("-----------------------")
print("--- Computing Score for j-label: {} & u-label: {}. j: {}] ---".format(j_label,u_label, j))
# STOP
if j == (n+1):
lsPi = []
j_1 = x[j-1]
for state in range(lengthStates):
piVal = viterbiScoreTable.iloc[state, j-1] * transitionParamsTable.at[lsStates[state], u_label]
lsPi.append(piVal)
# To generate max score
maxScore = max(lsPi)
# Since we do not have space accomodated for STOP in our df
stopScore = maxScore
# To generate corresponding prevState
indxState = lsPi.index(maxScore)
maxState = lsStates[indxState]
# Since we do not have space accomodated for STOP in our df
stopState = maxState
# j == 0
elif j == 0:
piVal = 1 * transitionParamsTable.at['START', u_label]
print("--- Max Score: ------------",piVal)
viterbiScoreTable.iloc[u,j] = piVal
viterbiStateTable.iloc[u,j] = 'START'
# Everything else
elif j > 0 and j < (n+1):
j_1 = x[j-1]
print("j - 1 label ---",j_1)
lsPi = []
for state in range(len(lsStates)):
em = EmissionParams(j_1, u_label, k = 0.5)
#print('EM-----------:', em)
piVal = viterbiScoreTable.iloc[state,j-1] * transitionParamsTable.at[lsStates[state], u_label] * em
lsPi.append(piVal)
# To generate max score
maxScore = max(lsPi)
# Since we do not have space accomodated for STOP in our df
viterbiScoreTable.iloc[u,j] = maxScore
# To generate corresponding prevState
indxState = lsPi.index(maxScore)
#print(indxState)
maxState = lsStates[indxState]
# Since we do not have space accomodated for STOP in our df
viterbiStateTable.iloc[u,j] = maxState
print("--- Max Score: ------------",maxScore)
print("--- Max State: ------------",maxState)
# ---
# Parent function for score calculation
# Input: End Node (Will always start from 0)
# Output: Modifications made to viterbiScoreTable and viterbiStateTable
def parentPi(end):
global viterbiScoreTable
global viterbiStateTable
global stopScore
global stopState
global lengthStates
print("--- Length of States:",lengthStates)
print("--- Length of Data Set:",lengthDataSet)
# Preprocessed nec lengths
for i in range(0,end):
for j in range(0,lengthStates):
pi(j = i, u = j, n = lengthDataSet)
print("-----------------------")
print("-----------------------")
print("--- Score Table:")
print(viterbiScoreTable)
print("-----------------------")
print("-----------------------")
print("--- State Table:")
print(viterbiStateTable)
(viterbiScoreTable.sort_index()).to_pickle('viterbiScoreTable')
(viterbiStateTable.sort_index()).to_pickle('viterbiStateTable')
# Backtracking funciton
# Input: Which word to backtrack from (3 for 'close')
# Output: Series of sentiments
def backtrack(s):
global sequence
viterbiScoreTable = pd.read_pickle('viterbiScoreTable')
viterbiStateTable = pd.read_pickle('viterbiStateTable')
# NOTE: NEED SOME HELP VISUALISING THE INDEXING FOR THIS PART.
s = s - 1
if s < 0 and s > lengthDataSet:
print("--- Please select an appropriate value to backtrack from ---")
if s >= 0 and s <= lengthDataSet:
for i in range(0, (s+1)):
i = s - i
if s == (lengthDataSet - 1):
# Need to integrate stopState variable
sequence.insert(0, stopState)
print("--- LAST ONE ---")
print("--- For '{}' maximum scoring label is '{}' with a score of '{}'. ---".format(x[i], stopState, stopScore))
# Gather index with maximum value. Convert the output to type str. Split the output. ->
# -> Retrieve the 2nd entry of the string which is the index value. Do some string cleaning
maximumScoreIndex = viterbiScoreTable.iloc[:, [i]].idxmax().to_string().split(' ')[1][1:]
#print(maximumScoreIndex)
#print(x[i])
#print("--- For '{}' maximum scoring label is '{}' with a score of '{}'. ---".format(x[i], maximumScoreIndex, viterbiScoreTable.at[maximumScoreIndex,x[i]].to_string().split('\n')[0]))
print("--- For '{}' maximum scoring label is '{}' with a score of '{}'. ---".format(x[i], maximumScoreIndex, ' '))
sequence.insert(0, maximumScoreIndex)
sequence.insert(0, 'START')
print('--- Generated Sequence ---')
print(sequence)
print('--- Storing Generated sequence as a Pickle ---')
temp_df = pd.DataFrame(sequence)
(temp_df).to_pickle('sequence')
return None
### ISSUE #5S:
### NOTE: THE STATE TABLE SETS THE STATE TO B-ADJP WHENEVER THE SCORE IS 0. CAN CONSIDER USING A SMALL NUMBER INSTEAD OF 0 CALCULATIONS.
### NOTE: SOME INDEXING ISSUES WITH BACKTRACK.
### NOTE: SOMETIMES THE LOGS WILL SHOW 0 VALUE FOR SOME VERY LOW VALUES.
### RESOLVED:
### NOTE: NEED TO SORT OUT RUNNING VITERBI FOR TEST SET. IT WORKS WELL FOR TRAINING SET. ```Can't seem to enter elif j > 0 and j < (n+1):```
# Execution Script ---
# RUN ONCE FOR FILE CREATION. THEN COMMENT OUT.
df, x, y = df_train('./Data/EN/train')
transParamsTable()
# Comment the following for the first run. Then uncomment it for all following runs.
# NOTE: TAKE NOTE OF FILE PATH ENTERED HERE!!!
df, x, y = df_test('./Data/EN/train')
preProc()
parentPi(30)
#backtrack(27)
# seq = pd.read_pickle('sequence')
# l = list(flatten(seq.values.tolist()))
# print(l)
# ---
|
{"/part3_deprecated.py": ["/part2.py"]}
|
20,287,724
|
Devishlydashing/HMM_50007
|
refs/heads/master
|
/temp.py
|
# # To produce the labels for Viterbi algo
# # Input: x, y, emission matrix and transition matrix
# # Output: Sequence
# def dicViterbi(x,y,em,tm):
# # Number of sentences
# n = len(x)
# sequence = []
# # Initialization of pi dictionary
# pi = {}
# pi[0] = 1
# temp = {}
# for i in range(len(y)):
# temp[i] = 0
# for j in range(n):
# pi[j+1] = temp
# pi[n+1] = 0
# # Perform Viterbi Algo to gather the predicted labels
# for j in range(n):
# # For each new sentence start a fresh pairs dic
# pairs = {}
# if j == 0:
# for u in range(0, len(pi[1])):
# # Pick maximum score for each entry in pi matrix
# pi[1][u] = pi[1][0]*emissionProbability(y[0],x[j],em)*transitionProbability(y[0],y[0],tm)
# # Gather corresponding label and score for the maximum score
# pairs[u] = pi[1][u]
# else:
# for u in range(0, len(pi[j+1])):
# # Pick maximum score for each entry in pi matrix
# pi[j+1][u] = max([pi[j][v]*emissionProbability(y[u],x[j],em)*transitionProbability(y[v],y[u],tm) for v in range(len(pi[j]))])
# # Gather corresponding label and score for the maximum score
# pairs[u] = pi[j+1][u]
# # Conduct backtracking
# index = max(pairs,key=pairs.get)
# sequence.append(y[index])
# # # Perform Viterbi Algo to gather the predicted labels
# # for j in range(n):
# # # For each new sentence start a fresh pairs dic
# # pairs = {}
# # for u in range(0, len(pi[j+1])):
# # # Pick maximum score for each entry in pi matrix
# # pi[j+1][u] = max([pi[j][v]*emissionProbability(y[u],x[j],em)*transitionProbability(y[v],y[u],tm) for v in range(len(pi[j]))])
# # # Gather corresponding label and score for the maximum score
# # pairs[u] = pi[j+1][u]
# # # Conduct backtracking
# # index = max(pairs,key=lambda item:item[1])[0]
# # sequence.append(y[index])
# #print(" --- ")
# #print(sequence)
# return sequence
# # ---
# To produce the labels for Viterbi algo
# Input: x, y, emission matrix and transition matrix
# Output: Sequence
def Viterbi(x,y,em,tm):
# Number of sentences
n = len(x)
sequence = []
# Initialization of pi matrix
start = [[1]]
t_square = [ [ 0 for i in range(len(y)) ] for j in range(n) ]
stop = [[0]]
pi = start + t_square + stop
# Perform Viterbi Algo to gather the predicted labels
for j in range(n):
# For each new sentence start a fresh pi
pairs = []
for u in range(0, len(pi[j+1])):
# Pick maximum score for each entry in pi matrix
pi[j+1][u] = max([pi[j][v]*emissionProbability(y[u],x[j],em)*transitionProbability(y[v],y[u],tm) for v in range(len(pi[j]))])
# Gather corresponding label and score for the maximum score
pairs.append((u,pi[j+1][u]))
# Conduct backtracking
#print(pairs)
index = max(pairs,key=lambda item:item[1])[0]
sequence.append(y[index])
#print(" --- ")
#print(sequence)
return sequence
# ---
import numpy as np
def simpleViterbi(sentence,labels,em,tm):
n = len(sentence)
#last word of sentence must be a fullstop
startword = [[1]]
#stopword = [[0]]
#body = [[0]*len(labels)]*len(sentence)
body = [ [ 0 for i in range(len(labels)) ] for j in range(len(sentence)) ]
pi = startword+body
sentence = ['START'] + sentence
for i in range(1,len(sentence)):
for v in range(len(pi[i])):
max_val = 0
for u in range(len(pi[i-1])):
val = pi[i-1][u] * transitionProbability(labels[u],labels[v],tm) * emissionProbability(labels[v],sentence[i],em)
if val > max_val:
max_val = val
pi[i][v] = max_val
#backtracking
res_y = [labels[np.argmax(pi[n-1])]]
for j in range(n-2,-1,-1):
maxval = 0
label = labels[0]
for v in range(len(pi[j])):
val = pi[j][v]*transitionProbability(labels[v],res_y[n-j-2],tm)
if val > maxval:
maxval = val
label = labels[v]
res_y.append(label)
return res_y
# Calculate transition parameters matrix ---
# Input: global variable y will be called
# Output: Transition Parameters matrix
def transitionParameters():
global y
labels = flatten(y)
transition_matrix = pd.DataFrame(index = labels, columns = labels)
transition_matrix.fillna(0,inplace=True)
for i in range(len(y)):
for j in range(len(y[i])-1):
first_word = y[i][j]
second_word = y[i][j+1]
transition_matrix.at[str(second_word),str(first_word)] +=1
for i in labels:
count = flatten2D(y).count(i)
transition_matrix[i] = transition_matrix[i].div(count)
transition_matrix = np.log(transition_matrix.sort_index() + small)
(transition_matrix).to_pickle('transition_matrix')
return transition_matrix
# ---
import numpy as np
def simpleViterbi(sentence,labels,em,tm):
n = len(sentence)
#last word of sentence must be a fullstop
startword = [[1]]
body = [ [ 0 for i in range(len(labels)) ] for j in range(len(sentence)) ]
pi = startword+body
sentence = ['START'] + sentence
res_y = []
for i in range(1,len(sentence)):
for v in range(len(pi[i])):
max_val = float('-inf')
for u in range(len(pi[i-1])):
# if not(sentence[i] in word_list):
# v = label_count.idxmin()
# v = labels.index(v)
val = pi[i-1][u] + transitionProbability(labels[u],labels[v],tm) + emissionProbability(labels[v],sentence[i],em)
if val > max_val:
max_val = val
pi[i][v] = max_val
#print(pi)
# #backtracking
res_y = [labels[np.argmax(pi[n-1])]]
for j in range(n-2,-1,-1):
maxval = float('-inf')
label = labels[0]
for v in range(len(pi[j])):
val = pi[j][v]+transitionProbability(labels[v],res_y[n-j-2],tm)
if val > maxval:
maxval = val
label = labels[v]
res_y.append(label)
return res_y
|
{"/part3_deprecated.py": ["/part2.py"]}
|
20,317,961
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/migrations/0001_initial.py
|
# Generated by Django 3.1.5 on 2021-06-13 23:45
import ckeditor_uploader.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Cathegorie',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(choices=[('action', 'Action'), ('drama', 'DRAMA'), ('comedy', 'COMEDY'), ('romance', 'ROMANCE')], default='1', max_length=10)),
('slug', models.SlugField(max_length=255)),
],
),
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, unique=True)),
('slug', models.SlugField(max_length=255)),
('tag', models.CharField(max_length=100)),
('description', ckeditor_uploader.fields.RichTextUploadingField()),
('location', models.CharField(max_length=255)),
('event_start_date', models.DateField(blank=True, null=True)),
('event_start_time', models.TimeField(blank=True, null=True)),
('event_end_date', models.DateField(blank=True, null=True)),
('event_end_time', models.TimeField(blank=True, null=True)),
('date_added', models.DateTimeField(auto_now_add=True)),
('images_baniere', models.ImageField(upload_to='img')),
('images_2', models.ImageField(upload_to='img')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='eventss', to='events.cathegorie')),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='eventss', to='accounts.promotor')),
],
options={
'ordering': ['-date_added'],
},
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_order', models.DateTimeField(auto_now_add=True)),
('complete', models.BooleanField(default=False)),
('transaction_id', models.IntegerField(default=1)),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='purche', to='accounts.promotor')),
],
),
migrations.CreateModel(
name='Ticket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('maximum_attende', models.PositiveIntegerField()),
('price', models.IntegerField()),
('ticket_cathegories', models.CharField(max_length=15)),
('slug', models.SlugField(max_length=255)),
('ticket_start_date_sell', models.DateField(blank=True, null=True)),
('ticket_start_time_sell', models.TimeField(blank=True, null=True)),
('ticket_end_date_sell', models.DateField(blank=True, null=True)),
('ticket_end_time_sell', models.TimeField(blank=True, null=True)),
('date_added', models.DateTimeField(auto_now_add=True)),
('min_ticket', models.IntegerField(default=1)),
('max_ticket', models.IntegerField(default=10)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='events.event')),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='accounts.promotor')),
],
options={
'ordering': ['-date_added'],
},
),
migrations.CreateModel(
name='ShippinrAddress',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('address', models.CharField(max_length=200)),
('city', models.CharField(max_length=200)),
('state', models.CharField(max_length=200)),
('phone', models.IntegerField()),
('date_added', models.DateTimeField(auto_now_add=True)),
('order', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='events.order')),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='shop', to='accounts.promotor')),
],
),
migrations.CreateModel(
name='Publish',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('publish_date', models.DateTimeField(auto_now_add=True)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='publishs', to='events.event')),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='publishs', to='accounts.promotor')),
('ticket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='publishs', to='events.ticket')),
],
),
migrations.CreateModel(
name='OrderEvent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quantity', models.IntegerField(blank=True, default=0, null=True)),
('order', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='events.order')),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='orderEvents', to='accounts.promotor')),
('ticket', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='events.ticket')),
],
),
migrations.CreateModel(
name='AchatTicket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Ticket_quantity', models.IntegerField(blank=True, default=0, null=True)),
('Ticket_date_achat', models.DateTimeField(auto_now_add=True)),
('Email_customer', models.EmailField(max_length=255, null=True)),
('Phone_number', models.CharField(max_length=255, null=True)),
('Total_amount', models.IntegerField(blank=True, default=0, null=True)),
('qr_code', models.ImageField(blank=True, upload_to='qr_codes')),
('Event_ticket', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='events.ticket')),
],
),
]
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,962
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/accounts/models.py
|
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class Promotor(models.Model):
name = models.CharField(max_length=255)
created_at = models.DateField(auto_now_add=True)
created_by = models.OneToOneField(User, related_name='promotor', on_delete=models.CASCADE)
amount = models.IntegerField(max_length=255,blank=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,963
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/views.py
|
from django.shortcuts import render, redirect, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic.list import ListView
from .models import Event, Ticket, Cathegorie, Order, OrderEvent, ShippinrAddress,AchatTicket,Publish, PublishEvent, TicketSale
from .forms import EventAddForm, TicketAddForm,AchatTicketForm
from django.utils.text import slugify
from django.conf import settings
from django.core.mail import send_mail
from django.template import Context
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMessage
from django.core import mail
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from django.utils.html import strip_tags
from django.http import JsonResponse
import json
import random
from django.contrib import messages
from django.contrib.auth.decorators import login_required
def event_home(request):
allevents = PublishEvent.objects.all()
promotor = request.user.promotor
context = {"allevents": allevents, "promotor": promotor}
return render(request, 'events/event_index.html', context)
# permet d'afficher les details sur un evenement
@login_required(login_url='login')
def event_detail(request, id):
event = PublishEvent.objects.get(id=id)
print(event)
a = request.GET['name']
slu = slugify(a)
myid = id
promotor = request.user.promotor
ev = Event.objects.get(slug=slu)
tickets = TicketSale.objects.filter(name=ev)
context = {
"event": event,'myid': myid,'promotor': promotor, 'tickets': tickets
}
return render(request, 'events/event_detail.html', context)
# l'utilisateur remplis les informations pour le payement
def event_shipping(request, id):
name = request.GET['name']
promotor = request.user.promotor
id = id
if request.method == 'POST':
sp = request.POST['price']
event = PublishEvent.objects.get(id=id)
sp.split(";")
prix = sp[0]
cat = sp[1]
idtick = sp[-1]
val = TicketSale.objects.get(id=idtick)
cont = {"name": name, "event": event, "val": val,"promotor": promotor, "id": id}
return render(request, 'events/event_shipping.html', cont)
event = PublishEvent.objects.get(id=id)
context = {"name": name, "event": event,"id": id}
return render(request, 'events/event_shipping.html', context)
@login_required(login_url='login')
def event_confirmation_pay(request, id):
id = id
promotor = request.user.promotor
if request.method == 'POST':
code = request.POST.get("code")
name = request.GET['name']
amount = request.POST.get("useramount")
totalpay = request.POST.get("totalamount")
print(amount)
print(totalpay)
a= int(amount)
b= int(totalpay)
if b < a:
print("je suis if")
a = str(code)
email = request.POST.get("us")
subject = "Verification Code | Eventick"
message = "Copy This "+a+" and Paste it in the site to confirm Transaction"
to = [email]
from_email = settings.EMAIL_HOST_USER
send_mail(subject, message , from_email ,to )
context = {
"promotor" : promotor,
"id": id
}
return render(request, 'events/event_confirmation_pay.html', context)
else:
print("je suis else")
context = {
"promotor" : promotor,
"id": id
}
messages.success(request, 'Your balance is insuffisant')
return redirect('events:event_shipping'+"/"+str(id)+'?name='+str(name))
# affiche la facture achete par le client et fait l'envois du mail
@login_required(login_url='login')
def event_facture(request):
promotor = request.user.promotor
if request.method == 'POST':
cat = request.POST.get("categorie")
nom = request.POST.get("name")
total = request.POST.get("total")
email = request.POST.get("email")
qte = request.POST.get("qtee")
verifcode = request.POST.get("validecode")
code = request.POST.get("code")
pr = request.POST.get("prix")
phone = request.POST.get("phone")
print(verifcode)
print(code)
print(total)
print(cat)
print(nom)
print(email)
print(qte)
print(phone)
it = request.POST.get("idtick")
if verifcode == code:
print("bon code")
categorie = Ticket.objects.get(ticket_cathegories=cat)
sale_info = AchatTicket(Email_customer=email,Phone_number=phone,Ticket_quantity=qte,Total_amount=total)
sale_info.Event_ticket = categorie
sale_info.save()
context = {
"nom": nom,
"categorie": categorie,
"cat": cat,
"total": total,
"email": email,
"pr": pr,
"qte": qte,
"phone": phone,
"qrcode": sale_info.qr_code,
"promotor": promotor
}
# html_message = render_to_string('events/event_facture.html', context)
# plain_message = strip_tags(html_message)
# mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
# mail.send_mail(subject1, plain_message, from_email, [to], html_message=html_message)
template_path = 'events/event_facture.html'
return render(request, 'events/event_facture.html', context)
else:
messages.success(request, 'Code is Incorrect')
return render(request, 'events/event_confirmation_pay.html')
else:
return redirect('events:event_confirmation_pay')
def home(request):
allevents = Publish.objects.all()
context = {
"allevents": allevents
}
return render(request, 'events/index.html', context)
def about(request):
return render(request, 'events/about.html')
def pdf(request):
if request.method == 'POST':
picture = request.POST['pic']
date = request.POST['date']
qte = request.POST['qte']
total = request.POST['total']
pri = request.POST['pka']
z = AchatTicket.objects.filter(pk=pri)
print(z)
template_path = 'events/facture.html'
context={
'qr':picture,
'total': total,
'qt': qte,
'date': date,
'z': z,
}
# Create a Django response object, and specify content_type as pdf
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="ticket.pdf"'
# find the template and render it.
template = get_template(template_path)
html = template.render(context)
# create a pdf
pisa_status = pisa.CreatePDF(html, dest=response)
# if error then show some funy view
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
def pdfnew(request, *args, **kwargs):
pk = kwargs.get('pk')
ticket = get_object_or_404(AchatTicket, pk=pk)
template_path = 'events/recu.html'
context={'ticket': ticket}
# Create a Django response object, and specify content_type as pdf
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="ticket.pdf"'
# find the template and render it.
template = get_template(template_path)
html = template.render(context)
# create a pdf
pisa_status = pisa.CreatePDF(html, dest=response)
# if error then show some funy view
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
def pdfview(request, *args, **kwargs):
pk = kwargs.get('pk')
ticket = get_object_or_404(AchatTicket, pk=pk)
template_path = 'events/recu.html'
context={'ticket': ticket}
# Create a Django response object, and specify content_type as pdf
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="ticket.pdf"'
# find the template and render it.
template = get_template(template_path)
html = template.render(context)
# create a pdf
pisa_status = pisa.CreatePDF(html, dest=response)
# if error then show some funy view
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
def facture(request):
vnm = AchatTicket.objects.all()
context = {
"vnm" : vnm
}
return render(request, 'events/facture.html', context)
def recieve(request, id):
idr = AchatTicket.objects.get(id=id)
ids =idr.id
print(ids)
rvce = AchatTicket.objects.get(id=id)
context = {
"rvce":rvce
}
return render(request, 'events/facture.html', context)
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,964
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/accounts/views.py
|
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from .forms import CreateUserForm
from django.utils.text import slugify
# import db
from .models import Promotor
from events.models import Event, Ticket, Publish, AchatTicket, Cathegorie, PublishEvent, TicketSale
from events.forms import TicketAddForm, EventAddForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
# fonction du dashboard
# affiche tous ce qui permet de faire des statistiques
@login_required(login_url='login')
def home(request):
promotor = request.user.promotor
eventss = promotor.eventss.all()
eventdash = promotor.eventss.all()[0:5]
total_event = eventss.count()
email = request.user.email
ik = request.user.pk
print(id)
rvce = AchatTicket.objects.all()
ea = AchatTicket.objects.filter(Email_customer=email)
a = promotor.tickets.all()
print(eventss)
b = promotor.tickets.all()[0:5]
context = {'ea': ea, 'b': b, 'promotor': promotor, 'eventss': eventss, 'total_event': total_event, 'eventdash': eventdash}
return render(request, 'accounts/home.html', context)
# voir tous les evenement cree et participe
@login_required(login_url='login')
def manage_event(request):
promotor = request.user.promotor
eventss = promotor.eventss.all()
ctg = Cathegorie.objects.all()
email = request.user.email
ea = AchatTicket.objects.filter(Email_customer=email)
context = {'ea': ea, 'promotor': promotor, 'eventss': eventss,'ctg': ctg}
return render(request, 'accounts/manage_event.html', context)
# permet d'ajouter un evenement
@login_required(login_url='login')
def add_event(request):
promotor = request.user.promotor
eventss = promotor.eventss.all()
ctg = Cathegorie.objects.all()
if request.method == 'POST':
c = request.POST['category']
d = request.POST['desc']
name = request.POST['name']
tag = request.POST['tag']
location = request.POST['location']
sdate = request.POST['sdate']
stime = request.POST['stime']
edate = request.POST['edate']
imgbaniere = request.FILES['imgbaniere']
imganother = request.FILES['imganother']
etime = request.POST['etime']
pro = request.user.promotor
slug = slugify(name)
print(c)
print(d)
eve = Event(promotor=pro,name=name,slug=slug,tag=tag,description=d,location=location,event_start_date=sdate,event_start_time=stime,event_end_date=edate,event_end_time=etime,images_baniere=imgbaniere, images_2=imganother)
eve.category = Cathegorie.objects.get(name=c)
eve.save()
return redirect('manage_event')
else:
return redirect('manage_event')
context = {'promotor': promotor, 'eventss': eventss, 'form': form,'ctg': ctg}
return render(request, 'accounts/manage_event.html', context)
# affiche les details sur un evenement
# et d'ajouter un nouveau ticket sur un evenement
@login_required(login_url='login')
def details_of_event(request, slug):
event = Event.objects.get(slug=slug) # select * from event where id=id
promotor = request.user.promotor
tickets = Ticket.objects.filter(event=event)
public = PublishEvent.objects.filter(name=event)
if request.method == 'POST':
nameev = Event.objects.get(slug=slug)
place = request.POST['nbrplace']
price = request.POST['price']
category = request.POST['category']
sdate =request.POST['sdate']
stime = request.POST['stime']
edate = request.POST['edate']
etime = request.POST['etime']
mintick = request.POST['minticket']
maxtick = request.POST['maxticket']
pro = request.user.promotor
slu = slugify(category)
cont = {"event": event, 'promotor': promotor, 'tickets':tickets, 'public': public}
if Ticket.objects.filter(event=event,ticket_cathegories=category).exists():
messages.error(request, 'this Category already exist')
render(request, 'accounts/event_detail.html', cont)
else:
if Ticket.objects.filter(event=event,price=price).exists():
messages.error(request, 'this price Already Exist Try another')
render(request, 'accounts/event_detail.html', cont)
else:
ticket = Ticket(event=nameev,promotor=pro,maximum_attende=maxtick,price=price,ticket_cathegories=category,slug=slu,ticket_start_date_sell=sdate,ticket_start_time_sell=stime,ticket_end_date_sell=edate,ticket_end_time_sell=etime,min_ticket=mintick,max_ticket=maxtick)
ticket.save()
else:
render(request, 'accounts/event_detail.html')
context = {
"event": event, 'promotor': promotor, 'tickets':tickets, 'public': public
}
return render(request, 'accounts/event_detail.html', context)
# permet a un promoteur de publier son evenement
@login_required(login_url='login')
def publish(request, slug=None):
if request.method == 'POST':
name = request.POST['name']
promotor = request.user.promotor
pub = PublishEvent(promotor=promotor)
pub.name = Event.objects.get(name=name)
slu = slugify(name)
pub.save()
return redirect('details_of_event', slug=slu)
# permet a un promoteur de metre en vente un ticket
@login_required(login_url='login')
def onsale(request, slug=None):
if request.method == 'POST':
cat = request.POST['cat']
name = request.POST['name']
id = request.POST['id']
newname = Event.objects.get(name=name)
ticket = Ticket.objects.get(id=id)
newtic = ticket.tick.all()
print(newtic)
promotor = request.user.promotor
tick = TicketSale(promotor=promotor)
tick.ticket = ticket
tick.name = newname
slu = slugify(name)
tick.save()
return redirect('details_of_event', slug=slu)
# permet d'ajouter un nouveau ticket pour un evenement
@login_required(login_url='login')
def add_new_ticket(request, slug=None):
event = Event.objects.get(slug=slug) # select * from event where id=id
promotor = request.user.promotor
tickets = Ticket.objects.filter(event=event)
if request.method == 'POST':
nameev = Event.objects.get(slug=slug)
place = request.POST['nbrplace']
price = request.POST['price']
category = request.POST['category']
sdate =request.POST['sdate']
stime = request.POST['stime']
edate = request.POST['edate']
etime = request.POST['etime']
mintick = request.POST['minticket']
maxtick = request.POST['maxticket']
pro = request.user.promotor
slu = slugify(category)
ticket = TICKET(event=nameev,promoto=pro,maximum_attende=maxtick,price=price,ticket_cathegories=category,slug=slu,ticket_start_date_sell=sdate,ticket_start_time_sell=stime,ticket_end_date_sell=edate,ticket_end_time_sell=etime,min_ticket=mintick,max_ticket=maxtick)
ticket.save()
return redirect('details_of_event', slug=slu)
else:
return redirect('details_of_event', slug=slu)
context = {
"event": event, 'promotor': promotor, 'tickets':tickets
}
return render(request, 'accounts/event_detail.html', context)
def loginpa(request):
if request.user.is_authenticated:
return redirect('events:event_home')
else:
if request.method == 'POST':
username=request.POST.get('username')
password =request.POST.get('password')
user=authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('events:event_home')
else:
messages.info(request, 'Username OR password is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def logoutuser(request):
logout(request)
return redirect('events:event_home')
def register(request):
if request.user.is_authenticated:
return redirect('events:event_home')
else:
form = CreateUserForm()
if request.method== 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
amount = 0
promotor = Promotor.objects.create(name=user.username, created_by=user, amount=amount)
cool = form.cleaned_data.get('username')
messages.success(request, 'account was created for ' + cool)
return redirect('login')
context = {'form':form}
return render(request, 'accounts/register.html', context)
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,965
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/nullam/apps.py
|
from django.apps import AppConfig
class NullamConfig(AppConfig):
name = 'nullam'
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,966
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/accounts/forms.py
|
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from events.models import Ticket
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email', 'password1', 'password2']
class TicketAddForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ('maximum_attende',
'price',
'ticket_cathegories',
'ticket_start_date_sell',
'ticket_start_time_sell',
'ticket_end_date_sell',
'ticket_end_time_sell',
'min_ticket',
'max_ticket',)
widgets = {
'ticket_start_date_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}),
'ticket_end_date_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}),
'ticket_start_time_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}),
'ticket_end_time_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}),
}
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,967
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/urls.py
|
from django.urls import path
from . import views
app_name = "events"
urlpatterns = [
# path('', views.home, name='home'),
path('', views.event_home, name='event_home'),
path('about', views.about, name='about'),
# path('event_home', views.event_home, name='event_home'),
path('event_detail/<int:id>', views.event_detail, name='event_detail'),
path('event_shipping/<int:id>', views.event_shipping, name='event_shipping'),
path('event_facture', views.event_facture, name='event_facture'),
path('event_confirmation_pay/<int:id>', views.event_confirmation_pay, name='event_confirmation_pay'),
path('facture/', views.facture, name='facture'),
path('pdf', views.pdf, name='pdf'),
path('pdfnew/<pk>', views.pdfnew, name='pdfnew'),
path('pdfview/<pk>', views.pdfview, name='pdfview'),
path('recieve/<int:id>', views.recieve, name='recieve'),
]
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,968
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/admin.py
|
from django.contrib import admin
from .models import Event, Ticket, OrderEvent, AchatTicket, Cathegorie, Publish, OrderEvent, Order, ShippinrAddress, PublishEvent, TicketSale
from mapbox_location_field.admin import MapAdmin
# class EventsAdmin(admin.ModelAdmin):
# list_display = ('titre', 'description', 'photo', 'price')
admin.site.register(Event, MapAdmin)
admin.site.register(Ticket)
admin.site.register(Cathegorie)
admin.site.register(Publish)
admin.site.register(Order)
admin.site.register(OrderEvent)
admin.site.register(AchatTicket)
admin.site.register(ShippinrAddress)
admin.site.register(PublishEvent)
admin.site.register(TicketSale)
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,969
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/migrations/0004_publishevent.py
|
# Generated by Django 3.1.5 on 2021-07-19 20:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
('events', '0003_auto_20210614_1100'),
]
operations = [
migrations.CreateModel(
name='PublishEvent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('publish_date', models.DateTimeField(auto_now_add=True)),
('name', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='publ', to='events.event')),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='published', to='accounts.promotor')),
],
),
]
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,970
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/migrations/0005_ticketsale.py
|
# Generated by Django 3.1.5 on 2021-07-20 17:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
('events', '0004_publishevent'),
]
operations = [
migrations.CreateModel(
name='TicketSale',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('publish_sale_date', models.DateTimeField(auto_now_add=True)),
('name', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='publi', to='events.event')),
('promotor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pu', to='accounts.promotor')),
('ticket', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='tick', to='events.ticket')),
],
),
]
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,971
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/accounts/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
path('login', views.loginpa, name='login'),
path('home', views.home, name='home'),
path('manage_event', views.manage_event, name='manage_event'),
path('add_event', views.add_event, name='add_event'),
path('add_new_ticket', views.add_new_ticket, name='add_new_ticket'),
path('publish', views.publish, name='publish'),
path('onsale', views.onsale, name='onsale'),
path('details_of_event/(?P<slug>[.\-\w]+)/$', views.details_of_event, name='details_of_event'),
path('logout', views.logoutuser, name='logout'),
path('register', views.register, name='register'),
]
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,972
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/forms.py
|
from django import forms
from .models import Event, Ticket,AchatTicket
# creating the forms
CATEGORY_CHOICES = [
('action', 'Action'),
('drama', 'DRAMA'),
('comedy', 'COMEDY'),
('romance', 'ROMANCE'),
]
class EventAddForm(forms.ModelForm):
class Meta:
model = Event
fields = ('name',
'tag',
'category',
'description',
'location',
'event_start_date',
'event_start_time',
'event_end_date',
'event_end_time',
'images_baniere',
'images_2',)
widgets = {
'event_start_date': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}),
'event_end_date': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}),
'event_start_time': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}),
'event_end_time': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}),
'description': forms.TextInput(attrs={'class': 'textarea_editor form-control border-radius-0'})
}
class TicketAddForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ('maximum_attende',
'price',
'ticket_cathegories',
'ticket_start_date_sell',
'ticket_start_time_sell',
'ticket_end_date_sell',
'ticket_end_time_sell',
'min_ticket',
'max_ticket',)
widgets = {
'ticket_start_date_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}),
'ticket_end_date_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}),
'ticket_start_time_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}),
'ticket_end_time_sell': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}),
}
class AchatTicketForm(forms.ModelForm):
class Meta:
model = AchatTicket
fields = (
'Ticket_quantity',
)
widgets = {
'Ticket_quantity': forms.TextInput(attrs={'class': 'form-control', 'type': 'text','id':'quantity', 'style': 'width: 70px;background-color:rgb(255, 255, 255);border:rgb(255, 255, 255)'}),
}
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,973
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/events/models.py
|
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from mapbox_location_field.models import LocationField, AddressAutoHiddenField
from ckeditor_uploader.fields import RichTextUploadingField
from django.utils.text import slugify
import qrcode
from io import BytesIO
from django.core.files import File
from PIL import Image, ImageDraw
# model import
from accounts.models import Promotor
CATEGORY_CHOICES = [
('action', 'Action'),
('drama', 'DRAMA'),
('comedy', 'COMEDY'),
('romance', 'ROMANCE'),
]
STATUS_CHOICES = [
('NOS', 'NOT ON SELL'),
('OS', 'ON SELL'),
]
# Create your models here.
# location = LocationField()
# user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
class Cathegorie(models.Model):
name = models.CharField(max_length=10, choices=CATEGORY_CHOICES, default='1')
slug = models.SlugField(max_length=255)
def __str__(self):
return self.name
class Event(models.Model):
promotor = models.ForeignKey(Promotor, related_name='eventss', on_delete=models.CASCADE)
category = models.ForeignKey(Cathegorie, related_name='eventss', on_delete=models.CASCADE)
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255)
tag = models.CharField(max_length=100) # tag de l'evemenemt
description = RichTextUploadingField()
location = models.CharField(max_length=255)
event_start_date = models.DateField(null=True, blank=True) # date de debut
event_start_time = models.TimeField(null=True, blank=True)
event_end_date = models.DateField(null=True, blank=True) # date de fin
event_end_time = models.TimeField(null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
images_baniere = models.ImageField(upload_to='img')
images_2 = models.ImageField(upload_to='img')
class Meta:
ordering = ['-date_added']
def __str__(self):
return self.name
def __unicode__(self):
return self.name
# auto generating the slug
def _get_unique_slug(self):
slug = slugify(self.name)
unique_slug = slug
num = 1
while Event.objects.filter(slug=unique_slug).exists():
unique_slug = '{}-{}'.format(slug, num)
num += 1
return unique_slug
# saving the slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self._get_unique_slug()
super().save()
class Ticket(models.Model):
event = models.ForeignKey(Event, related_name='tickets', on_delete=models.CASCADE)
promotor = models.ForeignKey(Promotor, related_name='tickets', on_delete=models.CASCADE)
maximum_attende = models.PositiveIntegerField() # nombre de place maximun
price = models.IntegerField()
ticket_cathegories = models.CharField(max_length=15)
slug = models.SlugField(max_length=255)
ticket_start_date_sell = models.DateField(null=True, blank=True) # date de debut
ticket_start_time_sell = models.TimeField(null=True, blank=True)
ticket_end_date_sell = models.DateField(null=True, blank=True) # date de fin
ticket_end_time_sell = models.TimeField(null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
min_ticket = models.IntegerField(default=1)
max_ticket = models.IntegerField(default=10)
class Meta:
ordering = ['-date_added']
def __str__(self):
return str(self.ticket_cathegories)
class PublishEvent(models.Model):
name = models.ForeignKey(Event, related_name='publ', null=True, on_delete=models.CASCADE)
promotor = models.ForeignKey(Promotor, related_name='published', on_delete=models.CASCADE)
publish_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.name)
class TicketSale(models.Model):
name = models.ForeignKey(Event, related_name='publi', null=True, on_delete=models.CASCADE)
ticket = models.ForeignKey(Ticket, related_name='tick', null=True, on_delete=models.CASCADE)
promotor = models.ForeignKey(Promotor, related_name='pu', on_delete=models.CASCADE)
publish_sale_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.ticket)
class Publish(models.Model):
ticket = models.ForeignKey(Ticket, related_name='publishs',null=True, on_delete=models.CASCADE)
publish_date = models.DateTimeField(auto_now_add=True) # date de publication
def __str__(self):
return str(self.ticket)
class Order(models.Model):
promotor = models.ForeignKey(Promotor, related_name='purche', on_delete=models.CASCADE)
date_order = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.IntegerField(default=1)
def __str__(self):
return str(self.id)
class OrderEvent(models.Model):
promotor = models.ForeignKey(Promotor, related_name='orderEvents', on_delete=models.CASCADE)
ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, null=True, blank=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
@property
def get_total(self):
total = self.ticket.price * self.quantity
return total
class ShippinrAddress(models.Model):
promotor = models.ForeignKey(Promotor, related_name='shop', on_delete=models.CASCADE)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
phone = models.IntegerField(null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
class AchatTicket(models.Model):
Event_ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, null=True, blank=True)
Ticket_quantity = models.IntegerField(default=0, null=True, blank=True)
Ticket_date_achat = models.DateTimeField(auto_now_add=True)
Email_customer = models.EmailField(max_length=255,null=True)
Phone_number = models.CharField(max_length=255,null=True)
Total_amount = models.IntegerField(default=0, null=True, blank=True)
qr_code = models.ImageField(upload_to='qr_codes', blank=True)
def __str__(self):
return str(self.Email_customer)
def save(self, *args, **kwargs):
rec = 'Categorie:'+str(self.Event_ticket)+'quantite:'+str(self.Ticket_quantity)+'Tel:'+str(self.Phone_number)
qrcode_img = qrcode.make(rec)
canvas = Image.new('RGB', (490, 490), 'white')
draw = ImageDraw.Draw(canvas)
canvas.paste(qrcode_img)
fname = f'qr_code-{rec}' + '.png'
buffer = BytesIO()
canvas.save(buffer, 'PNG')
self.qr_code.save(fname, File(buffer), save=False)
canvas.close()
super().save(*args, **kwargs)
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,317,974
|
Achaire-Zogo/Nullam
|
refs/heads/main
|
/accounts/admin.py
|
from django.contrib import admin
from .models import Promotor
# Register your models here.
admin.site.register(Promotor)
|
{"/events/models.py": ["/accounts/models.py"], "/events/forms.py": ["/events/models.py"], "/events/views.py": ["/events/models.py", "/events/forms.py"], "/events/admin.py": ["/events/models.py"], "/accounts/views.py": ["/accounts/forms.py", "/accounts/models.py", "/events/models.py", "/events/views.py", "/events/forms.py"], "/accounts/forms.py": ["/events/models.py"], "/accounts/admin.py": ["/accounts/models.py"]}
|
20,365,522
|
Shamanche/gk
|
refs/heads/main
|
/main.py
|
from flask import Flask, request, render_template, redirect, url_for
from sql_requests import *
app = Flask(__name__)
@app.route('/', methods=['post', 'get'])
def index():
companies_list = []
first_date = first_transaction()
last_date = last_transaction()
number_of_tranz = count_transactions()
if request.method == 'POST':
if request.form['button'] == 'getcompanylist':
companies_list = get_all_companies()
if request.form['button'] == 'getdata':
company_id = request.form['companyid']
first_date = request.form['firstdate']
last_date = request.form['lastdate']
print('Данные при получении из формы: ', first_date, type(first_date))
return redirect(url_for('report',
company_id=company_id,
first_date=first_date,
last_date=last_date))
template_context = {
'firstdate': first_date,
'lastdate': last_date,
'companies_list': companies_list,
'number_of_tranz': number_of_tranz
}
return render_template('index.html', **template_context)
@app.route('/report/')
def report():
company_id = request.args['company_id']
#company_id = 4 # временно
first_date = request.args['first_date']
last_date = request.args['last_date']
print ('report:', company_id, first_date, type(first_date))
phones_mssql_list = get_mssql_phones(company_id,
first_date.replace('-', ''),
last_date.replace('-', ''))
print(phones_mssql_list)
top_phones_list = phones_mssql_list[:5]
bottom_phones_list = phones_mssql_list[-5:]
template_context = {
'companyid': company_id,
'firstdate': first_date,
'lastdate': last_date,
'top_phones_list': top_phones_list,
'bottom_phones_list': bottom_phones_list,
'len_of_phones_list': len(phones_mssql_list)
}
return render_template('report.html', **template_context)
if __name__ == '__main__':
app.run(debug=True)
|
{"/main.py": ["/sql_requests.py"]}
|
20,365,523
|
Shamanche/gk
|
refs/heads/main
|
/mysql.py
|
import pymysql
conn = pymysql.connect(host='test.gorkarta.ru',
user='root',
password='Sm620514',
db='Ccserver')
with conn.cursor() as cursor:
sql_request = "SELECT phone FROM user WHERE token IS NOT NULL"
cursor.execute(sql_request)
result = cursor.fetchone()
##import pymssql
##conn = pymssql.connect(
## server="test.gorkarta.ru",
## database="RSLoyalty5",
## user="sa",
## password="Hymp112",
## port=1433)
|
{"/main.py": ["/sql_requests.py"]}
|
20,365,524
|
Shamanche/gk
|
refs/heads/main
|
/sql_requests.py
|
import pymssql
conn = pymssql.connect(
server="test.gorkarta.ru",
database="RSLoyalty5",
user="sa",
password="Hymp112",
port=1433)
def count_transactions(conn=conn):
sql_request ="select count(*) FROM Transactions"
cursor = conn.cursor()
cursor.execute(sql_request)
row = cursor.fetchone()
return row[0]
def first_transaction(conn = conn):
sql_request ="select min(TransactionTime) from Transactions"
cursor = conn.cursor()
cursor.execute(sql_request)
row = cursor.fetchone()
print('first_transaction: ', row[0])
return row[0]
def last_transaction(conn = conn):
sql_request ="select max(TransactionTime) from Transactions"
cursor = conn.cursor()
cursor.execute(sql_request)
row = cursor.fetchone()
print('last_transaction: ', row[0])
return row[0]
def get_all_companies(conn = conn):
sql_request ="select CompanyID, Name from Companies"
cursor = conn.cursor()
cursor.execute(sql_request)
rows = cursor.fetchall()
return rows
# у company_id=4 всего 25 телефонов
def get_mssql_phones (company_id, first_date, last_date, conn=conn):
print('Start get_mssql_phones ')
sql_request ="exec get_phones {}, '{}', '{}'".format(company_id,
first_date, last_date)
#sql_request = "exec get_phones 4, '20130101', '20131231'"
print(sql_request)
print('firstdate: ', first_date, type(first_date))
print('lasdate', last_date)
cursor = conn.cursor()
cursor.execute(sql_request)
rows = cursor.fetchall()
return rows
#Yx = get_mssql_phones(4, "'20130101'", "'20131231'")
|
{"/main.py": ["/sql_requests.py"]}
|
20,494,585
|
monasaad/CAPEsFinal
|
refs/heads/main
|
/Website/app.py
|
import os
import re
import nltk
import spacy
import random
import sqlite3
import warnings
import emoji as emoji
from nltk import WordNetLemmatizer
from difflib import SequenceMatcher
from flask_mail import Mail, Message
from werkzeug.utils import secure_filename
from flask import Flask, render_template, redirect, url_for, request, session
user = ""
app = Flask(__name__)
mail = Mail(app)
if __name__ == '__main__':
app.run()
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
UPLOAD_FOLDER = 'static/logos/'
app.secret_key = 'CAPEs secret key CAPEs'
app.config['SESSION_TYPE'] = 'null'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '2020capes@gmail.com'
app.config['MAIL_PASSWORD'] = 'Senoritas2020'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
# vendor home page
@app.route('/home', methods=["GET", "POST"])
def home():
if session['logged_in'] == False: return render_template('Login.html')
if request.method == "POST":
title = request.form['tit']
return redirect(url_for('update', pe=title))
user = session['username']
con = sqlite3.connect('CAPEsDatabase.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM certificate WHERE lower(v_username) ='" + user + "'")
rows = cur.fetchall()
return render_template('home.html', rows=rows)
# vendor list page
@app.route('/list', methods=["GET", "POST"])
def ViewListVendors():
if session['logged_in'] == False: return render_template('Login.html')
user = session['username']
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
result = cursor.execute(" SELECT * FROM vendor ")
rows = result.fetchall()
return render_template('beneficiary/vendor-list.html', c=rows)
# vendor details page
@app.route('/de/<v_username>', methods=["GET", "POST"])
def ViewVendorDetails(v_username):
if session['logged_in'] == False: return render_template('Login.html')
user = session['username']
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
result = cursor.execute(" SELECT * FROM vendor where v_username ='" + v_username + "'")
with conn:
cur = conn.cursor()
cur.execute("SELECT * FROM certificate WHERE lower(v_username) ='" + v_username + "'")
rows = cur.fetchall()
return render_template('beneficiary/vendor-details.html', c=result, users=v_username, user=user, rows=rows)
# Beneficiary recommecndation page
@app.route('/recommendation')
def RecommendationPEs():
if session['logged_in'] == False: return render_template('Login.html')
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
cursor.execute(" SELECT * FROM result where b_id='" + session['username'] + "'")
result = cursor.fetchall()
return render_template('beneficiary/recommendation.html', rows=result)
# todo ?
# beneficiary home page
@app.route('/bhome')
# @app.route('/', methods=["GET", "POST"])
def Bhome():
if session['logged_in'] == False: return render_template('Login.html')
user = session['username']
# conn = sqlite3.connect("CAPEsDatabase.db")
# cursor = conn.cursor()
# cursor.execute(" SELECT * FROM vendor")
# result = cursor.fetchall()
# ,user=user
# return render_template('beneficiary/home.html', rows=result, i=0)
return render_template('beneficiary/home.html')
# vendor add PE page
@app.route("/add", methods=["GET", "POST"])
def add():
if session['logged_in'] == False: return render_template('Login.html')
if request.method == "POST":
title = request.form['title']
v_username = session['username']
major = request.form['major']
level = request.form['level']
field = request.form['field']
pre_req = request.form['pre_req']
pre_c = request.form['pre_c']
prog_l = request.form['prog_l']
duration = request.form['duration']
exam_name = request.form['exam']
description = request.form['description']
URLlink = request.form['URLlink']
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
cursor.execute('INSERT INTO certificate VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)', (
None, title, v_username, major, level, field, pre_req, pre_c, prog_l, duration, description, exam_name,
URLlink))
conn.commit()
cursor.close()
conn.close()
return redirect(url_for('home'))
return render_template("vendor/add.html")
# vendor update PE page
@app.route('/update/<pe>', methods=['GET', 'POST'])
def update(pe):
if session['logged_in'] == False: return render_template('Login.html')
if request.method == "GET":
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
result = cursor.execute(" SELECT * FROM certificate where p_id='" + pe + "'")
return render_template('vendor/update.html', info=result)
if request.method == "POST":
title = request.form['title']
v_username = session['username']
major = request.form['major']
level = request.form['level']
field = request.form['field']
pre_req = request.form['pre_req']
pre_c = request.form['pre_c']
prog_l = request.form['prog_l']
duration = request.form['duration']
exam_name = request.form['exam']
description = request.form['description']
URLlink = request.form['URLlink']
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
cursor.execute("UPDATE certificate SET name='" + title +
"', major='" + major +
"', level='" + level +
"', field='" + field +
"', pre_req='" + pre_req +
"', pre_c='" + pre_c +
"', prog_l='" + prog_l +
"', duration='" + duration +
"', description='" + description +
"', exams='" + exam_name +
"', URLlink='" + URLlink +
"' WHERE p_id='" + pe + "';")
conn.commit()
cursor.close()
conn.close()
return redirect(url_for('home'))
return render_template("vendor/update.html")
# delete vendor info page
@app.route('/delete/<pe>', methods=['GET', 'POST'])
def delete(pe):
if session['logged_in'] == False: return render_template('Login.html')
user = session['username']
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
cursor.execute('DELETE FROM certificate WHERE p_id=?', (pe,))
conn.commit()
return redirect(url_for('home'))
# upload vendor info page
@app.route('/upload', methods=['GET', 'POST'])
def upload():
# Check if a valid image file was uploaded
if request.method == 'POST':
print("hi rnrn")
if 'img' not in request.files:
print("hi leen")
return redirect(request.url)
file = request.files['img']
print("hi lnrn")
if file.filename == '':
print("hello")
return redirect(request.url)
if file and allowed_file(file.filename):
print("hi")
# The image file seems valid!
# Get the filenames and pass copy in logo dir and keep it in database
name = request.form['username']
password = request.form['password']
desc = request.form['descption']
email = request.form['email']
conn = sqlite3.connect("CAPEsDatabase.db")
cursor = conn.cursor()
cursor.execute('INSERT INTO vendor VALUES (?,?,?,?,?)', (name, password, desc, email, file.filename))
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
conn.commit()
cursor.close()
conn.close()
return render_template('upload.html')
# If no valid image file was uploaded, show the file upload form:
return render_template('upload.html', error="Not added")
# method for upload vendor image
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# reset password page
@app.route('/resetpassword')
def resetpassword():
return render_template('resetpassword.html')
# login page
@app.route('/', methods=['GET', 'POST'])
def Login():
session['logged_in'] = False
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
completion = b_validate(username, password)
if completion == False:
completion = v_validate(username, password)
if completion == False:
error = 'Invalid Credentials. Please try again.'
else:
session['logged_in'] = True
return redirect(url_for('home'))
else:
session['logged_in'] = True
return redirect(url_for('Bhome'))
if 'forgetpass' in session:
error2 = session['forgetpass']
else:
error2 = None
return render_template('Login.html', error=error, error2=error2)
# method for beneficiary login
def b_validate(username, password):
print(username)
print(password)
con = sqlite3.connect('CAPEsDatabase.db')
completion = False
with con:
cur = con.cursor()
cur.execute("SELECT * FROM beneficiary")
rows = cur.fetchall()
for row in rows:
dbUser = row[0]
dbPass = row[1]
print(dbUser)
print(dbPass)
if ((dbUser == username) and (dbPass == password)):
session['username'] = dbUser
global user
user = session['username']
completion = True
return completion
# method for vendor login
def v_validate(username, password):
con = sqlite3.connect('CAPEsDatabase.db')
completion = False
with con:
cur = con.cursor()
cur.execute("SELECT * FROM vendor")
rows = cur.fetchall()
for row in rows:
dbUser = row[0]
dbPass = row[1]
if dbUser == username and dbPass == password:
session['username'] = dbUser
completion = True
return completion
# logout
@app.route('/logout')
def logout():
return redirect(url_for('Login'))
@app.route('/reset', methods=['GET', 'POST'])
def reset():
error = None
if request.method == 'POST':
token = request.form['Token']
password = request.form['password']
ConfirmPassword = request.form['ConfirmPassword']
con = sqlite3.connect('CAPEsDatabase.db')
cur = con.cursor()
with con:
cur.execute("SELECT * FROM ResetPassword")
rows = cur.fetchall()
for row in rows:
Token = row[1]
username = row[0]
if token == Token and username == session['username']:
if password == ConfirmPassword:
if session['table'] == 'vendor':
cur.execute(" UPDATE vendor SET password ='" + password + "' Where v_username='" + session[
'username'] + "'")
cur.execute('DELETE FROM ResetPassword WHERE username=?', (session['username'],))
con.commit()
return redirect(url_for('Login'))
elif session['table'] == 'beneficiary':
cur.execute(
" UPDATE beneficiary SET password ='" + password + "' Where b_username='" + session[
'username'] + "'")
cur.execute('DELETE FROM ResetPassword WHERE username=?', (session['username'],))
con.commit()
return redirect(url_for('Login'))
else:
con.commit()
else:
error = "Password and Confirm Password fileds not matching"
return render_template('resetpassword.html', error=error)
else:
error = "Please enter a right token"
return render_template('resetpassword.html', error=error)
return render_template('resetpassword.html', error=error)
# method for vendor login
def E_validate(Email):
completion = False
con = sqlite3.connect('CAPEsDatabase.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM vendor")
rows = cur.fetchall()
for row in rows:
email = row[3]
if email == Email:
completion = True
con.commit()
session['table'] = 'vendor'
return (completion, row[0])
else:
with con:
cur.execute("SELECT * FROM beneficiary")
rows = cur.fetchall()
for row in rows:
email = row[3]
if email == Email:
completion = True
con.commit()
session['table'] = 'beneficiary'
return (completion, row[0])
if completion == False:
return (completion, None)
def sendmassage(token, email):
msg = Message('Reset Password', sender='2020capes@gmail.com', recipients=[email])
msg.body = "Hello \nDear user use this token to reset your password : " + token
mail.send(msg)
return None
def get_random_string(length=5, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
return ''.join(random.choice(allowed_chars) for i in range(length))
@app.route('/forgot', methods=['GET', 'POST'])
def ForgotPassword():
error = None
if request.method == 'POST':
email = request.form['email']
completion, username = E_validate(email)
if completion == False:
error = 'Invalid Credentials. Please try again.'
return render_template('forgetpassword.html', error=error)
elif completion == True and username is not None:
token = get_random_string()
con = sqlite3.connect('CAPEsDatabase.db')
cur = con.cursor()
cur.execute('INSERT INTO ResetPassword VALUES (?,?)', (username, token))
con.commit()
cur.close()
con.close()
sendmassage(token, email)
session['username'] = username
return redirect(url_for('reset'))
if request.method == 'GET':
return render_template('forgetpassword.html', error=error)
# TODO: chat
nlp = spacy.load("en_core_web_lg")
warnings.simplefilter("error", UserWarning)
connection = sqlite3.connect('CAPEsDatabase.db', check_same_thread=False)
cursor = connection.cursor()
def randomID():
cursor.execute("SELECT qNumer FROM log")
result = [i[0] for i in cursor.fetchall()]
i = random.randint(0, 10000)
if i not in result:
return i
else:
return randomID()
exam = []
link = []
vendor = []
certificate = []
list_matching = []
question_result = []
training_pattern = []
training_keyword = []
counter = 0
rude_counter = 0
res = ''
inpput = ''
count_q7 = 1
counter_q = 1
rude_flag = False
questionN = 'What is your major?' # TODO still needed?
temp = ' '
exit_flag = False
reapet = False
res_rude = ' '
accepted_c = []
q_count = 0
result_preC = []
uniq = []
wave_emoji = emoji.emojize(':wave:', use_aliases=True)
smile_emoji = emoji.emojize(':smile:', use_aliases=True)
thumbs_emoji = emoji.emojize(':thumbs_up:', use_aliases=True)
grimacing_emoji = emoji.emojize(':grimacing:', use_aliases=True)
def getinput(input):
global inpput
inpput = input
def setinput():
global res
return res
# TODO remove comment
non_value = ['no', 'neither', 'not', 'non', 'all', 'every', 'dont', 'both', 'any', 'each', 'nothing', 'nor']
random_id = randomID()
def getQuestion():
global question_result
cursor.execute("SELECT question FROM questions")
question_result = [i[0] for i in cursor.fetchall()]
def exitProgram(x, question):
global res
global exit_flag
if x == 'q':
res = "Conversation ends. Bye!" + wave_emoji + "</br> </br> If you want to try again reload this page <3"
data_ca = (
question, x, user, 'stopped',
"Conversation ends. Bye!" + wave_emoji)
uploadCA(data_ca)
exit_flag = True
elif x == 'f':
res += " </br>Thank you for using CAPEs, Best wishes!" + smile_emoji + \
"</br></br>Please, help us to improve CAPEs by completing this survey: " \
"<a href=\"https://forms.gle/PCjbY7Znetn8xNQA9\">here</a>"
data_ca = (question, x, user, 'complete', "Thank you for using CAPEs, Best wishes!" + smile_emoji)
uploadCA(data_ca)
exit_flag = True
def getPattern(query):
cursor.execute("SELECT anwser_p FROM pattern Where id_r = ?", [query])
patterns = cursor.fetchall()
for row in patterns:
training_pattern.append(row[0])
return training_pattern
def removeKeyword(user_input):
keys = ' '.join(list_matching).split()
removed_keyword = ' '.join(word for word in user_input.split() if word not in keys)
return removed_keyword
def getKeyword(user_input, query):
global list_matching
list_matching.clear()
cursor.execute("SELECT keyword FROM keyword Where id_r = ?", [query])
keyword = cursor.fetchall()
for row in keyword:
training_keyword.append(row[0])
match = SequenceMatcher(None, user_input, row[0]).find_longest_match(0, len(user_input), 0, len(row[0]))
list_matching.append(row[0][match.b: match.b + match.size])
list_matching = list(set(list_matching).intersection(set(training_keyword)))
def removeSpecialCharacters(user_input):
patterns = r'[^a-zA-z0-9 #+\s]'
user_input_removed_char = re.sub(patterns, '', user_input)
return user_input_removed_char
def lemmatize(user_input):
lemmatizer = WordNetLemmatizer()
user_input_lemmatized = ' '.join(lemmatizer.lemmatize(w) for w in nltk.word_tokenize(user_input))
return user_input_lemmatized
def generalKeyword(user_input, query):
training_keyword.clear()
global list_matching
list_matching.clear()
cursor.execute("SELECT keyword FROM keyword Where id_c = ?", [query])
result = cursor.fetchall()
for row in result:
training_keyword.append(row[0])
match = SequenceMatcher(None, user_input, row[0]).find_longest_match(0, len(user_input), 0, len(row[0]))
list_matching.append(row[0][match.b: match.b + match.size])
list_matching = list(set(list_matching).intersection(set(training_keyword)))
def patternSimilarity(user_input):
user = removeKeyword(user_input)
user_cleaned = removeSpecialCharacters(user)
similarity_list = []
if len(user_cleaned) > 0:
user_input_cleaned = lemmatize(user_cleaned)
token1 = nlp(user_input_cleaned)
for row in training_pattern:
token2 = nlp(row)
try:
similarity = token1.similarity(token2)
except UserWarning:
similarity = 0.0
similarity_list.append(similarity)
return max(similarity_list)
else:
return 1
def rudeKeyword(user_input, count):
global rude_counter
global res
global rude_flag
global temp
global reapet
global res_rude
reapet = False
generalKeyword(user_input, 4)
rude = list_matching
for word in rude:
if user_input.__contains__(word):
if rude_counter < 2:
temp = questionN
resp = 'This a warning for using a rude word!<br><br>'
reapet = True
res_rude = resp
rude_counter += 1
data_ca = (question_result[count], user_input, session['username'], 'continue', resp)
uploadCA(data_ca)
else:
rude_flag = True
res = 'You were warned for using rude words two times the program will terminate now.'
data_ca = (question_result[count], user_input, session['username'], 'stopped', 'You were warned for using rude words two times the program will terminate now.')
uploadCA(data_ca)
def response(word_type, id_g, count, user_input):
global res
temp = questionN
i_val = random.choice([0, 1])
cursor.execute("SELECT ans2 FROM response Where id_c = ?", [id_g])
result = cursor.fetchall()
if id_g == 2:
if word_type.__contains__('result') | word_type.__contains__('record'):
res = result[0][0] + "<br /><br /> Now," + temp
data_ca = (question_result[count], user_input, user, 'continue', result[0][0])
uploadCA(data_ca)
else:
res = result[1][0] + "<br /><br /> Now, " + temp
data_ca = (question_result[count], user_input, user, 'continue', result[0][0])
uploadCA(data_ca)
else:
resp = result[i_val][0]
res = resp + "<br /><br /> Now, " + temp
data_ca = (question_result[count], user_input, user, 'continue', str(resp))
uploadCA(data_ca)
def checkGeneralKeyword(user_input, count):
global counter_q
global res
temp = questionN
generalKeyword(user_input, 2)
general = list_matching
if len(general) != 0:
pattern_similarity = patternSimilarity(user_input)
if pattern_similarity > 0.7:
response(general, 2, count, user_input)
else:
generalKeyword(user_input, 3)
weather = list_matching
if len(weather) != 0:
pattern_similarity = patternSimilarity(user_input)
if pattern_similarity > 0.7:
response(weather, 3, count, user_input)
else:
res = "Sorry, I did not understand you" + grimacing_emoji + " <br /><br /> " + temp
data_ca = (question_result[count], user_input, user, 'continue', "Sorry, I did not understand you" + grimacing_emoji + "and go next question")
uploadCA(data_ca)
def question():
global counter
global res
global inpput
global counter_q
global questionN
if counter > 5: # TODO what will happen?
"""findCertificate()"""
# exitProgram('f', '')
# if we have time need to improve
else:
questions_joint = questionN
user_input = inpput
user_input = removeSpecialCharacters(user_input)
exitProgram(user_input, questions_joint)
if not exit_flag:
rudeKeyword(user_input, counter) # rude word
if reapet:
res = res_rude + questions_joint
else:
if not rude_flag:
getPattern(counter + 1)
getKeyword(user_input, counter + 1)
if len(list_matching) != 0:
pattern_similarity = patternSimilarity(user_input)
if pattern_similarity > 0.7:
keyword = ','.join(list_matching)
user_input_removed_keywords = "".join(removeKeyword(user_input))
for word in non_value: # check none values
if user_input.__contains__(word):
keyword = "%"
data = (
random_id, user_input, user_input_removed_keywords, keyword, pattern_similarity,
questions_joint)
uploadLog(data)
if counter == 5:
responss = 'pre-cretificat q'
else:
responss = question_result[counter + 1]
data_ca = (questions_joint, user_input, user, 'continue', responss)
uploadCA(data_ca)
if counter <= 4:
questions_joint = ''.join(
question_result[
counter_q]) # loop over questions_joint table, and save the result in questions_joint
questionN = questions_joint
res = questions_joint
elif counter == 5:
# findCertificate()
res = findCertificate()
counter += 1
counter_q += 1
else:
checkGeneralKeyword(user_input, counter)
else:
checkGeneralKeyword(user_input, counter)
def uploadLog(data):
cursor.execute(
"INSERT INTO log (qNumer, userAns, textWithOutKey, keywords , patternAsimilarity, question) "
"VALUES (?, ?, ?, ?, ?, ?)", data)
connection.commit()
def print_result(accepted_list, result, w):
global res, inpput
if accepted_list.__len__() != 0:
res = "I found the most matching certificate for you: </br></br>"
count = 1
for row in result:
if row[2] in accepted_list:
certificate = row[0]
vendor = row[1]
exam = row[3]
link = row[4]
res += str(count) + "- " + certificate + ".</br></br>"
data = (user, certificate, vendor, exam, link)
uploadResult(data)
count += 1
else:
continue
res += 'If you want more information you can go to <b>Recommendation</b>tab</br>'
else:
# print("Sorry, I can not found the most matching certificate for you")
res = 'Sorry, I could not found the most matching certificate for you'+grimacing_emoji
# TODO below still needed?
certificate = 'no recommendation'
vendor = 'no recommendation'
exam = 'no recommendation'
link = 'no recommendation'
exitProgram('f', '')
def q7_check_ans(uniq, result_preC):
global q_count
ans = inpput
data_ca = (res, ans, user, 'continue', 'after those question the result will show')
uploadCA(data_ca)
while q_count >= 0:
if ans.__contains__(str(q_count)):
try:
accepted_c.append(uniq[q_count])
except IndexError:
pass
else:
'noting'
q_count -= 1
"""if q_count <= 0:
print_result(accepted_c, result_preC, random_id)"""
def findCertificate():
global certificate, vendor, exam, link
global res
global inpput
global q_count
global result_preC
global uniq
w = random_id
# w = 9502
cursor.execute("SELECT keywords FROM log WHERE qNumer=?", [w])
result = cursor.fetchall()
# print(result)
a = []
for k in range(1):
a.append([])
for j in range(6):
a[k].append([])
values = str(result[j][0]).split(",")
for v in values:
# print(result[k][i])
a[k][j].append(v)
# for access a q1
# print(a[0][0])
major = []
len_m = len(a[0][0])
for x in range(0, 3):
if len_m > 0:
if a[0][0][x].__contains__('computer science'):
major.append('%cs%')
elif a[0][0][x].__contains__('computer information system'):
major.append('%cis%')
elif a[0][0][x].__contains__('cyber security'):
major.append('%cys%')
elif a[0][0][x].__contains__('artificial intelligent'):
major.append('%ai%')
elif a[0][0][x].__contains__('%'):
major.append('%')
else:
major.append('%' + a[0][0][x] + '%')
elif len_m <= 0:
major.append('')
len_m -= 1
# _____________________________________________________________________________
level = []
len_l = len(a[0][1])
max = 0
asnum = 0
for x in range(0, 3):
if len_l > 0:
if a[0][1][x] in "one":
asnum = 1
elif a[0][1][x] in "two":
asnum = 2
elif a[0][1][x] in "three":
asnum = 3
elif a[0][1][x] in "four":
asnum = int(4)
elif a[0][1][x] in "five":
asnum = int(5)
elif a[0][1][x] in "six":
asnum = int(6)
elif a[0][1][x] in "seven":
asnum = int(7)
elif a[0][1][x] in "eight":
asnum = int(8)
elif a[0][1][x] in "nine":
asnum = int(9)
elif a[0][1][x] in "ten":
asnum = int(10)
elif a[0][1][x] in "%":
asnum = int(10)
else:
asnum = int(a[0][1][x])
if asnum > max:
max = asnum
level.append(max)
len_l -= 1
# ____________________________________________________________________________
filed = []
len_f = len(a[0][2])
for x in range(0, 3):
if len_f > 0:
if a[0][2][x] in "oop":
filed.append("%java%")
elif a[0][2][x] in "artificial intelligence":
filed.append("%ai%")
elif a[0][2][x] in "machine learning":
filed.append("%ml%")
elif a[0][2][x] in "%":
filed.append("%")
else:
filed.append('%' + a[0][2][x] + '%')
elif len_f <= 0:
filed.append('')
len_f -= 1
# _______________________________________________________________________________
program_language = []
len_p = len(a[0][3])
for x in range(0, 3):
if len_p > 0:
if a[0][3][x] in "HTML5":
program_language.append("%HTML%")
elif a[0][3][x] in "CSS3":
program_language.append("%CSS%")
elif a[0][3][x] in "%":
program_language.append("%")
else:
program_language.append('%' + a[0][3][x] + '%')
elif len_p <= 0:
program_language.append('')
len_p -= 1
# ____________________________________________________________________
vendor_name = []
len_v = len(a[0][4])
for x in range(0, 3):
if len_v > 0:
if a[0][4][x] in "python":
vendor_name.append("%python institute%")
elif a[0][4][x] in "red hat":
vendor_name.append("%red hat academy%")
elif a[0][4][x] in "%": # chage it
vendor_name.append("%")
else:
vendor_name.append('%' + a[0][4][x] + '%')
elif len_v <= 0:
vendor_name.append('')
len_v -= 1
# ________________________________________________________________________
duration = []
len_d = len(a[0][5])
for x in range(0, 3):
if len_d > 0:
if a[0][5][x] in "%":
duration.append("%")
else:
duration.append('%' + a[0][5][x] + '%')
elif len_d <= 0:
duration.append('')
len_d -= 1
cursor.execute(
"SELECT name , v_username , pre_c , exams , urllink FROM certificate WHERE (major like ? or major like ? or major like ?)and (level <= ?) and (field like ? or field like ? or field like ? ) and (prog_l like ? or prog_l like 'null' or prog_l like ? or prog_l like ?)and (v_username like ? or v_username like ? or v_username like ?) and (duration like ? or duration like ? or duration like ?)",
(major[0], major[1], major[2], level[0], filed[0], filed[1], filed[2],
program_language[0],
program_language[1], program_language[2], vendor_name[0], vendor_name[1], vendor_name[2], duration[0],
duration[1], duration[2]))
result_preC = cursor.fetchall()
seen = set()
uniq = []
# print('result: ',result_preC)
# to take the duplicate pre-certificate
for x in result_preC:
if x[2] not in seen:
uniq.append(x[2])
seen.add(x[2])
# to take the accept certificate
# accepted_c = []
count_q7 = uniq.__len__()
# print('uniq:',uniq)
qusion7 = ' '
q_count = 0
for row in uniq:
if row != 'NULL':
# q7 = "Have you taken this pre-certificate", row, "? (yes or no)"
qusion7 += str(q_count) + '-' + row + '</br>'
if row == 'NULL':
accepted_c.append(row)
q_count += 1
count_q7 -= 1
# print(qusion7)
if qusion7.strip():
q7 = 'Do you have any certificates from this list?</br>' + qusion7 + 'Please enter all <b>numbers</b> for certificates you have.'
else:
# todo please change it.
q7 = 'Are you ready to see the result.'
return q7
def uploadResult(data):
cursor.execute("INSERT INTO result (b_id, certificate, vendor, exam, link) VALUES (?, ?, ?, ?, ?)", data)
connection.commit()
def uploadCA(data):
cursor.execute("INSERT INTO CA (question, answer, b_id, complete_chat, response) VALUES (?, ?, ?, ?,?)", data)
# cursor.execute("INSERT INTO CA (question, answer, b_id, complete_chat, response) VALUES (?, ?, ?, ?,?)", data)
connection.commit()
# ______________________________________________________________
@app.route('/get')
def get_bot_response():
global res
global counter
userText = request.args.get('msg')
getinput(userText)
getQuestion()
if counter < 6:
question()
elif counter == 6:
q7_check_ans(uniq, result_preC)
print_result(accepted_c, result_preC, random_id)
counter += 1
elif counter > 6:
# todo: 1- end program 2- reuse it
# counter = 0
res = 'If you want to try again reload this page <3'
x = setinput()
return str(x)
|
{"/Website/env/Lib/site-packages/thinc/v2v.py": ["/Website/env/Lib/site-packages/thinc/neural/_classes/mish.py", "/Website/env/Lib/site-packages/thinc/_registry.py"], "/Website/env/Lib/site-packages/thinc/__init__.py": ["/Website/env/Lib/site-packages/thinc/about.py", "/Website/env/Lib/site-packages/thinc/_registry.py"], "/Website/env/Lib/site-packages/srsly/__init__.py": ["/Website/env/Lib/site-packages/srsly/_pickle_api.py"], "/Website/env/Lib/site-packages/spacy/lang/ur/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/ur/stop_words.py", "/Website/env/Lib/site-packages/spacy/lang/ur/punctuation.py"], "/Website/env/Lib/site-packages/thinc/t2v.py": ["/Website/env/Lib/site-packages/thinc/_registry.py"], "/Website/env/Lib/site-packages/spacy/lang/is/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/is/stop_words.py"], "/Website/env/Lib/site-packages/thinc/tests/unit/test_imports.py": ["/Website/env/Lib/site-packages/thinc/i2v.py", "/Website/env/Lib/site-packages/thinc/v2v.py", "/Website/env/Lib/site-packages/thinc/t2t.py", "/Website/env/Lib/site-packages/thinc/t2v.py", "/Website/env/Lib/site-packages/thinc/misc.py"], "/Website/env/Lib/site-packages/thinc/t2t.py": ["/Website/env/Lib/site-packages/thinc/neural/_classes/multiheaded_attention.py", "/Website/env/Lib/site-packages/thinc/_registry.py"], "/Website/env/Lib/site-packages/spacy/lang/sl/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/sl/stop_words.py"], "/Website/env/Lib/site-packages/spacy/lang/et/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/et/stop_words.py"], "/Website/env/Lib/site-packages/srsly/_pickle_api.py": ["/Website/env/Lib/site-packages/srsly/__init__.py"], "/Website/env/Lib/site-packages/spacy/lang/sk/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/sk/stop_words.py"], "/Website/env/Lib/site-packages/spacy/lang/mr/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/mr/stop_words.py"], "/Website/env/Lib/site-packages/thinc/rates.py": ["/Website/env/Lib/site-packages/thinc/_registry.py"], "/Website/env/Lib/site-packages/thinc/i2v.py": ["/Website/env/Lib/site-packages/thinc/_registry.py"], "/Website/env/Lib/site-packages/spacy/lang/cs/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/cs/stop_words.py"], "/Website/env/Lib/site-packages/spacy/lang/it/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/it/tokenizer_exceptions.py"], "/Website/env/Lib/site-packages/thinc/misc.py": ["/Website/env/Lib/site-packages/thinc/_registry.py"], "/Website/env/Lib/site-packages/thinc/neural/_classes/mish.py": ["/Website/env/Lib/site-packages/thinc/__init__.py"], "/Website/env/Lib/site-packages/spacy/lang/eu/__init__.py": ["/Website/env/Lib/site-packages/spacy/lang/eu/stop_words.py", "/Website/env/Lib/site-packages/spacy/lang/eu/lex_attrs.py"]}
|
20,511,522
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/users/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
path('register/',views.RegisterAPIView.as_view()),
]
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,523
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/questions/migrations/0004_alike.py
|
# Generated by Django 3.1.3 on 2021-02-20 13:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('questions', '0003_auto_20210219_1909'),
]
operations = [
migrations.CreateModel(
name='alike',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('answer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='likers', to='questions.answer')),
('liker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,524
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/questions/views.py
|
from rest_framework import status,viewsets,permissions,generics
from rest_framework.views import APIView
from .serializers import QuestionSerializer,AnswerSerializer,QuestionLikeSerializer,AnswerLikeSerializer,ReplySerializer
from .models import Question,Answer,qlike,alike,Reply
from .permissions import IsOwnerOrReadonly
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from rest_framework.generics import get_object_or_404
from .task import question_created,question_answered,question_liked
from decouple import config
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
from rest_framework.status import (
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
HTTP_201_CREATED,
HTTP_204_NO_CONTENT,
)
CACHE_TTL = int(config("CACHE_TTL"))
class QuestionsViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated,IsOwnerOrReadonly]
serializer_class = QuestionSerializer
queryset = Question.objects.all().order_by('-created_at')
lookup_field = 'slug'
def perform_create(self,serializer):
question = serializer.save(author=self.request.user)
question_created.delay(question.id)
@method_decorator(vary_on_cookie)
@method_decorator(cache_page(CACHE_TTL))
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
class AnswerCreateAPIView(generics.CreateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = AnswerSerializer
queryset = Answer.objects.all()
def perform_create(self,serializer):
question = Question.objects.get(slug=self.kwargs['slug'])
if question.answers.filter(author=self.request.user).exists():
raise ValidationError('you already answered this question')
answer = serializer.save(
author=self.request.user,
question = question
)
question_answered.delay(answer.id)
class AnswerListAPIView(generics.ListAPIView):
permission_classes = [permissions.AllowAny]
serializer_class = AnswerSerializer
queryset = Answer.objects.all()
def get_queryset(self):
return self.queryset.filter(question__slug=self.kwargs['slug'])
# '''question = Question.objects.get(slug = self.kwargs['slug'])
# return question.answers.all()'''
@method_decorator(vary_on_cookie)
@method_decorator(cache_page(CACHE_TTL))
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
class AnswerRUDAPIView(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [IsOwnerOrReadonly]
serializer_class = AnswerSerializer
queryset = Answer.objects.all()
def get_queryset(self):
return self.queryset.filter(question__slug=self.kwargs['slug'])
@method_decorator(vary_on_cookie)
@method_decorator(cache_page(CACHE_TTL))
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request,*args,**kwargs)
class QuestionLikeAPIView(APIView):
serializer_class = QuestionLikeSerializer
permission_classes = [permissions.IsAuthenticated]
queryset = qlike.objects.all()
def post(self,request,slug):
question = Question.objects.get(slug=slug)
serializer = QuestionLikeSerializer(data=request.data)
if self.queryset.filter(question=question,liker=self.request.user).exists():
raise ValidationError('already voted')
if serializer.is_valid():
q_like = serializer.save(
question=question,
liker=self.request.user
)
question_liked.delay(q_like.id)
return Response(serializer.data,status=status.HTTP_200_OK)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
def delete(self,request,slug):
question = Question.objects.get(slug=slug)
qs = question.likes.filter(
liker=self.request.user
)
qs.delete()
return Response({'msg':'suucessfully unliked'},status=status.HTTP_204_NO_CONTENT)
class AnswerLikeAPIView(APIView):
serializer_class = AnswerLikeSerializer
permission_classes = [permissions.IsAuthenticated]
queryset = alike.objects.all()
def post(self,request,slug,pk):
answer = Answer.objects.get(question__slug=slug,pk=pk)
serializer = AnswerLikeSerializer(data=request.data)
if answer.likers.filter(liker=self.request.user).exists():
raise ValidationError('already liked')
if serializer.is_valid():
serializer.save(
answer=answer,
liker=self.request.user
)
return Response(serializer.data,status=status.HTTP_200_OK)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
def delete(self,request,slug,pk):
answer = Answer.objects.get(question__slug=slug,pk=pk)
qs = answer.likers.filter(
liker = self.request.user
)
qs.delete()
return Response({'msg':'unliked!'},status=status.HTTP_204_NO_CONTENT)
# class QuestionUser(generics.ListAPIView):
# permission_classes = [permissions.IsAuthenticated]
# serializer_class = QuestionSerializer
# queryset = Question.objects.all()
# def get_queryset(self):
# return self.queryset.filter(author__username=self.kwargs['username'])
class ReplyCreateAPIView(generics.CreateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = ReplySerializer
queryset = Reply.objects.all()
def perform_create(self,serializer):
answer = Answer.objects.get(question__slug=self.kwargs['slug'],pk=self.kwargs['pk'])
qs = self.queryset.filter(answer=answer,author=self.request.user.is_staff)
if not qs:
raise ValidationError('just question owners can reply a question !')
serializer.save(
author = self.request.user,
answer = answer
)
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,525
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/users/serializers.py
|
from rest_framework import serializers
from .models import UserAccount,Profile
from questions.serializers import QuestionSerializer
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = UserAccount
fields = ('email','username','password','id')
extra_kwargs = {
'username':{'min_length':3},
'password':{'write_only':True,'min_length':5,'style':{'input_type':'password'}}
}
def create(self,validate_data):
return UserAccount.objects.create_user(**validate_data)
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,526
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/questions/urls.py
|
from django.urls import path,include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'questions',views.QuestionsViewSet)
urlpatterns = [
path('',include(router.urls)),
path('questions/<slug:slug>/answer/',views.AnswerCreateAPIView.as_view()),
path('questions/<slug:slug>/answers/',views.AnswerListAPIView.as_view()),
path('questions/<slug:slug>/like/',views.QuestionLikeAPIView.as_view()),
path('questions/<slug:slug>/answers/<int:pk>/',views.AnswerRUDAPIView.as_view()),
path('questions/<slug:slug>/answers/<int:pk>/like/',views.AnswerLikeAPIView.as_view()),
path('questions/<slug:slug>/answers/<int:pk>/reply/',views.ReplyCreateAPIView.as_view()),
#path('<slug:username>/',views.QuestionUser.as_view()),
]
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,527
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/questions/models.py
|
from django.db import models
from django.conf import settings
from django.db.models import signals
from django.dispatch import receiver
from django.utils.text import slugify
import uuid
class Question(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='questions')
content = models.CharField(max_length=255)
slug = models.SlugField(max_length=255,unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Answer(models.Model):
question = models.ForeignKey(Question,on_delete=models.CASCADE,related_name='answers')
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='user_answer')
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class qlike(models.Model):
question = models.ForeignKey(Question,on_delete=models.CASCADE,related_name='likes')
liker = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
def __str__(self):
return f"{self.question.content}, {self.liker}"
class alike(models.Model):
answer = models.ForeignKey(Answer,on_delete=models.CASCADE,related_name='likers')
liker = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
class Reply(models.Model):
answer = models.ForeignKey(Answer,on_delete=models.CASCADE,related_name='replies')
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
body = models.TextField()
@receiver(signals.pre_save,sender=Question)
def slugify_content(sender,instance,*args,**kwargs):
instance.slug = slugify(instance.content)+"-"+str(uuid.uuid4())[:4]
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,528
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/questions/admin.py
|
from django.contrib import admin
# Register your models here.
from .models import Question,qlike,alike,Answer,Reply
admin.site.register(Question)
admin.site.register(qlike)
admin.site.register(alike)
admin.site.register(Answer)
admin.site.register(Reply)
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,529
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/users/views.py
|
from rest_framework import status,permissions
from rest_framework.views import APIView
from .serializers import RegisterSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from questions.models import Question
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.decorators import api_view
from .task import user_created
class RegisterAPIView(APIView):
serializer_class = RegisterSerializer
def post(self,request):
serializer = RegisterSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
user_created.delay(user.id)
return Response({
'data':serializer.data,
'ok':'user created'
},status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,530
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/users/task.py
|
import time
from celery import shared_task
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
User = get_user_model()
@shared_task
def user_created(user_id):
user = User.objects.get(id=user_id)
subject = 'welcome!'
message = f'Dear, {user.username} we happy to join us '
email_host = settings.EMAIL_HOST_USER
mail_send = send_mail(subject,message,email_host,[user.email])
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,531
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/questions/serializers.py
|
from rest_framework import serializers
from .models import Question,Answer,qlike,alike,Reply
class AnswerSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField(read_only=True)
answer_likes = serializers.SerializerMethodField()
number_of_replies = serializers.SerializerMethodField()
like_by_req_user = serializers.SerializerMethodField()
class Meta:
model = Answer
exclude = ('updated_at','question',)
def get_answer_likes(self,instance):
return instance.likers.count()
def get_number_of_replies(self,instance):
return instance.replies.count()
def get_like_by_req_user(self,instance):
request = self.context['request']
return instance.likers.filter(liker_id=request.user.id).exists()
class QuestionSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField(read_only=True)
slug = serializers.SlugField(read_only=True)
number_of_likes = serializers.SerializerMethodField()
number_of_answers = serializers.SerializerMethodField()
like_by_req_user = serializers.SerializerMethodField()
user_has_answered = serializers.SerializerMethodField()
class Meta:
model = Question
exclude = ('updated_at',)
lookup_field = 'slug'
def get_number_of_answers(self,instance):
return instance.answers.count()
def get_number_of_likes(self,instance):
'''return qlike.objects.filter(question=instance).count()'''
return instance.likes.count()
def get_like_by_req_user(self,instance):
request = self.context['request']
return instance.likes.filter(liker_id=request.user.id).exists()
def get_user_has_answered(self,instance):
request = self.context['request']
return instance.answers.filter(
author=request.user
).exists()
# return Answer.objects.filter(
# question=instance,author=request.user
# ).exists()
class QuestionLikeSerializer(serializers.ModelSerializer):
liker = serializers.StringRelatedField(read_only=True)
class Meta:
model = qlike
exclude = ('question',)
class AnswerLikeSerializer(serializers.ModelSerializer):
liker = serializers.StringRelatedField(read_only=True)
class Meta:
model = alike
exclude = ('answer',)
class ReplySerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField(read_only=True)
class Meta:
model = Reply
exclude = ('answer',)
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,532
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/users/admin.py
|
from django.contrib import admin
from .models import UserAccount,Profile
admin.site.register(UserAccount)
admin.site.register(Profile)
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,511,533
|
moh-hosseini98/django-rest-quora-like
|
refs/heads/master
|
/questions/task.py
|
import time
from celery import shared_task
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
User = get_user_model()
from .models import Question,Answer,qlike
@shared_task
def question_created(question_id):
question = Question.objects.get(id=question_id)
subject = f'question id {question.id}'
message = f'dear {question.author} your have successfully created question. your question id is {question.id}'
email_host = settings.EMAIL_HOST_USER
mail_send = send_mail(subject,message,email_host,[question.author.email])
@shared_task
def question_answered(answer_id):
answer = Answer.objects.get(id=answer_id)
subject = f' user {answer.author.username} answered your question'
message = f'Dear { answer.question.author.username } answer body is {answer.body}'
email_host = settings.EMAIL_HOST_USER
mail_send = send_mail(subject,message,email_host,[answer.question.author.email])
@shared_task
def question_liked(q_id):
qs = qlike.objects.get(id=q_id)
subject = f' user {qs.liker.username} Liked your question'
message = f'Dear { qs.question.author.username } , {qs.liker.username} liked your question'
email_host = settings.EMAIL_HOST_USER
mail_send = send_mail(subject,message,email_host,[qs.question.author.email])
|
{"/users/urls.py": ["/users/views.py"], "/users/views.py": ["/users/serializers.py", "/questions/models.py", "/users/task.py"], "/questions/views.py": ["/questions/serializers.py", "/questions/models.py", "/questions/task.py"], "/users/serializers.py": ["/questions/serializers.py"], "/questions/admin.py": ["/questions/models.py"], "/questions/serializers.py": ["/questions/models.py"], "/questions/task.py": ["/questions/models.py"]}
|
20,595,485
|
Chelsea-Dover/MushroomHunters
|
refs/heads/master
|
/Morels/Player/views.py
|
from django.shortcuts import render
from django.shortcuts import redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, logout
from django.contrib.auth.views import login
from django.db.models import Q
from Game.models import Game
from Player.models import Player
from Player.forms.forms import UserForm, UserProfileForm
from .models import MyUser
# Create your views here.
def signup(request):
"""Creates user if form is valid"""
if request.user.is_authenticated():
return redirect('/home/')
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
print('form is valid')
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
print(request.FILES)
try:
profile.profilePic = request.FILES['profilePic']
except:
print('there are no files')
profile.save()
registered = True
return redirect('/login/')
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,
'signup.html',
{'user_form': user_form,
'profile_form': profile_form,
'registered': registered} )
def log_in(request):
"""Logs in user is info user has given is valid"""
username = password = ""
if request.user.is_authenticated():
return redirect('/home/')
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('/home/')
return render(request, 'login.html', context_instance=RequestContext(request))
@login_required(login_url='/login')
def user_logout(request):
"""Logs out user"""
logout(request)
return redirect('/login/')
def home(request):
"""If user is logged: Go to home page, Else: Go to signup page"""
if request.user.is_authenticated():
return render(request, 'home.html')
else:
return redirect('/')
def profile(request):
"""Sends info to template"""
user = request.user.username
current_player = MyUser.objects.filter(user=request.user)[0]
member = Player.objects.filter(userPlayer=current_player)
current_games = Game.objects.filter(Q(player_1__in=member) | Q(player_2__in=member))
count = current_games.count()
imagecount = current_player.profilePic
return render(request, 'profile.html', {'user': user,
'current_player': current_player,
'current_games': current_games,
'count': count, 'imagecount': imagecount})
def leader_board(request):
"""Sends info to template"""
users = MyUser.objects.all()
return render(request, 'leaderboard.html', {'users':users})
|
{"/Morels/Game/views.py": ["/Morels/Game/models.py"], "/Morels/Game/admin.py": ["/Morels/Game/models.py"], "/Morels/Player/views.py": ["/Morels/Player/models.py"], "/Morels/Player/admin.py": ["/Morels/Player/models.py"]}
|
20,595,486
|
Chelsea-Dover/MushroomHunters
|
refs/heads/master
|
/Morels/Game/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('Player', '__first__'),
]
operations = [
migrations.CreateModel(
name='Decay',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('decayDeckCard', models.ManyToManyField(default=None, to='Player.Card', related_name='decayCards')),
],
),
migrations.CreateModel(
name='Deck',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('deckCard', models.ManyToManyField(default=None, to='Player.Card', related_name='deckCards')),
],
),
migrations.CreateModel(
name='Forest',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('forestCard', models.ManyToManyField(default=None, to='Player.Card', related_name='forestCards')),
],
),
migrations.CreateModel(
name='FryingPan',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('card_id', models.ForeignKey(to='Player.Card')),
],
),
migrations.CreateModel(
name='Game',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('date', models.DateTimeField(editable=False)),
('decay_id', models.ForeignKey(to='Game.Decay', related_name='decay_id', default=None)),
('deck_id', models.ForeignKey(to='Game.Deck', related_name='deck_id', default=None)),
('forest_id', models.ForeignKey(to='Game.Forest', related_name='forest_id', default=None)),
],
),
migrations.CreateModel(
name='Night',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('nightDeckCard', models.ManyToManyField(default=None, to='Player.Card', related_name='nightCards')),
],
),
migrations.CreateModel(
name='PlayingCard',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('card_id', models.ForeignKey(to='Player.Card')),
('fryingPan_id', models.ForeignKey(to='Game.FryingPan')),
],
),
migrations.AddField(
model_name='game',
name='night_id',
field=models.ForeignKey(to='Game.Night', related_name='night_id', default=None),
),
migrations.AddField(
model_name='game',
name='player_1',
field=models.ForeignKey(related_name='player_1', to='Player.Player'),
),
migrations.AddField(
model_name='game',
name='player_2',
field=models.ForeignKey(related_name='player_2', to='Player.Player'),
),
migrations.AddField(
model_name='game',
name='winner',
field=models.ForeignKey(blank=True, null=True, to='Player.MyUser', default=None),
),
]
|
{"/Morels/Game/views.py": ["/Morels/Game/models.py"], "/Morels/Game/admin.py": ["/Morels/Game/models.py"], "/Morels/Player/views.py": ["/Morels/Player/models.py"], "/Morels/Player/admin.py": ["/Morels/Player/models.py"]}
|
20,595,487
|
Chelsea-Dover/MushroomHunters
|
refs/heads/master
|
/Morels/Player/migrations/0003_player_userplayingcards.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('Player', '0002_player_sticks'),
]
operations = [
migrations.AddField(
model_name='player',
name='userPlayingCards',
field=models.ManyToManyField(related_name='playingcards', to='Player.Card', blank=True),
),
]
|
{"/Morels/Game/views.py": ["/Morels/Game/models.py"], "/Morels/Game/admin.py": ["/Morels/Game/models.py"], "/Morels/Player/views.py": ["/Morels/Player/models.py"], "/Morels/Player/admin.py": ["/Morels/Player/models.py"]}
|
20,595,488
|
Chelsea-Dover/MushroomHunters
|
refs/heads/master
|
/Morels/Game/views.py
|
# IMPORTS
from .models import *
from random import shuffle
from random import choice
from Game.models import Forest, Night, Deck, Decay
from Player.models import Card, User, Player, MyUser
from django.shortcuts import redirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt
# END OF IMPORTS
def make_starting_decks(person, person1):
"""Appending cards into decks"""
# Variables
cards = []
forest = Forest()
forest.save()
night = Night()
night.save()
deck = Deck()
deck.save()
for i in Card.objects.filter().exclude(type__startswith='Night'):
#Appending all cards(except for the ones that's type is "Night") to the list cards
cards.append(i)
shuffle(cards)
num = 0
for c in cards:
# Appending all cards from list cards into forest, userHand, and deck
if num < 8:
forest.forestCard.add(c)
forest.save()
if num > 7 and num < 11:
person.userHand.add(c)
person.save()
if num > 12 and num < 16:
person1.userHand.add(c)
person1.save()
else:
deck.deckCard.add(c)
deck.save()
num += 1
decay = Decay()
decay.save()
for n in Card.objects.filter(type__startswith='Night'):
# Appending all cards with type "Night" into nightDeck
night.nightDeckCard.add(n)
night.save()
list_of_decks = [forest.id, night.id, deck.id, decay.id]
return list_of_decks
def invite(request):
"""Get's all player objects except current user"""
me = request.user
people = User.objects.all().exclude(username=me.username)
return render(request, 'invite.html', {'people': people, 'me': me})
def new_game(request):
""" Creates new Player objects with the given user and current user """
if request.method == 'POST':
player2 = request.POST.get("player2")
user_object = User.objects.filter(username__exact=player2)
real_user = MyUser.objects.get(user=user_object)
person = Player(userPlayer=real_user)
person.save()
player1 = request.user
real_user1 = MyUser.objects.get(user__exact=player1)
person1 = Player(userPlayer=real_user1)
person1.save()
test = make_starting_decks(person, person1)
game_id = create_game(person, person1, test)
return HttpResponseRedirect(reverse('game_urls:game', kwargs={'game_id': game_id}))
else:
return redirect('/invite/')
def create_game(person, person1, test):
""" Creates new game with the right decks and users """
deck = Deck.objects.get(id=test[0])
forest = Forest.objects.get(id=test[1])
night = Night.objects.get(id=test[2])
decay = Decay.objects.get(id=test[3])
players= []
players.append(person1)
players.append(person)
game = Game(player_1=person,
player_2=person1,
current_player=choice(players),
deck_id=deck,
forest_id=forest,
night_id=night,
decay_id=decay,)
game.save()
return game.id
def game(request, game_id):
"""Prints game and calls all other functions (So this is basically main)"""
game = Game.objects.get(pk=game_id)
game_player = game.player_1
player_sticks = 0
hand = []
forest = []
playing = []
decay = []
player_one = Player.objects.get(id=game_player.id)
player_two = Player.objects.get(id=game.player_2.id)
current_player = game.current_player
# Appending information to lists so I can send it to template
if game_player.userPlayer.user.id == request.user.id:
player_sticks = (player_one.sticks)
for i in game.player_1.userHand.filter():
hand.append(i)
for crd in game.player_1.userPlayingCards.filter():
playing.append(crd)
elif game.player_2.userPlayer.user.id == request.user.id:
player_sticks = player_two.sticks
for i in game.player_2.userHand.filter():
hand.append(i)
for crd in game.player_2.userPlayingCards.filter():
playing.append(crd)
else:
return redirect('/home/')
user = request.user.username
for mushroom in game.forest_id.forestCard.filter():
forest.append(mushroom)
for token in game.decay_id.decayDeckCard.filter():
decay.append(token)
test = json.dumps(game_player.userPlayer.user.username)
boop = json.dumps(request.user.username)
# Takes away turn from player and adds winner to game
if game.current_player.turns >= 1:
update(request, game_id)
sell_cards(request, game_id)
play_cards(request, game_id)
else:
if game.player_2.score >= game.player_1.score:
game.winner = game.player_2.userPlayer
game.winner.save()
elif game.player_1.score >= game.player_2.score:
game.winner = game.player_1.userPlayer
game.winner.save()
return render(request, 'game.html', {'hand': hand,
'decay': decay,
'forest': forest,
'game_player': game_player,
'test': test,
'boop': boop,
'game_id': game_id,
'player_sticks': player_sticks,
'current_player': current_player,
'user': user,
'playing': playing
})
@csrf_exempt
def update(request, game_id):
"""Updates userHand and Forest"""
if request.method == 'POST':
post_forest = request.POST.getlist('forest[]')
post_decay = request.POST.getlist('decay[]')
game = Game.objects.get(id=game_id)
forest_obj = game.forest_id
decay_id = game.decay_id
decay_obj = Decay.objects.get(id=decay_id.id)
fore = Forest.objects.get(id=forest_obj.id)
# Calling functions
forest_card(game, post_forest, fore, request)
decay_card(game, post_decay, decay_obj, request)
# Changing decay and forest
decay = game.forest_id.forestCard.get(id=post_forest[1])
other_decay = Card.objects.get(id=decay.id)
decay_obj.decayDeckCard.add(other_decay)
decay_obj.save()
fore.forestCard.remove(decay)
fore.save()
# Calls function to change player
update_player(game)
try:
print("Yoo")
except:
print('no good')
return HttpResponse(
print("blah")
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"})
)
def forest_card(game, post_forest, fore, request):
"""Updates forest"""
post_test = request.POST.getlist('testest[]')
forest = game.forest_id.forestCard.all()
forest_cards = []
num = len(post_forest) - 1
deck = game.deck_id
forest_num = len(post_forest)
# See's if player called this
if len(post_test) >= 0:
for i in forest:
forest_cards.append(i.id)
# Appends to cards_in_forest
cards_in_forest = [str(i) for i in forest_cards]
# Finds missing index in when comparing cards_in forest and post_forest
missing_card = list(set(cards_in_forest) - set(post_forest))
# Sorting list
cards_in_forest.sort()
post_forest.sort()
# Loops through missing_card and appends cards to forest
if forest_num != len(forest_cards):
for i in missing_card:
forest_delcard = game.forest_id.forestCard.filter(id=i)
other_card = Card.objects.get(id=i)
for e in forest_delcard:
if game.player_1.userPlayer.user.id == request.user.id:
fu = Player.objects.get(id=game.player_1.id)
fu.userHand.add(other_card)
fu.save()
elif game.player_2.userPlayer.user.id == request.user.id:
meanie = Player.objects.get(id=game.player_2.id)
meanie.userHand.add(other_card)
meanie.save()
fore.forestCard.remove(e)
fore.save()
# Adds cards to forest until forest length is 8
while num <= 8:
fore.forestCard.add(deck.deckCard.order_by('?').first())
fore.save()
num += 1
def decay_card(game, post_decay, decay_obj, request):
"""Updates decay Basically the forest_card but with decay"""
decay = game.decay_id.decayDeckCard.all()
decay_cards = []
decay_num = len(post_decay)
for i in decay:
decay_cards.append(i.id)
cards_in_decay = []
for i in decay_cards:
cards_in_decay.append(str(i))
missing = list(set(cards_in_decay) - set(post_decay))
if decay_num == 4:
decay_obj.decayDeckCard.clear()
decay_obj.save()
if decay_num != len(decay_cards):
for i in missing:
decay_delcard = game.decay_id.decayDeckCard.filter(id=i)
other_card = Card.objects.get(id=i)
for e in decay_delcard:
if game.player_1.userPlayer.user.id == request.user.id:
player_one = Player.objects.get(id=game.player_1.id)
player_one.userHand.add(other_card)
player_one.save()
elif game.player_2.userPlayer.user.id == request.user.id:
player_two = Player.objects.get(id=game.player_2.id)
player_two.userHand.add(other_card)
player_two.save()
decay_obj.decayDeckCard.remove(e)
decay_obj.save()
@csrf_exempt
def sell_cards(request, game_id):
"""Updates users hand and score"""
if request.method == 'POST':
post_check = request.POST.getlist('sellingCards[]')
game = Game.objects.get(id=game_id)
hand =[]
sell_num = len(post_check)
game_player = game.player_1
if game_player.userPlayer.user.id == request.user.id:
for i in game_player.userHand.all():
hand.append(i.id)
elif game.player_2.userPlayer.user.id == request.user.id:
for i in game.player_2.userHand.all():
hand.append(i.id)
missing_card = list(set(post_check) - set(hand))
for i in missing_card:
if game_player.userPlayer.user.id == request.user.id:
sel_crd = game.player_1.userHand.filter(id=i)
elif game.player_2.userPlayer.user.id == request.user.id:
sel_crd = game.player_2.userHand.filter(id=i)
other_card = Card.objects.get(id=i)
for e in sel_crd:
if game.player_1.userPlayer.user.id == request.user.id:
game.player_1.userHand.remove(e)
game.player_1.userPlayingCards.add(other_card)
game.player_1.score += e.cardValue
game.player_1.save()
elif game.player_2.userPlayer.user.id == request.user.id:
game.player_2.userHand.remove(e)
game.player_2.userPlayingCards.add(other_card)
game.player_2.score += e.cardValue
game.player_2.save()
update_player(game)
try:
print("Yoo")
except:
print('no good')
return HttpResponse(
print("blah")
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
@csrf_exempt
def play_cards(request, game_id):
"""Update userHand sticks"""
# TODO: swap play_cards with sell_cards
if request.method == 'POST':
post_check = request.POST.getlist('sellingCards[]')
game = Game.objects.get(id=game_id)
hand =[]
sell_num = len(post_check)
game_player = game.player_1
if len(post_check) >= 0:
if game_player.userPlayer.user.id == request.user.id:
for i in game_player.userHand.all():
hand.append(i.id)
elif game.player_2.userPlayer.user.id == request.user.id:
for i in game.player_2.userHand.all():
hand.append(i.id)
missing_card = list(set(post_check) - set(hand))
for i in missing_card:
if game_player.userPlayer.user.id == request.user.id:
sel_card = game.player_1.userHand.filter(id=i)
elif game.player_2.userPlayer.user.id == request.user.id:
sel_card = game.player_2.userHand.filter(id=i)
# sel_crd = game.player_2.userHand.filter(id=i)
other_card = Card.objects.get(id=i)
for e in missing_card:
# print(e.stickValue)
if game.player_1.userPlayer.user.id == request.user.id:
# game.player_1.userHand.remove(e)
game.player_1.sticks += e.cardValue
game.player_1.save()
elif game.player_2.userPlayer.user.id == request.user.id:
# game.player_2.userHand.remove(e)
game.player_2.sticks += e.stickValue
game.player_2.save()
update_player(game)
try:
print("Yoo")
except:
print('no good')
return HttpResponse(
print("blah")
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
@csrf_exempt
def buy_cards(request, game_id):
"""Updates userHand and stick"""
post_forest = request.POST.getlist('forest[]')
post_method = request.POST.getlist('method[]')
if len(post_method) >= 1:
game = Game.objects.get(id=game_id)
forest_obj = game.forest_id
fore = Forest.objects.get(id=forest_obj.id)
forest = game.forest_id.forestCard.all()
forest_cards = []
num = len(post_forest) - 1
deck = game.deck_id
forest_num = len(post_forest)
for i in forest:
forest_cards.append(i.id)
card_thats_missing = [str(i) for i in forest_cards]
missing_card = list(set(card_thats_missing) - set(post_forest))
card_thats_missing.sort()
post_forest.sort()
if forest_num != len(forest_cards):
for i in missing_card:
forest_delcard = game.forest_id.forestCard.filter(id=i)
other_card = Card.objects.get(id=i)
for e in forest_delcard:
if game.player_1.userPlayer.user.id == request.user.id:
fu = Player.objects.get(id=game.player_1.id)
fu.userHand.add(other_card)
fu.sticks -= e.stickValue
fu.save()
elif game.player_2.userPlayer.user.id == request.user.id:
meanie = Player.objects.get(id=game.player_2.id)
meanie.userHand.add(other_card)
meanie.sticks -= e.stickValue
meanie.save()
fore.forestCard.remove(e)
fore.save()
while num <= 8:
fore.forestCard.add(deck.deckCard.order_by('?').first())
fore.save()
num += 1
update_player(game)
try:
print("Yoo")
except:
print('no good')
return HttpResponse(
print("blah")
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
def update_player(game):
"""Updates player"""
if game.current_player == game.player_1:
# print(game.current_player)
# print(game.current_player.turns)
game.current_player = game.player_2
game.player_1.turns -= 1
game.player_1.save()
game.save()
elif game.current_player == game.player_2:
print(game.current_player)
print(game.current_player.turns)
game.current_player = game.player_1
game.player_2.turns -= 1
game.player_2.save()
game.save()
|
{"/Morels/Game/views.py": ["/Morels/Game/models.py"], "/Morels/Game/admin.py": ["/Morels/Game/models.py"], "/Morels/Player/views.py": ["/Morels/Player/models.py"], "/Morels/Player/admin.py": ["/Morels/Player/models.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.