├── .DS_Store ├── .TOKEN.txt ├── .gitignore ├── AUX.md ├── README.md ├── __pycache__ ├── decomposer.cpython-39.pyc ├── getToken.cpython-39.pyc ├── problemClassifier.cpython-39.pyc └── utils.cpython-39.pyc ├── decomposer.py ├── frontCover.png ├── getToken.py ├── main.py ├── output ├── .DS_Store ├── archive │ ├── .DS_Store │ ├── blogSite │ │ ├── blogList.js │ │ ├── comments.js │ │ ├── manage.py │ │ └── relatedAndSharing.js │ ├── example2 │ │ ├── .DS_Store │ │ └── root │ │ │ ├── main.py │ │ │ ├── menus.py │ │ │ ├── powerUpsAndMultiplayer.py │ │ │ └── soundAndDifficulty.py │ ├── forexTrader │ │ ├── compare_forex_pairs.js │ │ ├── forex_display.js │ │ ├── forex_scraper.py │ │ └── user_authentication.js │ └── pong │ │ ├── highScoresAndPause.py │ │ ├── main.py │ │ ├── menu.py │ │ └── powerupsAndSound.py └── root │ └── .DS_Store ├── problemClassifier.py ├── requirements.txt ├── sample.png ├── utils.py └── workspace ├── classifiedProblems.yaml └── statement.txt /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/.DS_Store -------------------------------------------------------------------------------- /.TOKEN.txt: -------------------------------------------------------------------------------- 1 | OPENAI_TOKEN_HERE -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/.gitignore -------------------------------------------------------------------------------- /AUX.md: -------------------------------------------------------------------------------- 1 | # GPT Automator 2 | 3 | 4 | 5 | # Aspiration 6 | 7 | 8 | 1. Problem classifier 9 | 2. High level code planner breaks problem down into smallest deliverable components as instructions for the next step. 10 | 3. Code Generator Decomposition Agent: Called for each smallest deliverable increment. 11 | If under 4000 tokens create, if more, call agent with instructions for 4k token piecemeal delivery. 12 | Must include Code only, at end of code block, should include a operation instruction different kind of markup code we will agree, something like. 13 | RUN=PYTHON,FILENAME=main.py,SAVE_LOCATION=src 14 | 4. 4EyesCheck Agent: Iterates all the produced instructions from GPT, checks if it can be parsed properly by automation harness. Also ensures runtime instructions are correct. 15 | 5. File Creator Automation: Saves files in the correct place. 16 | 6. Runner: Executes code based upon step3. 17 | 7. Automated Output Capture 18 | 8 GPT Debugger agent. Setup in the same way where we have a language which says what file to change/replace. 19 | 9. Repeat - once no errors, human checks, Provides feedback into original prompt and repeats. 20 | 21 | 22 | ## implementation 23 | 24 | Create a class for each agent: 25 | 26 | ProblemClassifier 27 | HighLevelCodePlanner 28 | CodeGeneratorDecompositionAgent 29 | FourEyesCheckAgent 30 | FileCreatorAutomation 31 | Runner 32 | AutomatedOutputCapture 33 | GPTDebuggerAgent 34 | Create an orchestrator class ProjectCreator that initializes and calls these agent classes in the appropriate order. 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | # Job examples 44 | 45 | AI-assisted brainstorming software that helps users generate new ideas and concepts by presenting unconventional connections. 46 | 47 | "Create a simple command-line tool that takes a URL as input, downloads the HTML content, and counts the frequency of each word in the HTML content. Display the top 10 most frequent words and their counts." 48 | 49 | 50 | "Develop a weather app that fetches weather data from an API, such as OpenWeatherMap, and displays the current temperature, humidity, and a brief weather description for a given location. The app should have a simple graphical user interface and be able to update the displayed information when the user enters a new location." 51 | 52 | 53 | 54 | 55 | 56 | # --------LEGACY 57 | 58 | 59 | SET UP MULTIPLE GPT AGENTS WITH DIFFERENT INITIAL SYSTEM PROMPTS INCLUDING: 60 | 61 | 62 | - GPT Problem classifier 63 | - GPT Code Generator 64 | - GPT Code RunTime advisor (produces parsable tokens i.e. RUN_MAIN.PY RUN_START.SH etc) 65 | - GPT Code Directory Checker (stiched prompts to ensure all files, code in the right place in the folder) 66 | - Automation Harness Runner - Runs the main.py or instructions given by RunTime advisor 67 | - Automation Harness OutPut Capture - captures terminal, log outputs. 68 | - GPT debugger - Reviews logs/errors and enriches description with provided high level solutions. 69 | 70 | -- LOOP REPEATS with high level solutions passed back into problem classifier 71 | 72 | 73 | ## MORE INFO: 74 | 75 | 1. USER inputs `problem statement` 76 | 2. GPT Problem classifier Agent kicks in, categorises it into: 77 | ```shell 78 | Can solve with code || Can Not solve with code. 79 | ``` 80 | 3. If Can Not - produce Business plan only 81 | 4. If Can: move to next step 82 | 83 | 84 | 85 | # GPT Automator 86 | 87 | Set up multiple GPT agents with different initial system prompts: 88 | 89 | 1. GPT Problem Classifier 90 | 2. GPT Code Generator 91 | 3. GPT Code RunTime Advisor 92 | 4. GPT Code Directory Checker 93 | 5. Automation Harness Runner 94 | 6. Automation Harness Output Capture 95 | 7. GPT Debugger 96 | 97 | User inputs the problem statement: 98 | 99 | Collect the user's problem statement and pass it to the GPT Problem Classifier agent 100 | 101 | ## Problem classification: 102 | 103 | GPT Problem Classifier agent processes the problem statement and categorizes it into "Can solve with code" or "Cannot solve with code" 104 | 105 | ### Handle "Cannot solve with code" cases: 106 | 107 | If the problem statement falls into the "Cannot solve with code" category, generate a business plan or other relevant output 108 | 109 | ### Handle "Can solve with code" cases: 110 | 111 | 1. Pass the problem statement to the GPT Code Generator agent 112 | 2. Generate the necessary code using the GPT Code Generator agent 113 | 3. Pass the generated code to the GPT Code RunTime Advisor agent, which produces parsable tokens (e.g., RUN_MAIN.PY, RUN_START.SH) 114 | 4. Use the GPT Code Directory Checker agent to ensure all files and code are in the right place in the folder 115 | 5. Execute the main.py or instructions given by the GPT Code RunTime Advisor using the Automation Harness Runner 116 | 6. Capture terminal and log outputs using the Automation Harness Output Capture agent 117 | 118 | ## Debugging and iterative improvement: 119 | 120 | 1. Pass the captured outputs to the GPT Debugger agent, which reviews logs/errors and enriches the description with high-level solutions 121 | 2. Loop and repeat the process with the high-level solutions passed back into the GPT Problem Classifier agent for further refinement 122 | 123 | ## Optimize and maintain the system: 124 | 125 | - Continuously analyze the performance metrics to identify bottlenecks or inefficiencies in the process 126 | - Fine-tune the prompts, testing methodology, or other aspects of the system to improve code quality and system performance 127 | - Regularly monitor the system's performance and address any emerging issues 128 | - Update the system as needed to incorporate new GPT models, API changes, or other relevant updates 129 | 130 | ## Document the system and create user guides: 131 | 132 | - Document the architecture, configuration, and usage of the system for future reference 133 | - Develop user guides or tutorials to help users interact with and utilize the GPT Automator 134 | 135 | ## Integrate the solution with existing systems: 136 | 137 | - Develop APIs or interfaces to connect the GPT Automator with existing code repositories, CI/CD pipelines, or other relevant systems 138 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Automator V 0.1 2 | 3 | ![cover image](frontCover.png) 4 | 5 | Automator V 0.1 is a Python-based project that uses OpenAI's GPT-3.5-turbo model to help decompose software development problems into smaller deliverables and generate code for the specified deliverables. 6 | 7 | *contact Adam McMurchie to report issues or post them here* 8 | 9 | 10 | ## What can I do? 11 | 12 | ![](sample.png) 13 | 14 | 15 | - Create me pong in pygame 16 | - Create me a blogging platform 17 | - Create me a website scraper 18 | 19 | # What it does 20 | 21 | 1. Takes your command 22 | 2. Creates all the resources you need in the `output` folder 23 | 24 | **NOTE** You need to do the cleanup of your outputs for now. 25 | 26 | ## Prerequisites 27 | 28 | Before you begin, ensure you have met the following requirements: 29 | 30 | * You have a working Python 3.6+ environment. 31 | * You have an OpenAI API key to access the GPT-3.5-turbo model. 32 | 33 | ## Installation 34 | 35 | To set up the project, follow these steps: 36 | 37 | 1. Clone the repository. 38 | 39 | ```bash 40 | git clone https://github.com/your-username/automator-v0.1.git 41 | cd automator-v0.1 42 | ``` 43 | 44 | 2. Install the required Python packages. 45 | 46 | ```bash 47 | pip install -r requirements.txt 48 | ``` 49 | 50 | 51 | 3. Add your OpenAI API key. 52 | 53 | ```bash 54 | export OPENAI_API_KEY="your-openai-api-key" 55 | ``` 56 | 57 | Or you can create a .TOKEN.txt file in the root directory of the project and add your OpenAI API key. 58 | 59 | ```bash 60 | echo "your-openai-api-key" > .TOKEN.txt 61 | ``` 62 | 63 | ## Usage 64 | 65 | Run the main script to start the application: 66 | 67 | ```bash 68 | python main.py 69 | ``` 70 | 71 | 72 | Follow the prompts to describe your problem, and the application will classify the problem, decompose it into smaller deliverables, and generate code for each deliverable. 73 | 74 | The work will be in the output folder 75 | 76 | ## Limitations 77 | 78 | This is still a work in progress so use it at your own discretion, items to add are: 79 | 80 | 1. Recursive debugging 81 | 2. Better sub componentisation 82 | 3. Consistent sub componentisation 83 | 4. Logging 84 | 5. Automated archiving of output folder 85 | 86 | 87 | 88 | ## Future work 89 | 90 | 91 | *Modularize the code*: Separate the code into multiple Python modules based on functionality. For example, create a separate module for interacting with the OpenAI API, another for parsing YAML files, and another for handling user input and main program flow. 92 | 93 | *Use configuration files*: Instead of hardcoding the API key and other settings in the code, use a configuration file (e.g., JSON, YAML, or INI) to store these settings. This will make it easier to manage and update the configuration without modifying the code. 94 | 95 | *Add error handling and validation*: Improve error handling and validation throughout the code. For example, validate user input, check for the existence of required files, and handle exceptions that might be raised when interacting with external services (e.g., OpenAI API). 96 | 97 | *Add logging*: Implement a proper logging system to capture important events, warnings, and errors during the execution of the application. This will make it easier to troubleshoot and understand the program flow. 98 | 99 | *Improve user interface*: Enhance the user interface by using a more user-friendly library like prompt_toolkit or even building a web interface for a better user experience. 100 | 101 | *Add unit tests*: Write unit tests for different modules and functions to ensure the reliability and correctness of the code. This will help you catch bugs and regressions before they reach production. 102 | 103 | *Add documentation*: Add docstrings to functions and classes to provide more information about their purpose and usage. This will make the code easier to understand and maintain. 104 | 105 | *Use environment variables for sensitive information*: Instead of storing the OpenAI API key in a file, use environment variables to store sensitive information like API keys. This will make it easier to manage secrets and improve security. 106 | 107 | *Use a package manager*: Utilize a package manager like pipenv or poetry to manage dependencies and virtual environments, making it easier for others to set up and use the project. 108 | 109 | *Implement a progress indicator*: When generating code or interacting with external services like the OpenAI API, display a progress indicator to give the user feedback on the progress of the operation. This can be a simple spinner or a more advanced progress bar. 110 | 111 | 112 | 113 | ## Contributing 114 | 115 | Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. 116 | 117 | ## License 118 | 119 | [MIT](https://choosealicense.com/licenses/mit/) 120 | -------------------------------------------------------------------------------- /__pycache__/decomposer.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/__pycache__/decomposer.cpython-39.pyc -------------------------------------------------------------------------------- /__pycache__/getToken.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/__pycache__/getToken.cpython-39.pyc -------------------------------------------------------------------------------- /__pycache__/problemClassifier.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/__pycache__/problemClassifier.cpython-39.pyc -------------------------------------------------------------------------------- /__pycache__/utils.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/__pycache__/utils.cpython-39.pyc -------------------------------------------------------------------------------- /decomposer.py: -------------------------------------------------------------------------------- 1 | import openai 2 | import yaml 3 | import re 4 | import pprint 5 | from termcolor import colored, cprint 6 | import os 7 | 8 | 9 | def generate_code(prompt,openaiObject): 10 | 11 | print('') 12 | cprint('Sending Request', 'yellow',attrs=['blink']) 13 | availableResponses = openaiObject.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "system", "content": prompt}]) 14 | currentResponse = availableResponses['choices'][0]['message']['content'].lstrip() 15 | 16 | return currentResponse 17 | 18 | def process_deliverable(yaml_content, desired_deliverable,openaiObject): 19 | 20 | # Find the desired deliverable 21 | deliverable = None 22 | for d in yaml_content: 23 | if d['DELIVERABLE'] == desired_deliverable: 24 | deliverable = d 25 | break 26 | 27 | if deliverable is None: 28 | raise ValueError(f'DELIVERABLE: {desired_deliverable} not found.') 29 | 30 | location = 'output/' + deliverable['RUNTIME_INSTRUCTIONS']['LOCATION'] 31 | filename = deliverable['RUNTIME_INSTRUCTIONS']['FILENAME'] 32 | 33 | 34 | print("DESIRED DELIVERABLE IS ") 35 | print(desired_deliverable) 36 | print("LOCATION IS ") 37 | print(location) 38 | print("FILENAME IS ") 39 | print(filename) 40 | 41 | print('') 42 | cprint('ready to generate code?','white',attrs=['bold']) 43 | input('') 44 | # Generate and append code in chunks of 400 lines 45 | code_chunk = None 46 | chunkCount = 0 47 | while code_chunk != "": 48 | prompt = f"You are given a YAML file that describes a project broken into multiple deliverables. Your task is to generate code for the specified deliverable in chunks of 150 lines at a time. DO NOT add any extra words, just provide only the code. If there is no more code to provide, just return ##JOB_COMPLETE## \n\nPlease process DELIVERABLE: {desired_deliverable}. \n\n{yaml_content}\n\nPreviously generated code (if any):\n{code_chunk}\n\nGenerate the next 400 lines:" 49 | cprint(prompt + '\n**prompt ends**', 'blue') 50 | 51 | # SENDING REQUEST 52 | code_chunk = generate_code(prompt,openaiObject) 53 | chunkCount += 1 54 | print(code_chunk) 55 | cprint('Received, saving...', 'white') 56 | 57 | 58 | # Create location if not exist 59 | os.makedirs(location, exist_ok=True) 60 | 61 | with open(f"{location}/{filename}", "a") as f: 62 | f.write(code_chunk) 63 | 64 | cprint('Saved', 'yellow') 65 | 66 | # 67 | if('JOB_COMPLETE' in code_chunk): 68 | cprint('Job Complete', 'white') 69 | return() 70 | #input("Continue with next chunk? Number: " + str(chunkCount)) 71 | if(chunkCount>5): 72 | print("Something likely went wrong - chunk at 400 * 5") 73 | input("Exit or continue?") 74 | 75 | 76 | 77 | def decompose(openaiObject): 78 | # Usage: 79 | file_path = 'workspace/classifiedProblems.yaml' 80 | with open(file_path, 'r') as file: 81 | data = file.read() 82 | 83 | 84 | print('printing raw data') 85 | print(data) 86 | 87 | print('Printing as dict') 88 | yaml_content = yaml.safe_load(data) 89 | pprint.pprint(yaml_content) 90 | 91 | 92 | 93 | 94 | 95 | desired_deliverable = 0 96 | for n in range(len(yaml_content)): 97 | process_deliverable(yaml_content, n+1,openaiObject) 98 | -------------------------------------------------------------------------------- /frontCover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/frontCover.png -------------------------------------------------------------------------------- /getToken.py: -------------------------------------------------------------------------------- 1 | import os 2 | import openai 3 | from termcolor import colored, cprint 4 | 5 | def getOpenAPIKey(): 6 | 7 | # ----------------- CALL OPEN AI 8 | 9 | if os.environ.get("OPENAI_API_KEY"): 10 | cprint('Loading Key from Environment variable','yellow') 11 | openai.api_key = os.environ["OPENAI_API_KEY"] 12 | else: 13 | cprint('No key in env vars, attempting to load from file ','yellow') 14 | #keyFile = open('/Users/adammcmurchie/code/tools/davinci/.KEY.txt','r') 15 | keyFile = open('.TOKEN.txt','r') 16 | openai.api_key = keyFile.read() 17 | 18 | print('') 19 | cprint('Loaded','white') 20 | print('') 21 | 22 | return(openai) -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import os 2 | from termcolor import colored, cprint 3 | from art import * 4 | import problemClassifier 5 | from decomposer import * 6 | from getToken import * 7 | 8 | class agent_coordinator(): 9 | def __init__(self): 10 | self.state = 'not started' 11 | self.classifier = problemClassifier.ProblemClassifier() 12 | self.deliverableStatement = None 13 | self.no_deliverables = 0 14 | self.currentDeliv = 0 15 | self.deliverablesArray = [] 16 | self.openaiObject = None 17 | 18 | def mainLoop(self): 19 | 20 | self.openaiObject = getOpenAPIKey() 21 | 22 | if(self.state =='not started'): 23 | self.classifier.get_requirements(self.openaiObject) 24 | if(self.classifier.problem_state == 'solvable_with_code'): 25 | 26 | # IMPORT METRICS 27 | self.problemStatement = self.classifier.problemStatement 28 | self.deliverableStatement = self.classifier.currentResponse 29 | self.no_deliverables = self.classifier.no_deliverables 30 | self.state = 'decompose' 31 | 32 | print('Deliverables : ' + str(self.no_deliverables)) 33 | cprint('Complete! press any key to proceed to the next step', 'white') 34 | input('') 35 | else: 36 | self.state = 'complete' 37 | cprint('Complete! Problem is not solvable with code unfortunately', 'red') 38 | input('') 39 | if(self.state =='decompose'): 40 | decompose(self.openaiObject) 41 | 42 | os.system('clear') 43 | welcomeMessage=text2art("Welcome") 44 | amuMessage=text2art("Automator V 0.1") 45 | print(welcomeMessage) 46 | print(amuMessage) 47 | coordinator = agent_coordinator() 48 | coordinator.mainLoop() 49 | -------------------------------------------------------------------------------- /output/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/output/.DS_Store -------------------------------------------------------------------------------- /output/archive/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/output/archive/.DS_Store -------------------------------------------------------------------------------- /output/archive/blogSite/blogList.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import axios from 'axios'; 3 | import BlogCard from './blogCard'; 4 | 5 | class BlogList extends Component { 6 | state = { 7 | blogList: [], 8 | loading: true, 9 | error: null, 10 | currentPage: 1, 11 | blogsPerPage: 10, 12 | keyword: '', 13 | searchFilter: false, 14 | }; 15 | 16 | componentDidMount() { 17 | this.fetchBlogList(); 18 | } 19 | 20 | fetchBlogList = () => { 21 | axios 22 | .get('/api/blog/') 23 | .then((response) => { 24 | const blogList = response.data; 25 | this.setState({ blogList, loading: false }); 26 | }) 27 | .catch((error) => { 28 | this.setState({ error, loading: false }); 29 | }); 30 | }; 31 | 32 | handlePageChange = (pageNumber) => { 33 | this.setState({ currentPage: pageNumber }); 34 | }; 35 | 36 | handleKeywordChange = (event) => { 37 | const keyword = event.target.value; 38 | this.setState({ keyword }); 39 | }; 40 | 41 | handleSearchFilterChange = () => { 42 | const { searchFilter } = this.state; 43 | this.setState({ searchFilter: !searchFilter }); 44 | }; 45 | 46 | render() { 47 | const { blogList, loading, error, currentPage, blogsPerPage, keyword, searchFilter } = this.state; 48 | 49 | const indexOfLastBlog = currentPage * blogsPerPage; 50 | const indexOfFirstBlog = indexOfLastBlog - blogsPerPage; 51 | const currentBlogs = blogList.slice(indexOfFirstBlog, indexOfLastBlog); 52 | 53 | const filteredBlogs = currentBlogs.filter((blog) => 54 | blog.title.toLowerCase().includes(keyword.toLowerCase()) 55 | ); 56 | 57 | const totalBlogs = searchFilter ? filteredBlogs.length : blogList.length; 58 | const totalPages = Math.ceil(totalBlogs / blogsPerPage); 59 | 60 | const renderBlogCards = loading ? ( 61 |

Loading...

62 | ) : error ? ( 63 |

{error.message}

64 | ) : filteredBlogs.length ? ( 65 | filteredBlogs.map((blog) => ) 66 | ) : ( 67 |

No blogs found.

68 | ); 69 | 70 | const renderPageNumbers = Array.from({ length: totalPages }, (_, index) => index + 1).map((pageNumber) => ( 71 |
  • 72 | 75 |
  • 76 | )); 77 | 78 | return ( 79 |
    80 |
    81 |
    82 |
    83 |

    Latest Blogs

    84 |
    85 |
    86 | 95 |
    96 | 103 |
    104 |
    105 |
    106 |
    107 | {renderBlogCards} 108 | 113 |
    114 |
    115 |
    116 | ); 117 | } 118 | } 119 | 120 | export default BlogList;##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/blogSite/comments.js: -------------------------------------------------------------------------------- 1 | const Comment = (props) => { 2 | const [showCommentBox, setShowCommentBox] = useState(false); 3 | const [reply, setReply] = useState(""); 4 | const [showReplies, setShowReplies] = useState(false); 5 | 6 | const handleSubmit = (event) => { 7 | event.preventDefault(); 8 | //TODO: Implement logic for submitting comment reply 9 | }; 10 | 11 | const handleUpvote = (event) => { 12 | //TODO: Implement logic for upvoting comment 13 | }; 14 | 15 | const handleDownvote = (event) => { 16 | //TODO: Implement logic for downvoting comment 17 | }; 18 | 19 | return ( 20 |
    21 |
    22 |
    {props.userName}
    23 |
    {props.text}
    24 |
    25 | Upvote 26 | Downvote 27 | setShowCommentBox(!showCommentBox)}> 28 | Reply 29 | 30 |
    31 |
    32 |
    33 |
    {props.date}
    34 |
    35 | {showCommentBox && ( 36 |
    37 |
    38 | 44 | 47 |
    48 |
    49 | )} 50 | {props.replies.length > 0 && ( 51 |
    52 | setShowReplies(!showReplies)}> 53 | {showReplies ? "Hide replies" : `View ${props.replies.length} replies`} 54 | 55 | {showReplies && 56 | props.replies.map((reply, index) => ( 57 | 64 | ))} 65 |
    66 | )} 67 |
    68 | ); 69 | }; 70 | 71 | export default Comment;##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/blogSite/manage.py: -------------------------------------------------------------------------------- 1 | # Create virtual environment and install Django 2 | mkdir myproject 3 | cd myproject 4 | python3 -m venv venv 5 | source venv/bin/activate 6 | pip install django 7 | 8 | # Create models for Blog post and user in Django and create migrations 9 | python manage.py startapp blog 10 | python manage.py makemigrations 11 | python manage.py migrate 12 | 13 | # Implement CRUD functionality for Blog post 14 | ## Views ## 15 | from django.shortcuts import render 16 | from .models import Blog 17 | 18 | def blog_list(request): 19 | blogs = Blog.objects.all() 20 | return render(request, 'blog_list.html', {'blogs': blogs}) 21 | 22 | def blog_detail(request, pk): 23 | blog = Blog.objects.get(pk=pk) 24 | return render(request, 'blog_detail.html', {'blog': blog}) 25 | 26 | def blog_create(request): 27 | if request.method == 'POST': 28 | # Create a form instance and populate it with data from the request (binding): 29 | form = BlogForm(request.POST) 30 | # Check if the form is valid: 31 | if form.is_valid(): 32 | # Save the blog data to the database: 33 | form.save() 34 | # Redirect to blog list view: 35 | return redirect('blog_list') 36 | else: 37 | # Create an empty form instance: 38 | form = BlogForm() 39 | return render(request, 'blog_create.html', {'form': form}) 40 | 41 | def blog_update(request, pk): 42 | blog = get_object_or_404(Blog, pk=pk) 43 | if request.method == 'POST': 44 | # Create a form instance and populate it with data from the request (binding): 45 | form = BlogForm(request.POST, instance=blog) 46 | # Check if the form is valid: 47 | if form.is_valid(): 48 | # Save the updated blog data to the database: 49 | form.save() 50 | # Redirect to blog list view: 51 | return redirect('blog_list') 52 | else: 53 | # Create a form instance with pre-populated data: 54 | form = BlogForm(instance=blog) 55 | return render(request, 'blog_update.html', {'form': form}) 56 | 57 | def blog_delete(request, pk): 58 | blog = get_object_or_404(Blog, pk=pk) 59 | blog.delete() 60 | return redirect('blog_list') 61 | 62 | ## URLs ## 63 | from django.urls import path 64 | from . import views 65 | 66 | urlpatterns = [ 67 | path('', views.blog_list, name='blog_list'), 68 | path('/', views.blog_detail, name='blog_detail'), 69 | path('create/', views.blog_create, name='blog_create'), 70 | path('/update/', views.blog_update, name='blog_update'), 71 | path('/delete/', views.blog_delete, name='blog_delete'), 72 | ] 73 | 74 | ## Forms ## 75 | from django import forms 76 | from .models import Blog 77 | 78 | class BlogForm(forms.ModelForm): 79 | class Meta: 80 | model = Blog 81 | fields = ('title', 'content', 'author') 82 | 83 | # Implement user authentication and authorization using Django built-in authentication system 84 | python manage.py createsuperuser 85 | ## Follow prompts to create superuser 86 | 87 | ## Views ## 88 | from django.shortcuts import render, redirect 89 | from django.contrib.auth.forms import AuthenticationForm 90 | from django.contrib.auth import login, authenticate, logout 91 | 92 | def login_view(request): 93 | if request.method == 'POST': 94 | # Create an instance of built-in form with data from request: 95 | form = AuthenticationForm(data=request.POST) 96 | if form.is_valid(): 97 | # Authenticate the user: 98 | user = form.get_user() 99 | login(request, user) 100 | return redirect('blog_list') 101 | else: 102 | # Create an empty form instance: 103 | form = AuthenticationForm() 104 | return render(request, 'login.html', {'form': form}) 105 | 106 | def logout_view(request): 107 | logout(request) 108 | return redirect('login') 109 | 110 | ## URLs ## 111 | from django.urls import path 112 | from . import views 113 | 114 | urlpatterns = [ 115 | path('login/', views.login_view, name='login'), 116 | path('logout/', views.logout_view, name='logout'), 117 | ] 118 | 119 | ## Templates ## 120 | 121 | {% extends 'base.html' %} 122 | {% block content %} 123 |

    Login

    124 |
    125 | {% csrf_token %} 126 | {{ form.as_p }} 127 | 128 |
    129 | {% endblock %} 130 | 131 | ## Decorators ## 132 | from django.contrib.auth.decorators import login_required 133 | 134 | @login_required 135 | def blog_create(request): 136 | ... 137 | 138 | # Build frontend using React library for displaying blogs and interacting with API 139 | ## Install dependancies ## 140 | npx create-react-app client 141 | cd client 142 | npm install axios react-router-dom 143 | 144 | ## Create Components ## 145 | ### App.js ### 146 | import React from 'react'; 147 | import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; 148 | import BlogList from './components/BlogList'; 149 | 150 | function App() { 151 | return ( 152 | 153 | 154 | 155 | 156 | 157 | ); 158 | } 159 | 160 | export default App; 161 | 162 | ### BlogList.js ### 163 | import React, { Component } from 'react'; 164 | import axios from 'axios'; 165 | 166 | class BlogList extends Component { 167 | state = { 168 | blogs: [] 169 | }; 170 | 171 | componentDidMount() { 172 | axios.get('/api/blogs') 173 | .then(res => { 174 | const blogs = res.data; 175 | this.setState({ blogs }); 176 | }); 177 | } 178 | 179 | render() { 180 | return ( 181 |
    182 |

    Blog List

    183 |
      184 | {this.state.blogs.map(blog =>
    • {blog.title}
    • )} 185 |
    186 |
    187 | ); 188 | } 189 | } 190 | 191 | export default BlogList; 192 | 193 | ### Routing ### 194 | ## Create urls.py file in blog app ## 195 | from django.urls import path 196 | from .views import BlogListView 197 | 198 | urlpatterns = [ 199 | path('api/blogs/', BlogListView.as_view()) 200 | ] 201 | 202 | ## Update views.py to accept API requests ## 203 | from django.views.generic import ListView 204 | from .models import Blog 205 | from django.http import JsonResponse 206 | 207 | class BlogListView(ListView): 208 | model = Blog 209 | template_name = 'blog_list.html' 210 | queryset = Blog.objects.all() 211 | 212 | def get(self, request, *args, **kwargs): 213 | blogs = list(Blog.objects.values()) 214 | return JsonResponse(blogs, safe=False) 215 | 216 | ## Update settings.py to accept React requests ## 217 | ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] 218 | CORS_ORIGIN_WHITELIST = [ 219 | 'http://localhost:3000', 220 | ] 221 | MIDDLEWARE = [ 222 | 'corsheaders.middleware.CorsMiddleware', 223 | 'django.middleware.common.CommonMiddleware', 224 | ... 225 | ] 226 | 227 | ## Update template to host react app ## 228 | {% load static %} 229 | 230 | 231 | 232 | My Blog 233 | 234 | 235 |
    236 | 237 | 238 | 239 | 240 | ## Build react app ## 241 | npm run build 242 | cp -r build/ ../static/ 243 | 244 | ## Create django views and linking ## 245 | ### Create home view and template ### 246 | ## views.py 247 | from django.shortcuts import render 248 | from blog.models import Blog 249 | 250 | def home(request): 251 | return render(request, 'home.html', {'blogs': Blog.objects.all()}) 252 | 253 | ## urls.py 254 | from django.urls import path 255 | from .views import home 256 | 257 | urlpatterns = [ 258 | path('', home, name='home'), 259 | ] 260 | 261 | ## home.html 262 | {% extends 'base.html' %} 263 | {% block content %} 264 |

    Blog List

    265 |
      266 | {% for blog in blogs %} 267 |
    • {{ blog.title }}
    • 268 | {% empty %} 269 |
    • No blog posts yet.
    • 270 | {% endfor %} 271 |
    272 | {% endblock %} 273 | 274 | ### Create blog detail view and template ### 275 | ## views.py 276 | def blog_detail(request, pk): 277 | blog = Blog.objects.get(pk=pk) 278 | return render(request, 'blog_detail.html', {'blog': blog}) 279 | 280 | ## urls.py 281 | from django.urls import path 282 | from .views import home, blog_detail 283 | 284 | urlpatterns = [ 285 | path('', home, name='home'), 286 | path('/', blog_detail, name='blog_detail') 287 | ] 288 | 289 | ## blog_detail.html 290 | {% extends 'base.html' %} 291 | {% block content %} 292 |

    {{ blog.title }}

    293 |

    {{ blog.author }} {{ blog.date }}

    294 |
    295 | {{ blog.content|safe }} 296 | {% endblock %} 297 | 298 | ## Update BlogList Component in App.js ## 299 | import React from 'react'; 300 | import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; 301 | import BlogList from './components/BlogList'; 302 | import BlogDetail from './components/BlogDetail'; 303 | 304 | function App() { 305 | return ( 306 | 307 | 308 | 309 | 310 | 311 | 312 | ); 313 | } 314 | 315 | export default App; 316 | 317 | ## Create BlogDetail Component ## 318 | ### BlogDetail.js ### 319 | import React, { Component } from 'react'; 320 | import axios from 'axios'; 321 | 322 | class BlogDetail extends Component { 323 | state = { 324 | blog: null 325 | }; 326 | 327 | componentDidMount() { 328 | const { match: { params } } = this.props; 329 | axios.get(`/api/blogs/${params.id}/`) 330 | .then(res => { 331 | const blog = res.data; 332 | this.setState({ blog }); 333 | }); 334 | } 335 | 336 | render() { 337 | const { blog } = this.state; 338 | if (blog === null) return (

    Loading ...

    ) 339 | return ( 340 |
    341 |

    {blog.title}

    342 |

    {blog.author} {blog.date}

    343 |
    344 |

    {blog.content}

    345 |
    346 | ); 347 | } 348 | } 349 | 350 | export default BlogDetail; 351 | 352 | ## Create appropriate url ## 353 | ### Update urls.py in blog app ### 354 | from django.urls import path 355 | from .views import BlogListView, BlogDetailView 356 | 357 | urlpatterns = [ 358 | path('api/blogs/', BlogListView.as_view()), 359 | path('api/blogs//', BlogDetailView.as_view()), 360 | ] 361 | 362 | ### Update views.py in blog app ### 363 | from django.views.generic import ListView, DetailView 364 | from django.http import JsonResponse 365 | from .models import Blog 366 | 367 | class BlogDetailView(DetailView): 368 | model = Blog 369 | template_name = 'blog_detail.html' 370 | queryset = Blog.objects.all() 371 | context_object_name = 'blog' 372 | 373 | def get(self, request, *args, **kwargs): 374 | blog = self.get_object() 375 | blog_dict = { 376 | 'id': blog.id, 377 | 'title': blog.title, 378 | 'content': blog.content, 379 | 'author': blog.author.username, 380 | 'date': blog.date.strftime("%b %d %Y"), 381 | } 382 | return JsonResponse(blog_dict, safe=False)# Implement nested comments for better organization 383 | ## Models ## 384 | from django.db import models 385 | from django.contrib.auth.models import User 386 | 387 | class Comment(models.Model): 388 | content = models.CharField(max_length=500) 389 | author = models.ForeignKey(User, on_delete=models.CASCADE) 390 | parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies') 391 | blog = models.ForeignKey(Blog, on_delete=models.CASCADE) 392 | 393 | ## Views ## 394 | def comment_create(request, pk): 395 | blog = Blog.objects.get(pk=pk) 396 | if request.method == 'POST': 397 | # Create a form instance and populate it with data from the request (binding): 398 | form = CommentForm(request.POST) 399 | # Check if the form is valid: 400 | if form.is_valid(): 401 | # Save the comment data to the database: 402 | new_comment = form.save(commit=False) 403 | new_comment.author = request.user 404 | new_comment.blog = blog 405 | new_comment.save() 406 | # Redirect to blog detail view: 407 | return redirect('blog_detail', pk=pk) 408 | else: 409 | # Create an empty form instance: 410 | form = CommentForm() 411 | return render(request, 'comment_create.html', {'form': form}) 412 | 413 | ### Templates ### 414 | 415 | {% extends 'base.html' %} 416 | {% block content %} 417 |

    New Comment

    418 |
    419 | {% csrf_token %} 420 | {{ form.as_p }} 421 | 422 |
    423 | {% endblock %} 424 | 425 | 426 | {% extends 'base.html' %} 427 | {% block content %} 428 |

    {{ blog.title }}

    429 |

    {{ blog.author }} {{ blog.date }}

    430 |
    431 | {{ blog.content|safe }} 432 |
    433 |

    Comments:

    434 |
      435 | {% for comment in blog.comment_set.all %} 436 |
    • {{ comment.content }} - {{ comment.author }} - {{ comment.date }}
    • 437 | {% if comment.replies.all %} 438 |
        439 | {% for reply in comment.replies.all %} 440 |
      • {{ reply.content }} - {{ reply.author }} - {{ reply.date }}
      • 441 | {% endfor %} 442 |
      443 | {% endif %} 444 |
      445 | {% endfor %} 446 | {% if not blog.comment_set.all %} 447 |

      No comments so far.

      448 | {% endif %} 449 |
    450 | {% if request.user.is_authenticated %} 451 | Add New Comment+ 452 | {% else %} 453 | Login to Add Comment 454 | {% endif %} 455 | {% endblock %} 456 | 457 | #JOB_COMPLETE# -------------------------------------------------------------------------------- /output/archive/blogSite/relatedAndSharing.js: -------------------------------------------------------------------------------- 1 | const getRelatedPosts = (tags) => { 2 | // implementation here 3 | } 4 | 5 | const shareOnFacebook = (title, link) => { 6 | // implementation here 7 | } 8 | 9 | const shareOnTwitter = (title, link) => { 10 | // implementation here 11 | } 12 | 13 | export { getRelatedPosts, shareOnFacebook, shareOnTwitter };##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/example2/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/output/archive/example2/.DS_Store -------------------------------------------------------------------------------- /output/archive/example2/root/main.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | 4 | # Initialize the game 5 | pygame.init() 6 | 7 | # Set up the screen 8 | screen_width = 800 9 | screen_height = 600 10 | screen = pygame.display.set_mode((screen_width, screen_height)) 11 | pygame.display.set_caption("Pong") 12 | 13 | # Set up the clock 14 | clock = pygame.time.Clock() 15 | 16 | # Set up the colors 17 | black = (0, 0, 0) 18 | white = (255, 255, 255) 19 | 20 | # Set up the fonts 21 | font_small = pygame.font.SysFont(None, 30) 22 | font_medium = pygame.font.SysFont(None, 50) 23 | font_large = pygame.font.SysFont(None, 80) 24 | 25 | # Set up the sound effects 26 | #bounce_sound = pygame.mixer.Sound("bounce.wav") 27 | #wall_sound = pygame.mixer.Sound("wall.wav") 28 | 29 | # Set up the variables for the game 30 | ball_speed = 7 31 | paddle_speed = 7 32 | difficulty = "easy" 33 | ball_x_speed = ball_speed 34 | ball_y_speed = ball_speed 35 | player_score = 0 36 | ai_score = 0 37 | 38 | # Set up the paddle dimensions 39 | paddle_width = 15 40 | paddle_height = 100 41 | 42 | # Set up the ball dimensions 43 | ball_width = 15 44 | ball_height = 15 45 | 46 | # Set up the paddles 47 | player_paddle_x = 50 48 | player_paddle_y = (screen_height / 2) - (paddle_height / 2) 49 | ai_paddle_x = screen_width - 50 - paddle_width 50 | ai_paddle_y = (screen_height / 2) - (paddle_height / 2) 51 | 52 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/example2/root/menus.py: -------------------------------------------------------------------------------- 1 | score_font = pygame.font.Font('freesansbold.ttf', 32) # Load font for displaying score 2 | player1_score = 0 # Set initial score for player 1 3 | player2_score = 0 # Set initial score for player 2 4 | 5 | def update_scores(): # Function to update score display 6 | score1 = score_font.render('Player 1 Score: ' + str(player1_score), True, (255, 255, 255)) 7 | score2 = score_font.render('Player 2 Score: ' + str(player2_score), True, (255, 255, 255)) 8 | screen.blit(score1, (50, 50)) 9 | screen.blit(score2, (screen_width - score2.get_width() - 50, 50)) 10 | 11 | def display_menu(): # Function to display main menu 12 | menu_font = pygame.font.Font('freesansbold.ttf', 64) # Load font for main menu text 13 | menu_title = menu_font.render('PONG MENU', True, (255, 255, 255)) 14 | menu_start = score_font.render('START GAME', True, (255, 255, 255)) 15 | menu_quit = score_font.render('QUIT GAME', True, (255, 255, 255)) 16 | menu_options = [menu_start, menu_quit] 17 | 18 | selected_option = 0 # Initialize selected option to first option 19 | menu_running = True # Set menu_running flag to True 20 | 21 | while True: # Main game loop 22 | for event in pygame.event.get(): 23 | if event.type == pygame.QUIT: 24 | pygame.quit() 25 | sys.exit() 26 | elif event.type == pygame.KEYDOWN: # Check for key presses 27 | if event.key == pygame.K_ESCAPE: # Exit game if player presses escape key 28 | pygame.quit() 29 | sys.exit() 30 | 31 | if menu_running: # Check if main menu is currently displayed 32 | if event.key == pygame.K_UP: # Move selection up on menu 33 | selected_option = (selected_option - 1) % len(menu_options) 34 | elif event.key == pygame.K_DOWN: # Move selection down on menu 35 | selected_option = (selected_option + 1) % len(menu_options) 36 | elif event.key == pygame.K_RETURN: # Select current option on menu 37 | if selected_option == 0: # Start new game 38 | menu_running = False # Set menu_running flag to False 39 | # Reset game variables 40 | ball.x = screen_width / 2 41 | ball.y = screen_height / 2 42 | ball.angle = random.uniform(-math.pi / 4, math.pi / 4) 43 | player1.y = (screen_height - player1.height) / 2 44 | player2.y = (screen_height - player2.height) / 2 45 | player2.speed = 10 # Reset AI paddle speed to default 46 | # Reset scores 47 | player1_score = 0 48 | player2_score = 0 49 | 50 | elif selected_option == 1: # Quit game 51 | pygame.quit() 52 | sys.exit() 53 | 54 | if menu_running: # Display main menu if it is currently running 55 | display_menu() 56 | else: # Otherwise, display game screen and update game logic 57 | screen.fill((0, 0, 0)) 58 | update_scores() 59 | ball.update() 60 | player1.update() 61 | player2.update() 62 | powerup.update() 63 | pygame.display.update() 64 | 65 | # Check for collision between ball and paddles 66 | if ball.rect.colliderect(player1.rect): 67 | ball.bounce(player1) 68 | elif ball.rect.colliderect(player2.rect): 69 | ball.bounce(player2) 70 | 71 | # Check for collision between ball and walls 72 | if ball.y < 0: 73 | ball.angle = -ball.angle 74 | elif ball.y > screen_height: 75 | ball.angle = -ball.angle 76 | elif ball.x < 0: 77 | player2_score += 1 78 | ball.x = screen_width / 2 79 | ball.y = screen_height / 2 80 | ball.angle = random.uniform(-math.pi / 4, math.pi / 4) 81 | powerup.reset() 82 | elif ball.x > screen_width: 83 | player1_score += 1 84 | ball.x = screen_width / 2 85 | ball.y = screen_height / 2 86 | ball.angle = random.uniform(-math.pi / 4, math.pi / 4) 87 | powerup.reset()##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/example2/root/powerUpsAndMultiplayer.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | 4 | # Powerup variables 5 | POWERUP_SPEED_CHANGE = 2 6 | POWERUP_PADDLE_SIZE_CHANGE = 50 7 | POWERUP_DURATION_SECONDS = 10 8 | 9 | # Colors 10 | BLACK = (0, 0, 0) 11 | WHITE = (255, 255, 255) 12 | 13 | # Game window dimensions 14 | WINDOW_WIDTH = 800 15 | WINDOW_HEIGHT = 600 16 | 17 | # Paddle variables 18 | PADDLE_WIDTH = 10 19 | PADDLE_HEIGHT = 100 20 | PADDLE_SPEED = 5 21 | 22 | # Ball variables 23 | BALL_WIDTH = 10 24 | BALL_HEIGHT = 10 25 | BALL_SPEED = 5 26 | 27 | # Multiplayer variables 28 | PLAYER_ONE_CONTROLS = { 29 | "up": pygame.K_w, 30 | "down": pygame.K_s 31 | } 32 | PLAYER_TWO_CONTROLS = { 33 | "up": pygame.K_UP, 34 | "down": pygame.K_DOWN 35 | } 36 | 37 | class Paddle: 38 | def __init__(self, x, y, up_key, down_key): 39 | self.rect = pygame.Rect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT) 40 | self.speed = PADDLE_SPEED 41 | self.up_key = up_key 42 | self.down_key = down_key 43 | 44 | def move_up(self): 45 | self.rect.y -= self.speed 46 | if self.rect.top < 0: 47 | self.rect.top = 0 48 | 49 | def move_down(self): 50 | self.rect.y += self.speed 51 | if self.rect.bottom > WINDOW_HEIGHT: 52 | self.rect.bottom = WINDOW_HEIGHT 53 | 54 | class Ball: 55 | def __init__(self): 56 | self.rect = pygame.Rect(WINDOW_WIDTH/2-BALL_WIDTH/2, WINDOW_HEIGHT/2-BALL_HEIGHT/2, BALL_WIDTH, BALL_HEIGHT) 57 | self.speed_x = BALL_SPEED 58 | self.speed_y = BALL_SPEED 59 | self.last_hit = None 60 | 61 | def move(self): 62 | self.rect.x += self.speed_x 63 | self.rect.y += self.speed_y 64 | 65 | if self.rect.left < 0 or self.rect.right > WINDOW_WIDTH: 66 | self.speed_x *= -1 67 | 68 | if self.rect.top < 0 or self.rect.bottom > WINDOW_HEIGHT: 69 | self.speed_y *= -1 70 | 71 | def detect_collision(self, paddles): 72 | for paddle in paddles: 73 | if self.rect.colliderect(paddle.rect) and paddle != self.last_hit: 74 | self.speed_x *= -1 75 | self.last_hit = paddle 76 | return True 77 | 78 | return False 79 | 80 | class PowerUp: 81 | def __init__(self, x, y): 82 | self.rect = pygame.Rect(x, y, 10, 10) 83 | self.speed = 2 84 | self.type = random.choice(["increase_speed", "decrease_speed", "increase_paddle_size", "decrease_paddle_size"]) 85 | self.start_time = 0 86 | 87 | def move(self): 88 | self.rect.y += self.speed 89 | 90 | if self.rect.bottom > WINDOW_HEIGHT: 91 | self.kill() 92 | 93 | def activate(self, player_one, player_two, ball): 94 | if self.type == "increase_speed": 95 | ball.speed_x += POWERUP_SPEED_CHANGE 96 | ball.speed_y += POWERUP_SPEED_CHANGE 97 | 98 | elif self.type == "decrease_speed": 99 | ball.speed_x -= POWERUP_SPEED_CHANGE 100 | ball.speed_y -= POWERUP_SPEED_CHANGE 101 | 102 | elif self.type == "increase_paddle_size": 103 | if self.rect.colliderect(player_one.rect): 104 | player_one.rect.h += POWERUP_PADDLE_SIZE_CHANGE 105 | 106 | elif self.rect.colliderect(player_two.rect): 107 | player_two.rect.h += POWERUP_PADDLE_SIZE_CHANGE 108 | 109 | elif self.type == "decrease_paddle_size": 110 | if self.rect.colliderect(player_one.rect): 111 | player_one.rect.h -= POWERUP_PADDLE_SIZE_CHANGE 112 | 113 | elif self.rect.colliderect(player_two.rect): 114 | player_two.rect.h -= POWERUP_PADDLE_SIZE_CHANGE 115 | 116 | self.start_time = pygame.time.get_ticks() 117 | 118 | def kill(self): 119 | self.rect.y = -1000 120 | 121 | def expired(self): 122 | return (pygame.time.get_ticks() - self.start_time)/1000 >= POWERUP_DURATION_SECONDS 123 | 124 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/example2/root/soundAndDifficulty.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import os 3 | 4 | 5 | class Sound: 6 | def __init__(self, file_path, volume=0.5): 7 | self.sound = pygame.mixer.Sound(file_path) 8 | self.sound.set_volume(volume) 9 | 10 | def play(self): 11 | self.sound.play() 12 | 13 | 14 | class Music: 15 | def __init__(self, file_path, volume=0.5): 16 | self.file_path = file_path 17 | self.volume = volume 18 | self.playing = False 19 | 20 | def play(self): 21 | if not self.playing: 22 | pygame.mixer.music.load(self.file_path) 23 | pygame.mixer.music.set_volume(self.volume) 24 | pygame.mixer.music.play(-1) 25 | self.playing = True 26 | 27 | 28 | class Ball(pygame.sprite.Sprite): 29 | def __init__(self, image_path, speed, bounds): 30 | super().__init__() 31 | self.image = pygame.image.load(image_path).convert_alpha() 32 | self.rect = self.image.get_rect(center=(bounds.centerx, bounds.centery)) 33 | self.speed = speed 34 | self.bounds = bounds 35 | self.direction = pygame.math.Vector2(1, 1).normalize() 36 | 37 | def update(self, dt, paddles): 38 | self.rect.move_ip(self.speed * dt * self.direction.x, self.speed * dt * self.direction.y) 39 | 40 | if self.rect.left < self.bounds.left or self.rect.right > self.bounds.right: 41 | self.direction.x *= -1 42 | self.rect.clamp_ip(self.bounds) 43 | Sound('bounce.wav').play() 44 | 45 | if self.rect.top < self.bounds.top or self.rect.bottom > self.bounds.bottom: 46 | self.direction.y *= -1 47 | self.rect.clamp_ip(self.bounds) 48 | Sound('bounce.wav').play() 49 | 50 | paddle_collision = pygame.sprite.spritecollideany(self, paddles) 51 | if paddle_collision: 52 | self.direction.y *= -1 53 | 54 | if isinstance(paddle_collision, AI): 55 | self.direction.x = (self.rect.centerx - paddle_collision.rect.centerx) / paddle_collision.rect.width 56 | Sound('bounce.wav').play() 57 | 58 | elif isinstance(paddle_collision, Player): 59 | self.direction.x = (self.rect.centerx - paddle_collision.rect.centerx) / (paddle_collision.rect.width * 1.5) 60 | Sound('bounce.wav').play() 61 | 62 | 63 | class Paddle(pygame.sprite.Sprite): 64 | def __init__(self, image_path, bounds): 65 | super().__init__() 66 | self.image = pygame.image.load(image_path).convert_alpha() 67 | self.rect = self.image.get_rect(midbottom=(bounds.centerx, bounds.bottom)) 68 | self.bounds = bounds 69 | self.speed = 0 70 | 71 | def update(self, dt, ball=None): 72 | self.rect.move_ip(self.speed * dt, 0) 73 | self.rect.clamp_ip(self.bounds) 74 | 75 | if ball: 76 | if ball.rect.colliderect(self.rect): 77 | ball.rect.clamp_ip(self.rect.left, self.rect.top, self.rect.right, self.rect.top) 78 | ball.direction.y *= -1 79 | 80 | 81 | class Player(Paddle): 82 | def __init__(self, image_path, bounds, controls): 83 | super().__init__(image_path, bounds) 84 | self.score = 0 85 | self.controls = controls 86 | 87 | def update(self, dt, ball=None): 88 | self.speed = 0 89 | 90 | key_state = pygame.key.get_pressed() 91 | 92 | if key_state[self.controls['LEFT']]: 93 | self.speed = -500 * dt 94 | 95 | elif key_state[self.controls['RIGHT']]: 96 | self.speed = 500 * dt 97 | 98 | super().update(dt, ball) 99 | 100 | 101 | class AI(Paddle): 102 | def __init__(self, image_path, bounds, difficulty): 103 | super().__init__(image_path, bounds) 104 | self.difficulty = difficulty 105 | self.target_x = self.rect.centerx 106 | 107 | def update(self, dt, ball=None): 108 | if ball: 109 | if self.difficulty == 'easy': 110 | self.target_x = ball.rect.centerx 111 | 112 | elif self.difficulty == 'medium': 113 | if ball.rect.centery < self.bounds.bottom / 2: 114 | self.target_x = ball.rect.centerx 115 | else: 116 | self.target_x = self.bounds.centerx 117 | 118 | elif self.difficulty == 'hard': 119 | offset = ball.rect.centerx - self.rect.centerx 120 | self.target_x += offset * 0.3 121 | 122 | self.speed = min(max(self.target_x - self.rect.centerx, -500 * dt), 500 * dt) 123 | 124 | super().update(dt) 125 | 126 | 127 | def main(difficulty='medium'): 128 | pygame.mixer.pre_init(44100, -16, 2, 512) 129 | pygame.init() 130 | 131 | screen = pygame.display.set_mode((800, 600)) 132 | bounds = screen.get_rect() 133 | clock = pygame.time.Clock() 134 | 135 | background = pygame.image.load(os.path.join('assets', 'background.png')).convert() 136 | 137 | font = pygame.font.Font(os.path.join('assets', 'Pixeltype.ttf'), 50) 138 | 139 | players = pygame.sprite.Group( 140 | Player(os.path.join('assets', 'paddle.png'), bounds.inflate(-50, 0), {'LEFT': pygame.K_a, 'RIGHT': pygame.K_d}), 141 | AI(os.path.join('assets', 'paddle.png'), bounds.inflate(-50, 0), difficulty) 142 | ) 143 | 144 | ball = Ball(os.path.join('assets', 'ball.png'), 500, bounds) 145 | sprites = pygame.sprite.Group(ball, *players) 146 | 147 | Music(os.path.join('assets', 'music.mp3')).play() 148 | 149 | def handle_event(event): 150 | if event.type == pygame.QUIT: 151 | pygame.quit() 152 | exit() 153 | 154 | elif event.type == pygame.KEYDOWN: 155 | if event.key == pygame.K_ESCAPE: 156 | pygame.quit() 157 | exit() 158 | 159 | elif event.key == pygame.K_SPACE: 160 | reset() 161 | 162 | def update(dt): 163 | sprites.update(dt, paddles=players.sprites()) 164 | 165 | if ball.rect.bottom > bounds.bottom: 166 | players.sprites()[0].score += 1 167 | reset() 168 | 169 | elif ball.rect.top < bounds.top: 170 | players.sprites()[1].score += 1 171 | reset() 172 | 173 | def draw(): 174 | screen.blit(background, bounds) 175 | 176 | for sprite in sprites: 177 | screen.blit(sprite.image, sprite.rect) 178 | 179 | score_surface = font.render(f'{players.sprites()[0].score} {players.sprites()[1].score}', True, (255, 255, 255)) 180 | screen.blit(score_surface, score_surface.get_rect(midtop=bounds.midtop).move(0, 10)) 181 | 182 | pygame.display.flip() 183 | 184 | def reset(): 185 | ball.rect.center = bounds.center 186 | ball.direction = pygame.math.Vector2(1, 1).rotate(pygame.math.Vector2(1, 0).angle_to(pygame.math.Vector2(-1, 0))) 187 | players.update(0, ball) 188 | pygame.time.wait(1000) 189 | 190 | while True: 191 | dt = clock.tick(60) / 1000 192 | 193 | for event in pygame.event.get(): 194 | handle_event(event) 195 | 196 | update(dt) 197 | draw() 198 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/forexTrader/compare_forex_pairs.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import axios from 'axios'; 3 | import { Line } from 'react-chartjs-2'; 4 | 5 | const CompareForexPairs = () => { 6 | const [forexPairs, setForexPairs] = useState([]); 7 | const [baseCurrency, setBaseCurrency] = useState('USD'); 8 | const [quoteCurrency, setQuoteCurrency] = useState('CAD'); 9 | const [data, setData] = useState({}); 10 | 11 | useEffect(() => { 12 | async function fetchData() { 13 | const response = await axios.get(`/forex/${baseCurrency}/${quoteCurrency}`); 14 | setForexPairs(response.data); 15 | } 16 | fetchData(); 17 | }, [baseCurrency, quoteCurrency]); 18 | 19 | useEffect(() => { 20 | function processData() { 21 | const labels = forexPairs.map((pair) => pair.date); 22 | const closePrices = forexPairs.map((pair) => pair.close); 23 | const openPrices = forexPairs.map((pair) => pair.open); 24 | 25 | setData({ 26 | labels: labels, 27 | datasets: [ 28 | { 29 | label: `${baseCurrency}/${quoteCurrency} Close`, 30 | data: closePrices, 31 | fill: false, 32 | borderColor: '#00FFFF' 33 | }, 34 | { 35 | label: `${baseCurrency}/${quoteCurrency} Open`, 36 | data: openPrices, 37 | fill: false, 38 | borderColor: '#FFFF00' 39 | } 40 | ] 41 | }); 42 | } 43 | 44 | processData(); 45 | }, [forexPairs]); 46 | 47 | const handleBaseCurrencyChange = (event) => { 48 | setBaseCurrency(event.target.value); 49 | }; 50 | 51 | const handleQuoteCurrencyChange = (event) => { 52 | setQuoteCurrency(event.target.value); 53 | }; 54 | 55 | return ( 56 |
    57 |

    Compare Forex Pairs

    58 |
    59 | 68 | 77 |
    78 |
    79 | 80 |
    81 |
    82 | ); 83 | }; 84 | 85 | export default CompareForexPairs; 86 | 87 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/forexTrader/forex_display.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | const { useState, useEffect } = require('react'); 3 | const { Line } = require('react-chartjs-2'); 4 | const { connect } = require('react-redux'); 5 | const { fetchForexData } = require('./actions/forexActions'); 6 | 7 | function ForexDisplay(props) { 8 | const [forexData, setForexData] = useState([]); 9 | const [searchInput, setSearchInput] = useState(''); 10 | const [page, setPage] = useState(1); 11 | const [totalPages, setTotalPages] = useState(1); 12 | 13 | useEffect(() => { 14 | props.fetchForexData(page, searchInput) 15 | .then(response => { 16 | setForexData(response.forexData); 17 | setTotalPages(response.totalPages); 18 | }); 19 | }, [page, searchInput]); 20 | 21 | function handleInputChange(event) { 22 | setSearchInput(event.target.value); 23 | setPage(1); 24 | } 25 | 26 | function handlePreviousPageClick() { 27 | setPage(page - 1); 28 | } 29 | 30 | function handleNextPageClick() { 31 | setPage(page + 1); 32 | } 33 | 34 | const data = { 35 | labels: forexData.map(data => data.date), 36 | datasets: [ 37 | { 38 | label: 'Forex Price', 39 | data: forexData.map(data => data.price), 40 | fill: false, 41 | backgroundColor: '#0066cc', 42 | borderColor: '#0066cc', 43 | }, 44 | ], 45 | }; 46 | 47 | const options = { 48 | scales: { 49 | xAxes: [ 50 | { 51 | ticks: { 52 | autoSkip: true, 53 | maxTicksLimit: 20, 54 | }, 55 | }, 56 | ], 57 | }, 58 | }; 59 | 60 | return ( 61 |
    62 |

    Forex Prices

    63 |
    64 | 65 | 66 |
    67 | {forexData.length > 0 && 68 |
    69 | 70 | 71 | 72 |
    73 | } 74 | {forexData.length === 0 && 75 |

    Loading...

    76 | } 77 |
    78 | ); 79 | } 80 | 81 | const mapDispatchToProps = { 82 | fetchForexData, 83 | }; 84 | 85 | export default connect(null, mapDispatchToProps)(ForexDisplay); 86 | 87 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/forexTrader/forex_scraper.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | from pymongo import MongoClient 4 | 5 | # Connect to Mongo DB 6 | client = MongoClient('localhost', 27017) 7 | db = client.forex_db 8 | forex_collection = db.forex_collection 9 | 10 | 11 | def get_forex_prices(): 12 | """ 13 | Retrieves forex prices from various sources and stores them in the database 14 | """ 15 | forex_sources = { 16 | 'EUR/USD': 'https://www.investing.com/currencies/eur-usd', 17 | 'GBP/USD': 'https://www.investing.com/currencies/gbp-usd', 18 | 'USD/JPY': 'https://www.investing.com/currencies/usd-jpy', 19 | 'AUD/USD': 'https://www.investing.com/currencies/aud-usd' 20 | } 21 | 22 | # Scrape the forex prices from the sources 23 | for currency_pair, url in forex_sources.items(): 24 | response = requests.get(url) 25 | soup = BeautifulSoup(response.text, 'html.parser') 26 | 27 | # Extract the forex price from the scraped data 28 | forex_price = soup.find('span', {'id': 'last_last'}).text 29 | 30 | # Add the forex price to the database 31 | forex_collection.insert_one({ 32 | 'currency_pair': currency_pair, 33 | 'price': forex_price 34 | }) 35 | 36 | 37 | def predict_next_prices(): 38 | """ 39 | Implements a basic prediction algorithm using historical data to predict next prices for the next five days 40 | """ 41 | # Retrieve historical forex prices from the database 42 | forex_prices = forex_collection.find() 43 | 44 | # Convert the forex prices to a list 45 | forex_prices_list = [price for price in forex_prices] 46 | 47 | # Predict the next forex prices for the next five days using a naive algorithm 48 | predicted_prices = [] 49 | for i in range(1, 6): 50 | next_price = float(forex_prices_list[-1]['price']) + ((i/100) * float(forex_prices_list[-1]['price'])) 51 | predicted_prices.append(next_price) 52 | 53 | return predicted_prices 54 | 55 | 56 | def store_predicted_prices(predicted_prices): 57 | """ 58 | Stores the predicted forex prices in the database 59 | """ 60 | for i, price in enumerate(predicted_prices): 61 | forex_collection.insert_one({ 62 | 'currency_pair': f'Predicted_{i+1}_day', 63 | 'price': price 64 | }) 65 | 66 | 67 | def main(): 68 | """ 69 | Main function for scraping forex prices and predicting next prices 70 | """ 71 | get_forex_prices() 72 | predicted_prices = predict_next_prices() 73 | store_predicted_prices(predicted_prices) 74 | 75 | 76 | if __name__ == '__main__': 77 | main()##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/forexTrader/user_authentication.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const passport = require('passport'); 3 | const session = require('express-session'); 4 | const MongoStore = require('connect-mongo')(session); 5 | 6 | const app = express(); 7 | 8 | // Passport Config 9 | require('./config/passport')(passport); 10 | 11 | // Connect to MongoDB 12 | const mongoose = require('mongoose'); 13 | mongoose.connect('mongodb://localhost/test', { 14 | useNewUrlParser: true, 15 | useCreateIndex: true, 16 | useUnifiedTopology: true, 17 | useFindAndModify: false 18 | }) 19 | .then(() => console.log('MongoDB Connected')) 20 | .catch((err) => console.log(err)); 21 | 22 | // Express body parser 23 | app.use(express.urlencoded({ extended: true })); 24 | 25 | // Express session 26 | app.use(session({ 27 | secret: 'secret', 28 | resave: false, 29 | saveUninitialized: false, 30 | store: new MongoStore({ mongooseConnection: mongoose.connection }) 31 | })); 32 | 33 | // Passport middleware 34 | app.use(passport.initialize()); 35 | app.use(passport.session()); 36 | 37 | // Routes 38 | app.use('/', require('./routes/index')); 39 | app.use('/users', require('./routes/users')); 40 | 41 | const PORT = process.env.PORT || 5000; 42 | 43 | app.listen(PORT, console.log(`Server started on port ${PORT}`)); 44 | 45 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/pong/highScoresAndPause.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import pygame 3 | import os 4 | import csv 5 | 6 | # Define colors 7 | BLACK = (0, 0, 0) 8 | WHITE = (255, 255, 255) 9 | BLUE = (50, 153, 213) 10 | YELLOW = (250, 218, 94) 11 | GREEN = (152, 245, 171) 12 | 13 | # Define screen dimensions and other constants 14 | SCREEN_WIDTH = 800 15 | SCREEN_HEIGHT = 600 16 | BOTTOM_PANEL_HEIGHT = 100 17 | BALL_RADIUS = 10 18 | PADDLE_WIDTH = 10 19 | PADDLE_HEIGHT = 80 20 | PADDLE_SPEED = 5 21 | BALL_SPEED = 5 22 | TITLE_FONT_SIZE = 50 23 | TEXT_FONT_SIZE = 30 24 | SCORE_FONT_SIZE = 40 25 | 26 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/pong/main.py: -------------------------------------------------------------------------------- 1 | # Pygame Pong: Deliverable 1 2 | 3 | import pygame 4 | import random 5 | 6 | # Define the colors we will use in RGB format 7 | BLACK = (0, 0, 0) 8 | WHITE = (255, 255, 255) 9 | 10 | # Set the height and width of the screen 11 | SCREEN_WIDTH = 700 12 | SCREEN_HEIGHT = 500 13 | 14 | # Create the ball class 15 | class Ball(object): 16 | def __init__(self): 17 | self.x = SCREEN_WIDTH / 2 18 | self.y = SCREEN_HEIGHT / 2 19 | self.radius = 10 20 | self.speedx = 5 21 | self.speedy = 5 22 | 23 | def update(self): 24 | # Update the ball's position based on its speed 25 | self.x += self.speedx 26 | self.y += self.speedy 27 | 28 | # Bounce off the top and bottom walls 29 | if self.y <= self.radius or self.y >= SCREEN_HEIGHT - self.radius: 30 | self.speedy = -self.speedy 31 | 32 | # Bounce off the paddles 33 | if (self.speedx < 0 and self.x - self.radius <= player1.x + player1.width and 34 | player1.y <= self.y <= player1.y + player1.height): 35 | self.speedx = -self.speedx 36 | elif (self.speedx > 0 and self.x + self.radius >= player2.x and 37 | player2.y <= self.y <= player2.y + player2.height): 38 | self.speedx = -self.speedx 39 | 40 | # If the ball goes off the screen, reset it 41 | if self.x < 0 or self.x > SCREEN_WIDTH: 42 | self.__init__() 43 | 44 | def display(self, screen): 45 | pygame.draw.circle(screen, WHITE, (int(self.x), int(self.y)), self.radius) 46 | 47 | def collide(self): 48 | self.speedx = -self.speedx 49 | 50 | # Create the paddle class 51 | class Paddle(object): 52 | def __init__(self, x): 53 | self.x = x 54 | self.y = SCREEN_HEIGHT / 2 55 | self.width = 10 56 | self.height = 75 57 | self.speed = 5 58 | 59 | def update(self): 60 | # Move the paddle up or down depending on the arrow key pressed 61 | keys = pygame.key.get_pressed() 62 | if keys[pygame.K_UP]: 63 | self.y -= self.speed 64 | elif keys[pygame.K_DOWN]: 65 | self.y += self.speed 66 | 67 | # Make sure the paddle doesn't go off the top or bottom of the screen 68 | if self.y < 0: 69 | self.y = 0 70 | elif self.y > SCREEN_HEIGHT - self.height: 71 | self.y = SCREEN_HEIGHT - self.height 72 | 73 | def display(self, screen): 74 | pygame.draw.rect(screen, WHITE, pygame.Rect(self.x, self.y, self.width, self.height)) 75 | 76 | # Initialize Pygame 77 | pygame.init() 78 | 79 | # Set the size of the screen 80 | screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) 81 | 82 | # Set the caption of the window 83 | pygame.display.set_caption("Pygame Pong") 84 | 85 | # Create the ball and paddles 86 | ball = Ball() 87 | player1 = Paddle(25) 88 | player2 = Paddle(SCREEN_WIDTH - 35) 89 | 90 | # Set up the clock 91 | clock = pygame.time.Clock() 92 | 93 | # Set up the font 94 | font = pygame.font.Font(None, 36) 95 | 96 | # Set up the score 97 | score1 = 0 98 | score2 = 0 99 | 100 | # Set up the game loop 101 | done = False 102 | while not done: 103 | # Handle events 104 | for event in pygame.event.get(): 105 | if event.type == pygame.QUIT: 106 | done = True 107 | 108 | # Update the ball and paddles 109 | ball.update() 110 | player1.update() 111 | player2.update() 112 | 113 | # Check for ball collision with the walls 114 | if ball.x <= ball.radius: 115 | score2 += 1 116 | ball.collide() 117 | elif ball.x >= SCREEN_WIDTH - ball.radius: 118 | score1 += 1 119 | ball.collide() 120 | 121 | # Draw the background 122 | screen.fill(BLACK) 123 | 124 | # Draw the ball and paddles 125 | ball.display(screen) 126 | player1.display(screen) 127 | player2.display(screen) 128 | 129 | # Draw the score 130 | score_text = font.render(str(score1) + " - " + str(score2), True, WHITE) 131 | screen.blit(score_text, (SCREEN_WIDTH / 2 - score_text.get_width() / 2, 10)) 132 | 133 | # Update the display 134 | pygame.display.update() 135 | 136 | # Set the frame rate 137 | clock.tick(60) 138 | 139 | # Quit Pygame 140 | pygame.quit() 141 | 142 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/pong/menu.py: -------------------------------------------------------------------------------- 1 | # Import necessary libraries 2 | import pygame 3 | import sys 4 | 5 | # Initialize pygame 6 | pygame.init() 7 | 8 | # Set up display 9 | screen_width = 800 10 | screen_height = 600 11 | screen = pygame.display.set_mode((screen_width, screen_height)) 12 | pygame.display.set_caption("Pong") 13 | 14 | # Set up colors 15 | white = (255, 255, 255) 16 | black = (0, 0, 0) 17 | 18 | # Set up font 19 | font = pygame.font.SysFont("calibri", 40) 20 | 21 | # Set up game variables 22 | player1_score = 0 23 | player2_score = 0 24 | game_over = False 25 | player1_wins = False 26 | player2_wins = False 27 | 28 | # Set up paddles 29 | paddle_width = 15 30 | paddle_height = 60 31 | paddle_speed = 5 32 | player1_paddle_x = 25 33 | player1_paddle_y = screen_height / 2 - paddle_height / 2 34 | player2_paddle_x = screen_width - 25 - paddle_width 35 | player2_paddle_y = screen_height / 2 - paddle_height / 2 36 | 37 | # Set up ball 38 | ball_width = 15 39 | ball_height = 15 40 | ball_speed = 5 41 | ball_x_direction = 1 42 | ball_y_direction = 1 43 | ball_x = screen_width / 2 - ball_width / 2 44 | ball_y = screen_height / 2 - ball_height / 2 45 | 46 | # Set up AI 47 | ai_speed = 3 48 | ai_paddle_up = False 49 | ai_paddle_down = False 50 | 51 | # Define function to draw paddles 52 | def draw_paddles(): 53 | global player1_paddle_y, player2_paddle_y, ai_paddle_up, ai_paddle_down 54 | 55 | # Move AI paddle 56 | if ball_x_direction == 1: 57 | if ball_y + ball_height / 2 > player2_paddle_y + paddle_height / 2: 58 | ai_paddle_down = True 59 | else: 60 | ai_paddle_down = False 61 | if ball_y + ball_height / 2 < player2_paddle_y + paddle_height / 2: 62 | ai_paddle_up = True 63 | else: 64 | ai_paddle_up = False 65 | else: 66 | ai_paddle_up = False 67 | ai_paddle_down = False 68 | 69 | # Move player 1 paddle 70 | keys = pygame.key.get_pressed() 71 | if keys[pygame.K_w] and player1_paddle_y > 0: 72 | player1_paddle_y -= paddle_speed 73 | if keys[pygame.K_s] and player1_paddle_y < screen_height - paddle_height: 74 | player1_paddle_y += paddle_speed 75 | 76 | # Move player 2 paddle with AI or manually 77 | if ai_paddle_up and player2_paddle_y > 0: 78 | player2_paddle_y -= ai_speed 79 | if ai_paddle_down and player2_paddle_y < screen_height - paddle_height: 80 | player2_paddle_y += ai_speed 81 | 82 | # Draw player 1 paddle 83 | pygame.draw.rect(screen, white, (player1_paddle_x, player1_paddle_y, paddle_width, paddle_height)) 84 | 85 | # Draw player 2 paddle 86 | pygame.draw.rect(screen, white, (player2_paddle_x, player2_paddle_y, paddle_width, paddle_height)) 87 | 88 | # Define function to draw ball 89 | def draw_ball(): 90 | global ball_x, ball_y, ball_x_direction, ball_y_direction, player1_score, player2_score, game_over, player1_wins, player2_wins 91 | 92 | # Move ball 93 | ball_x += ball_speed * ball_x_direction 94 | ball_y += ball_speed * ball_y_direction 95 | 96 | # Bounce ball off walls 97 | if ball_y < 0 or ball_y > screen_height - ball_height: 98 | ball_y_direction = -ball_y_direction 99 | if ball_x < 0: 100 | player2_score += 1 101 | ball_x = screen_width / 2 - ball_width / 2 102 | ball_y = screen_height / 2 - ball_height / 2 103 | ball_x_direction = -ball_x_direction 104 | if ball_x > screen_width - ball_width: 105 | player1_score += 1 106 | ball_x = screen_width / 2 - ball_width / 2 107 | ball_y = screen_height / 2 - ball_height / 2 108 | ball_x_direction = -ball_x_direction 109 | 110 | # Bounce ball off paddles 111 | if ball_x_direction == -1 and player1_paddle_x + paddle_width >= ball_x >= player1_paddle_x and player1_paddle_y + paddle_height >= ball_y >= player1_paddle_y: 112 | ball_x_direction = 1 113 | if ball_x_direction == 1 and player2_paddle_x <= ball_x + ball_width <= player2_paddle_x + paddle_width and player2_paddle_y + paddle_height >= ball_y >= player2_paddle_y: 114 | ball_x_direction = -1 115 | 116 | # Check for end game condition 117 | if player1_score >= 10: 118 | game_over = True 119 | player1_wins = True 120 | elif player2_score >= 10: 121 | game_over = True 122 | player2_wins = True 123 | 124 | # Draw ball 125 | pygame.draw.rect(screen, white, (ball_x, ball_y, ball_width, ball_height))# Import necessary libraries 126 | import pygame 127 | import sys 128 | 129 | # Initialize pygame 130 | pygame.init() 131 | 132 | # Set up display 133 | screen_width = 800 134 | screen_height = 600 135 | screen = pygame.display.set_mode((screen_width, screen_height)) 136 | pygame.display.set_caption("Pong") 137 | 138 | # Set up colors and font 139 | white = (255, 255, 255) 140 | black = (0, 0, 0) 141 | font = pygame.font.SysFont("calibri", 40) 142 | 143 | # Set up game variables 144 | player1_score = 0 145 | player2_score = 0 146 | game_over = False 147 | player1_wins = False 148 | player2_wins = False 149 | 150 | # Set up paddles and ball 151 | paddle_width = 15 152 | paddle_height = 60 153 | paddle_speed = 5 154 | player1_paddle_x = 25 155 | player1_paddle_y = screen_height / 2 - paddle_height / 2 156 | player2_paddle_x = screen_width - 25 - paddle_width 157 | player2_paddle_y = screen_height / 2 - paddle_height / 2 158 | ball_width = 15 159 | ball_height = 15 160 | ball_speed = 5 161 | ball_x_direction = 1 162 | ball_y_direction = 1 163 | ball_x = screen_width / 2 - ball_width / 2 164 | ball_y = screen_height / 2 - ball_height / 2 165 | 166 | # Set up AI 167 | ai_speed = 3 168 | ai_paddle_up = False 169 | ai_paddle_down = False 170 | 171 | # Define function to draw paddles 172 | def draw_paddles(): 173 | global player1_paddle_y, player2_paddle_y, ai_paddle_up, ai_paddle_down 174 | 175 | # Move AI paddle 176 | if ball_x_direction == 1: 177 | if ball_y + ball_height / 2 > player2_paddle_y + paddle_height / 2: 178 | ai_paddle_down = True 179 | else: 180 | ai_paddle_down = False 181 | if ball_y + ball_height / 2 < player2_paddle_y + paddle_height / 2: 182 | ai_paddle_up = True 183 | else: 184 | ai_paddle_up = False 185 | else: 186 | ai_paddle_up = False 187 | ai_paddle_down = False 188 | 189 | # Move player 1 paddle 190 | keys = pygame.key.get_pressed() 191 | if keys[pygame.K_w] and player1_paddle_y > 0: 192 | player1_paddle_y -= paddle_speed 193 | if keys[pygame.K_s] and player1_paddle_y < screen_height - paddle_height: 194 | player1_paddle_y += paddle_speed 195 | 196 | # Move player 2 paddle with AI or manually 197 | if ai_paddle_up and player2_paddle_y > 0: 198 | player2_paddle_y -= ai_speed 199 | if ai_paddle_down and player2_paddle_y < screen_height - paddle_height: 200 | player2_paddle_y += ai_speed 201 | 202 | # Draw player 1 paddle 203 | pygame.draw.rect(screen, white, (player1_paddle_x, player1_paddle_y, paddle_width, paddle_height)) 204 | 205 | # Draw player 2 paddle 206 | pygame.draw.rect(screen, white, (player2_paddle_x, player2_paddle_y, paddle_width, paddle_height)) 207 | 208 | # Define function to draw ball 209 | def draw_ball(): 210 | global ball_x, ball_y, ball_x_direction, ball_y_direction, player1_score, player2_score, game_over, player1_wins, player2_wins 211 | 212 | # Move ball 213 | ball_x += ball_speed * ball_x_direction 214 | ball_y += ball_speed * ball_y_direction 215 | 216 | # Bounce ball off walls 217 | if ball_y < 0 or ball_y > screen_height - ball_height: 218 | ball_y_direction = -ball_y_direction 219 | if ball_x < 0: 220 | player2_score += 1 221 | ball_x = screen_width / 2 - ball_width / 2 222 | ball_y = screen_height / 2 - ball_height / 2 223 | ball_x_direction = -ball_x_direction 224 | if ball_x > screen_width - ball_width: 225 | player1_score += 1 226 | ball_x = screen_width / 2 - ball_width / 2 227 | ball_y = screen_height / 2 - ball_height / 2 228 | ball_x_direction = -ball_x_direction 229 | 230 | # Bounce ball off paddles 231 | if ball_x_direction == -1 and player1_paddle_x + paddle_width >= ball_x >= player1_paddle_x and player1_paddle_y + paddle_height >= ball_y >= player1_paddle_y: 232 | ball_x_direction = 1 233 | if ball_x_direction == 1 and player2_paddle_x <= ball_x + ball_width <= player2_paddle_x + paddle_width and player2_paddle_y + paddle_height >= ball_y >= player2_paddle_y: 234 | ball_x_direction = -1 235 | 236 | # Check for end game condition 237 | if player1_score >= 10: 238 | game_over = True 239 | player1_wins = True 240 | elif player2_score >= 10: 241 | game_over = True 242 | player2_wins = True 243 | 244 | # Draw ball 245 | pygame.draw.rect(screen, white, (ball_x, ball_y, ball_width, ball_height)) 246 | 247 | # Define function to display score 248 | def display_score(): 249 | player1_text = font.render(str(player1_score), True, white) 250 | player2_text = font.render(str(player2_score), True, white) 251 | screen.blit(player1_text, (screen_width / 4, 10)) 252 | screen.blit(player2_text, (screen_width * 3 / 4 - player2_text.get_width(), 10)) 253 | 254 | # Run game loop 255 | while not game_over: 256 | for event in pygame.event.get(): 257 | if event.type == pygame.QUIT: 258 | sys.exit() 259 | 260 | # Draw screen 261 | screen.fill(black) 262 | draw_paddles() 263 | draw_ball() 264 | display_score() 265 | 266 | # Update display 267 | pygame.display.update() 268 | 269 | # Display winner 270 | if player1_wins: 271 | winner_text = font.render("Player 1 wins!", True, white) 272 | else: 273 | winner_text = font.render("Player 2 wins!", True, white) 274 | screen.blit(winner_text, (screen_width / 2 - winner_text.get_width() / 2, screen_height / 2 - winner_text.get_height() / 2)) 275 | 276 | # Update display and wait for user to quit 277 | pygame.display.update() 278 | while True: 279 | for event in pygame.event.get(): 280 | if event.type == pygame.QUIT: 281 | sys.exit() 282 | 283 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/archive/pong/powerupsAndSound.py: -------------------------------------------------------------------------------- 1 | ##JOB_COMPLETE## -------------------------------------------------------------------------------- /output/root/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/output/root/.DS_Store -------------------------------------------------------------------------------- /problemClassifier.py: -------------------------------------------------------------------------------- 1 | import openai 2 | from utils import * 3 | from termcolor import colored, cprint 4 | import re 5 | import os 6 | 7 | 8 | class ProblemClassifier: 9 | def __init__(self): 10 | self.state = 'not_started' 11 | self.problem_state = None 12 | self.run_count = 0 13 | self.human_feedback_count = 0 14 | self.fullDialogue = '' 15 | self.currentResponse = '' 16 | self.deliverableArray = [] 17 | self.problemStatement = '' 18 | self.no_deliverables = 0 19 | 20 | def get_requirements(self,openaiObject): 21 | 22 | # -----------------GET USER REQUIREMENT 23 | 24 | user_input = input("Please describe your problem: ") 25 | self.problemStatement = user_input 26 | 27 | # -----------------SAVE PROBLEM STATEMENT 28 | 29 | f = open('workspace/statement.txt','w') 30 | f.write(user_input) 31 | f.close() 32 | 33 | 34 | # -----------------CONSTRUCT THE PROMPT 35 | 36 | 37 | prompt = f""" 38 | This is an automation pipeline, please respond exactly as described below, do not deviate. 39 | First, quantify this problem: {user_input} 40 | If it cannot be solved by code, return only False and do not add any more information. 41 | If it can be solved by code, produce the high-level steps for the smallest seperate deliverable increments in the yaml format like below: 42 | 43 | - DELIVERABLE: 1 44 | Solution: 45 | - Set up backend server using Node.js and Express framework 46 | - Create database schema using MongoDB for storing blog data 47 | - Implement API endpoints for creating, editing, and deleting blogs 48 | - Implement user authentication using Passport.js 49 | - Build frontend using React library for displaying blogs and interacting with API 50 | Dependencies: Node.js, Express, MongoDB, React, Passport.js 51 | SharedState: N/A 52 | AdditionalNotes: N/A 53 | RUNTIME_INSTRUCTIONS: 54 | FILENAME: server.js 55 | RELIES_ON: package.json, client folder 56 | IS_LIBRARY: False 57 | LOCATION: root 58 | EXECUTION_ORDER: 1 59 | EXECUTION_COMMAND: npm start 60 | LANGUAGE: JavaScript 61 | ENV_VARS: N/A 62 | LIBRARIES: Node.js, Express, MongoDB, React, Passport.js 63 | 64 | - DELIVERABLE: 2 65 | Solution: 66 | - Add functionality for displaying a list of all blogs on the homepage 67 | - Implement pagination for displaying limited number of blogs per page 68 | - Implement search functionality for searching blogs by keyword 69 | Dependencies: Node.js, Express, MongoDB, React 70 | SharedState: N/A 71 | AdditionalNotes: Uses existing authentication from Deliverable 1 72 | RUNTIME_INSTRUCTIONS: 73 | FILENAME: blogList.js 74 | RELIES_ON: server.js 75 | IS_LIBRARY: True 76 | LOCATION: root 77 | EXECUTION_ORDER: 2 78 | EXECUTION_COMMAND: N/A 79 | LANGUAGE: JavaScript 80 | ENV_VARS: N/A 81 | LIBRARIES: Node.js, Express, MongoDB, React 82 | 83 | - DELIVERABLE: 3 84 | Solution: 85 | - Create functionality to allow users to comment on blogs 86 | - Implement nested comments for better organization 87 | - Add ability to upvote/downvote comments 88 | Dependencies: Node.js, Express, MongoDB, React 89 | SharedState: N/A 90 | AdditionalNotes: Uses existing authentication from Deliverable 1 91 | RUNTIME_INSTRUCTIONS: 92 | FILENAME: comments.js 93 | RELIES_ON: blogList.js 94 | IS_LIBRARY: True 95 | LOCATION: root 96 | EXECUTION_ORDER: 3 97 | EXECUTION_COMMAND: N/A 98 | LANGUAGE: JavaScript 99 | ENV_VARS: N/A 100 | LIBRARIES: Node.js, Express, MongoDB, React 101 | 102 | - DELIVERABLE: 4 103 | Solution: 104 | - Add functionality for displaying related blog posts based on keyword/tags 105 | - Implement sharing functionality on social media platforms 106 | Dependencies: Node.js, Express, MongoDB, React 107 | SharedState: N/A 108 | AdditionalNotes: Uses existing authentication from Deliverable 1 109 | RUNTIME_INSTRUCTIONS: 110 | FILENAME: relatedAndSharing.js 111 | RELIES_ON: comments.js 112 | IS_LIBRARY: True 113 | LOCATION: root 114 | EXECUTION_ORDER: 4 115 | EXECUTION_COMMAND: N/A 116 | LANGUAGE: JavaScript 117 | ENV_VARS: N/A 118 | LIBRARIES: Node.js, Express, MongoDB, React 119 | 120 | 121 | 122 | Continue for as many deliverables as required, DO NOT include successive deliverables if they are not imported or connected. 123 | Remember, each deliverable does not know about the other, so if imports, file reference or similar is required you need to mention it in the description. 124 | Remember, each deliverable does not know about the other do not use same filename. 125 | 126 | EACH filename must be connected via imports or references in the other files, the deliverables don't know about each other so you need to tell them what code to add to connect the other components. If DELIVERABLE: 1 filename is main.py, DELIVERABLE: 2 filename is extraFunctionality.py, then main.py must import extraFunctionality and the same for successive deliverables. 127 | The goal here is that the output file of each deliverable comes together into a single project folder with no duplication. 128 | Note, the preferred languages are python and bash scripts, but not exclusive such as if building with html, css, etc. 129 | Note: if the deliverable does not have a EXECUTION_COMMAND just put N/A 130 | """ 131 | 132 | 133 | # ----------------- CALL OPEN AI 134 | 135 | print('') 136 | cprint('Requesting....','white',attrs=['blink']) 137 | 138 | availableResponses = openaiObject.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "system", "content": prompt}]) 139 | self.currentResponse = availableResponses['choices'][0]['message']['content'].lstrip() 140 | self.fullDialogue += prompt + ' \n' + self.currentResponse 141 | 142 | os.system('clear') 143 | 144 | # -----------------VALIDATE DELIVERABLES 145 | 146 | 147 | try: 148 | data = yaml.safe_load(self.currentResponse) 149 | print(self.currentResponse) 150 | print('Dict data') 151 | print(data) 152 | print('') 153 | cprint('Does this look correct?', 'yellow',attrs=['bold']) 154 | print('\n\n') 155 | cprint('Continue?', 'white',attrs=['blink']) 156 | input('') 157 | except: 158 | print(self.currentResponse) 159 | cprint('WARNING: Can not verify deliverables match', 'yellow',attrs=['blink']) 160 | exit() 161 | 162 | 163 | # -----------------SAVE 164 | 165 | # Save self.currentResponse to workspace folder as classifiedProblems.txt 166 | workspace_dir = "workspace" 167 | if not os.path.exists(workspace_dir): 168 | os.makedirs(workspace_dir) 169 | with open(os.path.join(workspace_dir, "classifiedProblems.yaml"), "w") as file: 170 | file.write(self.currentResponse + "\n\n") 171 | 172 | 173 | # VALIDATE YAML 174 | passed = validate_yaml('workspace/classifiedProblems.yaml') 175 | if(not passed): 176 | cprint('YAML FAILED, continue?', 'red',attrs=['blink']) 177 | input('') 178 | 179 | 180 | # ----------------- SAVE TO ARRAY 181 | 182 | print('Deliverables are: ') 183 | print(self.currentResponse) 184 | 185 | # SOLVABLE? 186 | if self.currentResponse.lower() == 'false': 187 | self.problem_state = 'not_solvable_with_code' 188 | else: 189 | self.problem_state = 'solvable_with_code' 190 | self.run_count += 1 191 | 192 | self.state = 'classified' 193 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | termcolor==1.1.0 2 | art==5.2 3 | openai==0.27.0 4 | -------------------------------------------------------------------------------- /sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/murchie85/GPT_AUTOMATE/204eff36e2cc7759eee919b639322d7cbfe23c8f/sample.png -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | import sys 3 | 4 | def validate_yaml(file_path): 5 | try: 6 | with open(file_path, 'r') as file: 7 | yaml.safe_load(file) 8 | print(f"The YAML file '{file_path}' is valid.") 9 | return(True) 10 | except yaml.YAMLError as e: 11 | print(f"The YAML file '{file_path}' is not valid.") 12 | print(e) 13 | return(False) -------------------------------------------------------------------------------- /workspace/classifiedProblems.yaml: -------------------------------------------------------------------------------- 1 | - DELIVERABLE: 1 2 | Solution: 3 | - Write functions for basic math operations such as addition, subtraction, multiplication, and division 4 | - Take input from the user for two numbers and the desired operation 5 | - Perform the operation using the corresponding function and display the result 6 | Dependencies: N/A 7 | SharedState: N/A 8 | AdditionalNotes: N/A 9 | RUNTIME_INSTRUCTIONS: 10 | FILENAME: calculator.py 11 | RELIES_ON: N/A 12 | IS_LIBRARY: False 13 | LOCATION: root 14 | EXECUTION_ORDER: 1 15 | EXECUTION_COMMAND: python calculator.py 16 | LANGUAGE: Python 17 | ENV_VARS: N/A 18 | LIBRARIES: N/A 19 | 20 | - DELIVERABLE: 2 21 | Solution: 22 | - Refactor the code into a class-based implementation for better organization 23 | - Add functionality to handle edge cases such as division by zero and invalid inputs 24 | - Allow the user to enter multiple operations in one session 25 | Dependencies: N/A 26 | SharedState: N/A 27 | AdditionalNotes: Imports calculator.py module from Deliverable 1 28 | RUNTIME_INSTRUCTIONS: 29 | FILENAME: calculator2.py 30 | RELIES_ON: calculator.py 31 | IS_LIBRARY: False 32 | LOCATION: root 33 | EXECUTION_ORDER: 2 34 | EXECUTION_COMMAND: python calculator2.py 35 | LANGUAGE: Python 36 | ENV_VARS: N/A 37 | LIBRARIES: N/A 38 | 39 | - DELIVERABLE: 3 40 | Solution: 41 | - Create a graphical user interface (GUI) using tkinter for a more user-friendly experience 42 | - Add additional functions and buttons for advanced mathematical operations such as exponents, square roots, and trigonometry 43 | Dependencies: tkinter 44 | SharedState: N/A 45 | AdditionalNotes: Imports calculator2.py module from Deliverable 2 46 | RUNTIME_INSTRUCTIONS: 47 | FILENAME: calculator_gui.py 48 | RELIES_ON: calculator2.py 49 | IS_LIBRARY: False 50 | LOCATION: root 51 | EXECUTION_ORDER: 3 52 | EXECUTION_COMMAND: python calculator_gui.py 53 | LANGUAGE: Python 54 | ENV_VARS: N/A 55 | LIBRARIES: tkinter 56 | 57 | - DELIVERABLE: 4 58 | Solution: 59 | - Add the ability to save and reload previous calculations from a file 60 | - Allow the user to customize the GUI with themes and fonts 61 | Dependencies: tkinter 62 | SharedState: N/A 63 | AdditionalNotes: Imports calculator_gui.py module from Deliverable 3 64 | RUNTIME_INSTRUCTIONS: 65 | FILENAME: calculator_gui2.py 66 | RELIES_ON: calculator_gui.py 67 | IS_LIBRARY: False 68 | LOCATION: root 69 | EXECUTION_ORDER: 4 70 | EXECUTION_COMMAND: python calculator_gui2.py 71 | LANGUAGE: Python 72 | ENV_VARS: N/A 73 | LIBRARIES: tkinter 74 | 75 | -------------------------------------------------------------------------------- /workspace/statement.txt: -------------------------------------------------------------------------------- 1 | build me a simple calculator in python --------------------------------------------------------------------------------