mirror of
https://github.com/opus-tango/public-python.git
synced 2026-07-17 23:22:43 +00:00
Compare commits
2 Commits
40e9d93c05
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e23e4cdbf2 | ||
|
|
28d8abcfff |
0
tfc-forge-macro/.gitignore → .gitignore
vendored
0
tfc-forge-macro/.gitignore → .gitignore
vendored
397
README.md
397
README.md
@@ -1,15 +1,392 @@
|
||||
# public-python
|
||||
This repository contains all of my public python program releases
|
||||
# TFC Forge Macro
|
||||
|
||||
March 22 2026
|
||||
`tfc-forge-macro` is a small desktop automation tool for `TerraFirmaCraft` forging.
|
||||
It records the screen coordinates of the anvil and recipe UIs, then replays mouse clicks
|
||||
against named slots and buttons so you can run repeatable forging sequences.
|
||||
|
||||
terrafirmagreg_bloomery.py Release v1.0.0
|
||||
A calculator for optimizing iron dust to charcoal ratios to minimize lost iron in the bloomery
|
||||
## Table of Contents
|
||||
|
||||
Sep 19 2019
|
||||
- [What It Does](#what-it-does)
|
||||
- [Requirements](#requirements)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Installation (details)](#installation-details)
|
||||
- [Coordinate Setup](#coordinate-setup)
|
||||
- [Running the Macro](#running-the-macro)
|
||||
- [Running the macro through Macro Deck](#running-the-macro-through-macro-deck)
|
||||
- [Shift-Click Support](#shift-click-support)
|
||||
- [Using a Sequence File](#using-a-sequence-file)
|
||||
- [Command Reference](#command-reference)
|
||||
- [How `coords.json` Works](#how-coordsjson-works)
|
||||
- [Safety and Usage Notes](#safety-and-usage-notes)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [Recommended Workflow](#recommended-workflow)
|
||||
- [TODO](#todo)
|
||||
|
||||
mental_math.py Release v1.0.0
|
||||
Mental math training program utilizing the command line interface
|
||||
## What It Does
|
||||
|
||||
conversions.py Beta v0.1.0
|
||||
A command line temperature conversion calculator
|
||||
The macro works by:
|
||||
|
||||
1. Recording the outer rectangle of the anvil and recipe boxes.
|
||||
2. Storing button and slot positions as normalized offsets inside those rectangles.
|
||||
3. Moving the mouse to named targets such as `L`, `M`, `D`, `R`, `i1`, or `r1`.
|
||||
4. Left-clicking each target in order, with configurable timing between clicks.
|
||||
|
||||
Because the coordinates are normalized, the same `coords.json` can usually survive small
|
||||
position changes as long as the UI layout stays consistent. If your resolution or UI scale
|
||||
changes, you can refresh the saved rectangles without fully recalibrating everything.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python `3.12+`
|
||||
- `pynput`
|
||||
- A desktop session where Python is allowed to control the mouse and keyboard
|
||||
- The TerraFirmaCraft anvil UI open and visible, and an ingot with more than one page worth of recipes (like wrought iron) when you run the setup.py script
|
||||
- The TerraFirmaCraft anvil UI open and visible when you run the macro
|
||||
- [uv](https://docs.astral.sh/uv/getting-started/installation/) installed if you want to use it to install the dependencies and run the scripts
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. [Install uv](https://docs.astral.sh/uv/getting-started/installation/) (a rust based python package manager)
|
||||
2. Clone this repository
|
||||
3. Install the dependencies using uv
|
||||
|
||||
```powershell
|
||||
uv sync
|
||||
```
|
||||
|
||||
2. Open TerraFirmaCraft and open the anvil UI with an ingot with more than one page worth of recipes (like wrought iron) in your inventory (not in the top left inventory slot).
|
||||
3. Run a full calibration once:
|
||||
|
||||
```powershell
|
||||
python setup.py -f
|
||||
```
|
||||
|
||||
4. Test the macro:
|
||||
|
||||
```powershell
|
||||
python main.py -s 2000
|
||||
```
|
||||
|
||||
5. Once you confirm the clicks land correctly, run longer sequences directly or from a file. (The `-s 2000` is a 2 second delay before the macro starts, you can remove it if you want the macro to start immediately).
|
||||
|
||||
## Installation (details)
|
||||
|
||||
### Option 1: Use `uv`
|
||||
|
||||
From the `tfc-forge-macro` folder:
|
||||
|
||||
```powershell
|
||||
uv sync
|
||||
```
|
||||
|
||||
Then run commands with:
|
||||
|
||||
```powershell
|
||||
uv run python setup.py --help
|
||||
uv run python main.py --help
|
||||
```
|
||||
|
||||
### Option 2: Use a normal virtual environment
|
||||
|
||||
```powershell
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\activate
|
||||
pip install pynput
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```powershell
|
||||
python setup.py --help
|
||||
python main.py --help
|
||||
```
|
||||
|
||||
## Coordinate Setup
|
||||
|
||||
`setup.py` is interactive. It waits for you to click points on the screen and writes the
|
||||
results to `coords.json`.
|
||||
|
||||
Press `Esc` at any time during setup to abort.
|
||||
|
||||
### Full Setup
|
||||
|
||||
Run this the first time, or any time the stored offsets are wrong:
|
||||
|
||||
```powershell
|
||||
python setup.py -f
|
||||
```
|
||||
|
||||
Full setup records:
|
||||
|
||||
- Anvil outer box: `tl`, `br`, `width`, `height`. (`tl` stands for top left corner, `br` stands for bottom right corner)
|
||||
- Anvil buttons and controls:
|
||||
`plans`, `weld`, `input1`, `input2`, `L`, `M`, `D`, `P`, `G`, `Y`, `O`, `R`. (The letters correspond to the color of the anvil actions in the anvil GUI in the game)
|
||||
- Inventory and hotbar slots:
|
||||
`i1` through `i27`, and `h1` through `h9` (i2 through h9 are derived from i1)
|
||||
- Recipe outer box: `tl`, `br`, `width`, `height`
|
||||
- Recipe controls:
|
||||
`rlb`, `rrb`, and `r1` through `r18` (r2 through r18 are derived from r1)
|
||||
|
||||
### What Full Setup Asks You To Click
|
||||
|
||||
For the anvil UI:
|
||||
|
||||
1. Top-left corner of the anvil GUI
|
||||
2. Bottom-right corner of the anvil GUI
|
||||
3. The center of each named anvil control
|
||||
4. The center of `i1` (top-left slot of the 9x3 inventory grid)
|
||||
5. Two transition clicks while moving the ingot between input slots
|
||||
6. The `plans` button after the prompt sequence reaches it
|
||||
|
||||
For the recipe UI:
|
||||
|
||||
1. Top-left corner of the recipe GUI
|
||||
2. Bottom-right corner of the recipe GUI
|
||||
3. Left and right recipe scroll/page buttons: `rlb`, `rrb`
|
||||
4. The center of `r1`
|
||||
|
||||
### Refresh Only the GUI Rectangles
|
||||
|
||||
If you already have a good `coords.json`, and only the UI position/scale changed, run setup
|
||||
without `-f`:
|
||||
|
||||
```powershell
|
||||
python setup.py
|
||||
```
|
||||
|
||||
In this mode:
|
||||
|
||||
- the existing `coords.json` must already exist
|
||||
- only the anvil and recipe rectangles are updated
|
||||
- existing slot/button offsets are preserved
|
||||
|
||||
This is useful after changing resolution, window placement, or UI scale while keeping the
|
||||
same relative layout, and is a much faster way to recalibrate than a full setup. You can still perform a full setup any time you want, which will overwrite the existing coordinates file when you're done.
|
||||
|
||||
## Running the macro directly
|
||||
|
||||
The main runner replays a list of slot names:
|
||||
|
||||
```powershell
|
||||
python main.py SLOT SLOT SLOT
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```powershell
|
||||
python main.py -s 1500 i1 i2 i3
|
||||
```
|
||||
|
||||
This waits for the start delay, then clicks the first three inventory slots in order.
|
||||
|
||||
### Default Test Sequence
|
||||
|
||||
If you run `main.py` with no slot arguments and no `--file`, it uses this built-in test:
|
||||
|
||||
```text
|
||||
i1 i2 i3 i4 i5 i6 i7 i8 i9 i1
|
||||
```
|
||||
|
||||
That is useful for validating that your inventory row calibration is correct.
|
||||
|
||||
### Speeding up the macro
|
||||
|
||||
The default delays for click actions are about as fast as they can be while still being reliable. The best way to speed up the macro is to decrease the delay between actions, which you can do by passing the `-d` flag to `main.py` with a smaller number. `-d 5` is reliable, and quite fast, with only 5 milliseconds between clicks, not counting the delay built into the clicks themselves to keep everything reliable.
|
||||
|
||||
## Running the macro through Macro Deck
|
||||
|
||||
The whole reason for making this macro program in the first place was so I could run it through Macro Deck, a macro recording and playback program for Windows that allows you to trigger actions through your phone.
|
||||
|
||||
### Setup Instructions
|
||||
|
||||
Assuming you already followed the [Quick Start](#quick-start) and [Coordinate Setup](#coordinate-setup) instructions and have a coords.json file. The run.vbs file is a wrapper that runs the macro through uv, so you MUST have uv installed and the dependencies synced.
|
||||
|
||||
1. Install the Macro Deck server and a client from https://macro-deck.app/
|
||||
2. Open the server and client and connect them
|
||||
3. In the server interface (on your computer), install the windows utils plugin
|
||||
4. Create a new macro
|
||||
- Add a new action to the macro
|
||||
- Select "Start Application" from windows utils
|
||||
- Set the to the run.vbs file in your tfc-forge-macro folder.
|
||||
- Set the arguments something like `-d 5 --file scripts/bloom-wi_ingot-9.txt`. Any arguments just get passed through to main.py
|
||||
- Save your changes
|
||||
5. Open the anvil UI in the game
|
||||
6. Trigger the macro from a client (like your phone)
|
||||
|
||||
## Shift-Click Support
|
||||
|
||||
Prefix any slot token with `_` to hold `Shift` while clicking it.
|
||||
|
||||
Example:
|
||||
|
||||
```powershell
|
||||
python main.py _i1 _i2 _i3
|
||||
```
|
||||
|
||||
`_i2` means "shift-click `i2`".
|
||||
|
||||
This is the only special token syntax recognized by `main.py`.
|
||||
|
||||
## Using a Sequence File
|
||||
|
||||
Instead of passing slots on the command line, you can put them in a text file and use `--file`.
|
||||
|
||||
Example file:
|
||||
|
||||
```text
|
||||
_i1
|
||||
R R O Y L L L
|
||||
_i2
|
||||
R R Y Y Y L L L
|
||||
```
|
||||
|
||||
Run it with:
|
||||
|
||||
```powershell
|
||||
python main.py --file scripts\example.txt
|
||||
```
|
||||
|
||||
Token parsing rules:
|
||||
|
||||
- commas, spaces, tabs, and newlines all work as separators
|
||||
- empty entries are ignored
|
||||
- if `--file` is provided, slot arguments passed on the command line are ignored
|
||||
- every token must be a valid slot name, or `_slotname` for shift-click
|
||||
|
||||
## Command Reference
|
||||
|
||||
### `main.py`
|
||||
|
||||
```powershell
|
||||
python main.py [options] [SLOT ...]
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `-s`, `--start-delay MS`
|
||||
Wait before starting the sequence. Default: `700` ms.
|
||||
- `-d`, `--delay MS`
|
||||
Wait between clicks. Default: `200` ms.
|
||||
- `--move-settle-ms MS`
|
||||
Pause after moving the cursor before mouse-down. Default: `20` ms.
|
||||
- `--click-hold-ms MS`
|
||||
How long to hold the mouse button down. Default: `30` ms.
|
||||
- `--post-click-ms MS`
|
||||
Pause after mouse-up. Default: `30` ms.
|
||||
- `-c`, `--coords-file PATH`
|
||||
Use a custom coordinates file instead of `coords.json`.
|
||||
- `-f`, `--file PATH`
|
||||
Read tokens from a text file instead of positional arguments.
|
||||
|
||||
Examples:
|
||||
|
||||
```powershell
|
||||
python main.py -s 1200 -d 150 L M D
|
||||
python main.py -c alt-coords.json R R O Y
|
||||
python main.py --file scripts\forge-sequence.txt
|
||||
python main.py --move-settle-ms 40 --click-hold-ms 50 --post-click-ms 40 L L L
|
||||
```
|
||||
|
||||
### `setup.py`
|
||||
|
||||
```powershell
|
||||
python setup.py [options]
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `-f`, `--full`
|
||||
Perform a full calibration from scratch.
|
||||
- `-o`, `--output PATH`
|
||||
Write the generated coordinates file to a custom path.
|
||||
|
||||
Examples:
|
||||
|
||||
```powershell
|
||||
python setup.py -f
|
||||
python setup.py
|
||||
python setup.py -f -o custom-coords.json
|
||||
```
|
||||
|
||||
## How `coords.json` Works
|
||||
|
||||
The saved file has two top-level sections:
|
||||
|
||||
- `anvil`
|
||||
- `recipe`
|
||||
|
||||
Each section stores:
|
||||
|
||||
- `tl`: absolute top-left pixel
|
||||
- `br`: absolute bottom-right pixel
|
||||
- `width`
|
||||
- `height`
|
||||
- normalized offsets for the named clickable targets inside that box
|
||||
|
||||
`main.py` converts those normalized offsets back into screen pixels at runtime.
|
||||
|
||||
That means:
|
||||
|
||||
- changing the monitor resolution or GUI scale may require rerunning `setup.py`
|
||||
- if only the GUI rectangle moved but the internal layout stayed the same, rectangle-only refresh mode may be enough
|
||||
|
||||
## Safety and Usage Notes
|
||||
|
||||
- This tool moves your real mouse cursor and sends real clicks.
|
||||
- Do not touch the mouse while a sequence is running.
|
||||
- Keep the game window visible and in the expected state before the start delay expires.
|
||||
- Start with short sequences until you trust your calibration.
|
||||
- There is no dedicated emergency stop hotkey in `main.py`; use cautious timings and small tests first.
|
||||
- `setup.py` does support `Esc` to abort calibration.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Clicks land slightly off target
|
||||
|
||||
- Rerun `python setup.py`
|
||||
- If the layout changed completely, rerun `python setup.py -f`
|
||||
- Increase `--move-settle-ms` a little
|
||||
- Increase `--click-hold-ms` if the game misses short clicks
|
||||
|
||||
### The final click is sometimes missed
|
||||
|
||||
Increase:
|
||||
|
||||
- `--post-click-ms`
|
||||
- or `--click-hold-ms`
|
||||
|
||||
### The wrong screen area is being clicked after changing resolution or UI scale
|
||||
|
||||
Refresh calibration:
|
||||
|
||||
```powershell
|
||||
python setup.py
|
||||
```
|
||||
|
||||
If that does not fix it:
|
||||
|
||||
```powershell
|
||||
python setup.py -f
|
||||
```
|
||||
|
||||
### `coords.json` is missing
|
||||
|
||||
Create it first:
|
||||
|
||||
```powershell
|
||||
python setup.py -f
|
||||
```
|
||||
|
||||
### A slot name causes an error
|
||||
|
||||
Make sure the token is one of the names listed in this README. `main.py` only understands:
|
||||
|
||||
- defined anvil controls
|
||||
- inventory/hotbar slots
|
||||
- recipe slots and recipe page buttons
|
||||
- optional `_` prefix for shift-click
|
||||
|
||||
## TODO
|
||||
|
||||
- [ ] - Double check the anvil action colors without the resource pack and possibly change the letters or update the README to reflect the base mod
|
||||
- [ ] - Add support for actions other than clicking (like pressing keys)
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
"""
|
||||
conversions.py
|
||||
A command line temperature conversion calculator
|
||||
by Nayan Sawyer
|
||||
started Feb 2019
|
||||
version 0.1.0 Sep 19 2019
|
||||
|
||||
This was a small personal project to make chem class more interesting.
|
||||
I never got around to updating or documenting it, but it's pretty straight forward.
|
||||
|
||||
"""
|
||||
|
||||
def runTemp():
|
||||
inType = input("Input unit(F,C,K): ")
|
||||
while inType == "":
|
||||
inType = input("Input unit(F,C,K): ")
|
||||
outType = input("Output unit(F,C,K): ")
|
||||
while outType == "":
|
||||
outType = input("Output unit(F,C,K): ")
|
||||
inTemp = float(input("Temperature: "))
|
||||
|
||||
|
||||
if inType == "F" or inType == "f":
|
||||
if outType == "K" or outType == "k":
|
||||
print("F: " + str(inTemp) + ", K: " + str(((5/9) * (inTemp-32)) + 273.15))
|
||||
elif outType == "C" or outType == "c":
|
||||
print("F: " + str(inTemp) + ", C: " + str((5/9) * (inTemp-32)))
|
||||
else:
|
||||
print("invalid output unit")
|
||||
|
||||
elif inType == "C"or inType == "c":
|
||||
if outType == "F" or outType == "f":
|
||||
print("C: " + str(inTemp) + ", F: " + str(((9/5) * inTemp) + 32))
|
||||
elif outType == "K" or outType == "k":
|
||||
print("C: " + str(inTemp) + ", K: " + str(inTemp + 273.15))
|
||||
else:
|
||||
print("invalid output unit")
|
||||
|
||||
elif inType == "K" or inType == "k":
|
||||
if outType == "F" or outType == "f":
|
||||
print("K: " + str(inTemp) + ", F: " + str(((9/5) * (inTemp - 273.15)) + 32))
|
||||
elif outType == "C" or outType == "c":
|
||||
print("K: " + str(inTemp) +", C: " + str(inTemp - 273.15))
|
||||
else:
|
||||
print("invalid output unit")
|
||||
|
||||
else:
|
||||
print("invalid input unit")
|
||||
|
||||
|
||||
'''
|
||||
PROGRAM START
|
||||
'''
|
||||
while True:
|
||||
runTemp()
|
||||
print("")
|
||||
526
mental_math.py
526
mental_math.py
@@ -1,526 +0,0 @@
|
||||
"""
|
||||
mental_math.py
|
||||
Mental math training program utilizing the command line interface
|
||||
by Nayan Sawyer
|
||||
started Sep 17 2019
|
||||
version 1.0.0 Sep 19 2019
|
||||
|
||||
IMPORTANT INFORMATION
|
||||
This program uses two sections of GS_timing.py v0.2.1 by Gabriel Staples to calculate user
|
||||
response times. This is not my code and all credit goes to Gabriel Staples. Keep in mind that
|
||||
these selections do not represent the full quality of his work as only the sections of code used
|
||||
in mental_math.py are retained in the selection below the main program. Please do not use or reference
|
||||
his work as seen in my program. If you wish to use or reference a much better time implementation than
|
||||
standard python time, please use the original file and article by Gabriel Staples. The full GS_timing.py
|
||||
file can be found at https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTime and the original article
|
||||
can be found at https://www.electricrcaircraftguy.com/ go to table of contents, it is listed under
|
||||
PYTHON. Needless to say, a huge thank you Gabriel Staples! The timing code would be much less accurate
|
||||
without him!
|
||||
|
||||
MODES
|
||||
All modes utilize integer values only. This includes generated numbers and compatible inputs.
|
||||
For this reason and a few others division is not included. This program's sole purpose is intended
|
||||
to be practicing and training of high speed thinking and memory.
|
||||
Typing "stop" during normal operation of any mode is the correct way to stop the program. It will
|
||||
output final average user response time and jump to the end of the program. Unless "stop" is used
|
||||
the program will continue to produce problems indefinitely.
|
||||
|
||||
Type Simply for practicing typing numbers on the numpad (or any keyboard/configuration)
|
||||
Add This mode is for practicing mental addition. Two numbers are presented between
|
||||
input Minimum(boundMin) and Maximum(boundMax), and the correct answer is the sum of
|
||||
these two numbers.
|
||||
Subtract This mode is for practicing mental subtraction. Virtually the same as mode[Add] except for
|
||||
practicing subtraction, includes additional optional argument to restrict possible answers to
|
||||
positive only.
|
||||
Multiply This mode is for practicing multiplication tables. Arguments include number of multiplication
|
||||
tables, actual integer value[s] of table base[s], and maximum multiplier. The last being the highest
|
||||
number you can be asked to multiply the table base[s] by.
|
||||
|
||||
|
||||
TERMS / ACRONYMS
|
||||
URT User response time
|
||||
AURT Average user response time
|
||||
|
||||
|
||||
VARIABLES
|
||||
global
|
||||
flag An input variable used to determine which mode to run
|
||||
function*
|
||||
boundMin/boundMax Boundary values for generating random numbers
|
||||
n Number. Holds random number, for mode[Type] only
|
||||
a Math variable a. Used for display and calculation
|
||||
b Math variable b. Used for display and calculation
|
||||
t Total. This is the user input answer
|
||||
numBases Number of multiplication bases. User defined, defaults to 1, for mode[Multiplication] only
|
||||
bases Multiplication base(table) list. User defined, for mode[Multiplication] only
|
||||
fails ***DEPRECATED*** Used for accuracy calculation in alpha version, potential future feature
|
||||
time
|
||||
cTime Current time in millis. Used for calculating URT
|
||||
fTime Formatted float time. This is the time difference between question and user response
|
||||
count Counts loop iterations for calculating average user response time
|
||||
total Holds the sum of all response times, used for calculating AURT^
|
||||
|
||||
*many variable names are used in all functions, variables unique to only one function are specified( mode[...] only )
|
||||
|
||||
REFERENCE
|
||||
*1* fTime = round(((millis() - cTime) / 1000), 3)
|
||||
set fTime to the value of
|
||||
|
||||
...(millis() - cTime)...
|
||||
the time difference in milliseconds between start(cTime) and current(millis()) time
|
||||
|
||||
... / 1000)...
|
||||
converted to seconds
|
||||
|
||||
...round( ... , 3)...
|
||||
rounded to 3 decimal places
|
||||
|
||||
*2* str(" " + str(c) + " Problems in " + str(int(int(t) / 60)) + ":" + str(int(t) % 60) +
|
||||
"\n Final average response time: " + str(average) + " seconds per problem")
|
||||
|
||||
Final string should appear as: (example)
|
||||
3 Problems in 0:4
|
||||
Final average response time: 1.61 seconds per problem
|
||||
|
||||
...str(int(int(t) / 60))...
|
||||
to get minutes string remove* any fractions of a second ...int(t)...
|
||||
divide by 60 secs/minute, and remove* any remaining seconds ...int(... / 60)...
|
||||
|
||||
...str(int(t) % 60)...
|
||||
to get string of remaining seconds, remove* any fractions of a second and modulo by 60
|
||||
|
||||
*typecasting a float as an int truncates all information beyond the decimal point
|
||||
|
||||
|
||||
ERROR CODES
|
||||
1 Error printing. Most likely due to bug in time calculation code. Most likely deprecated
|
||||
2 Error with user input in mode[Subtract]. Debugging only, most likely deprecated
|
||||
3 Invalid user input for bases. Common error thrown for any non-integer input during multiplication
|
||||
setup. Has no effect on program function and can be ignored. Primarily for debugging
|
||||
4 This indicates an error while rounding the AURT to 3 decimal places. Typically result of all
|
||||
time variables being zero
|
||||
|
||||
|
||||
|
||||
"""
|
||||
|
||||
import random
|
||||
# For borrowed time code. See important info
|
||||
import ctypes, os
|
||||
|
||||
|
||||
# Generate time string. For compressing code. f = fTime, c = count, t = total
|
||||
def resTime(f, c, t, stop = 0):
|
||||
"""
|
||||
"\n " + str(int(((c - int(stop - 1)) / c) * 100)) + "% Input accuracy" ***DEPRECATED***
|
||||
"""
|
||||
try:
|
||||
if stop >= 1:
|
||||
# Generate float value of average time to nearest hundredth of a second
|
||||
average = round(t / c, 2)
|
||||
# Generate final string. See ref 2
|
||||
return str(" " + str(c) + " Problems in " + str(int(int(t) / 60)) + ":" + secString(t) +
|
||||
"\n Final average response time: " + str(average) + " seconds per problem")
|
||||
else:
|
||||
average = round(t / c, 2)
|
||||
return str("Time passed: " + str(f) + " Average response time = " + str(average))
|
||||
except:
|
||||
return str("Stopped before first submission. Error code 4")
|
||||
|
||||
|
||||
def secString(time):
|
||||
if (int(time) % 60) < 10:
|
||||
return "0" + str(int(time) % 60)
|
||||
else:
|
||||
return str(int(time) % 60)
|
||||
|
||||
|
||||
def getMin():
|
||||
while True:
|
||||
try:
|
||||
val = int(input("Minimum: "))
|
||||
break
|
||||
except:
|
||||
print("Invalid input")
|
||||
return val
|
||||
|
||||
|
||||
def getMax(mIn):
|
||||
while True:
|
||||
try:
|
||||
val = int(input("Maximum: "))
|
||||
while val < mIn:
|
||||
print("Maximum cannot be less than minimum")
|
||||
val = int(input("Maximum: "))
|
||||
break
|
||||
except:
|
||||
print("Invalid input")
|
||||
return val
|
||||
|
||||
|
||||
def isnumber(string):
|
||||
try:
|
||||
if string.isnumeric():
|
||||
return True
|
||||
elif string[1].isnumeric():
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
except:
|
||||
if string[1].isnumeric():
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def modeType():
|
||||
'''MODE[Type]'''
|
||||
# Initialize mode variables
|
||||
boundMin = getMin()
|
||||
boundMax = getMax(boundMin)
|
||||
count = 0
|
||||
total = 0
|
||||
fTime = 0
|
||||
fails = 0
|
||||
while True:
|
||||
# Generate random numbers
|
||||
n = random.randint(int(boundMin), int(boundMax))
|
||||
|
||||
# Get current time in millis
|
||||
cTime = millis()
|
||||
while True:
|
||||
# Try. Prints error instead of crashing if printing error occurs. Most likely deprecated
|
||||
try:
|
||||
# Get user input. For checking math
|
||||
t = input("Number (" + str(n) + "): ")
|
||||
# If input is "stop" end the program
|
||||
if t.lower() == "stop":
|
||||
return resTime(fTime, count, total, fails + 1)
|
||||
# Check if input is numeric
|
||||
elif isnumber(t):
|
||||
# Check that input is same as number, if so break (while True)
|
||||
if int(t) == int(n):
|
||||
break
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
except:
|
||||
print("Invalid input. Error code 1")
|
||||
fails += 1
|
||||
|
||||
# Calculate formatted float time (time difference). ref 1
|
||||
fTime = round(((millis() - cTime) / 1000), 3)
|
||||
|
||||
# Update total response times. Count number of times loop has run. For calculating AURT
|
||||
total += fTime
|
||||
count += 1
|
||||
|
||||
# Print answer "Correct" and response time. The function will only get here given a correct answer, otherwise
|
||||
print("Correct! " + resTime(fTime, count, total)) # it will loop forever (while True) or stop
|
||||
|
||||
|
||||
|
||||
|
||||
'''MODE[Add]'''
|
||||
def modeAdd():
|
||||
# Initialize mode variables
|
||||
boundMin = getMin()
|
||||
boundMax = getMax(boundMin)
|
||||
count = 0
|
||||
total = 0
|
||||
fTime = 0
|
||||
fails = 0
|
||||
while True:
|
||||
# Generate random numbers
|
||||
a = random.randint(int(boundMin), int(boundMax))
|
||||
b = random.randint(int(boundMin), int(boundMax))
|
||||
|
||||
# Get current time in millis
|
||||
cTime = millis()
|
||||
|
||||
# Keep asking for same number if incorrect
|
||||
while True:
|
||||
# Try so you don't crash you mother fucking piece of shit!
|
||||
try:
|
||||
# Get user input for checking math
|
||||
t = input("Sum (" + str(a) + " + " + str(b) + "): ")
|
||||
# Check for program stop
|
||||
if t == "stop":
|
||||
return resTime(fTime, count, total, fails + 1)
|
||||
elif isnumber(t):
|
||||
# Check that input is same as sum, if so break (while True)
|
||||
if int(t) == int(a) + int(b):
|
||||
break
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
except:
|
||||
print("Invalid input. Error code 1")
|
||||
fails += 1
|
||||
|
||||
# Calculate formatted float time (time difference). ref 1
|
||||
fTime = round(((millis() - cTime) / 1000), 3)
|
||||
total += fTime
|
||||
count += 1
|
||||
# Print answer "Correct" and response time. The function will only get here given a correct answer, otherwise
|
||||
print("Correct! " + resTime(fTime, count, total)) # it will loop forever (while True) or stop
|
||||
|
||||
|
||||
|
||||
|
||||
'''MODE[Subtraction]'''
|
||||
def modeSubtract():
|
||||
# Initialize mode variables
|
||||
boundMin = getMin()
|
||||
boundMax = getMax(boundMin)
|
||||
count = 0
|
||||
total = 0
|
||||
fTime = 0
|
||||
fails = 0
|
||||
|
||||
# Additional argument. Given all problems are subtraction does user want to allow negative answers?
|
||||
negativeA = input("Allow possibility of negative answers? (y/n): ")
|
||||
|
||||
# Check that input is valid
|
||||
while negativeA.lower() != "y" and negativeA.lower() != "n":
|
||||
negativeA = input("Allow possibility of negative answers? (y/n): ")
|
||||
|
||||
# If negative answers are undesired make sure the value being subtracted FROM is no lower than 1
|
||||
if negativeA.lower() == "n":
|
||||
if boundMin <= 1:
|
||||
boundMin = 1
|
||||
|
||||
while True:
|
||||
# Generate random numbers
|
||||
if negativeA.lower() == "y":
|
||||
a = random.randint(int(boundMin), int(boundMax))
|
||||
b = random.randint(int(boundMin), int(boundMax))
|
||||
elif negativeA.lower() == "n":
|
||||
# When no negatives make sure the subtracted value is lower than the initial value
|
||||
a = random.randint(int(boundMin), int(boundMax))
|
||||
b = random.randint(int(boundMin), int(a))
|
||||
else: # for debugging
|
||||
print("Negative answer input invalid, or bug. Returned error code: 2")
|
||||
|
||||
# Get current time in millis
|
||||
cTime = millis()
|
||||
|
||||
while True:
|
||||
# Try. Prints error instead of crashing if printing error occurs. Most likely deprecated
|
||||
try:
|
||||
# Get user input. For checking math
|
||||
t = input("Sum (" + str(a) + " - " + str(b) + "): ")
|
||||
# End if stop
|
||||
if t == "stop":
|
||||
return resTime(fTime, count, total, fails + 1)
|
||||
elif isnumber(t):
|
||||
# Check that input is same as sum, if so break while True
|
||||
if int(t) == int(a) - int(b):
|
||||
break
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
except:
|
||||
print("Invalid input. Error code 1")
|
||||
fails += 1
|
||||
|
||||
# Calculate formatted float time (time difference). ref 1
|
||||
fTime = round(((millis() - cTime) / 1000), 3)
|
||||
|
||||
# Update total response times. Count number of times loop has run. For calculating AURT
|
||||
total += fTime
|
||||
count += 1
|
||||
|
||||
# Print answer "Correct" and response time. The function will only get here given a correct answer, otherwise
|
||||
print("Correct! " + resTime(fTime, count, total)) # it will loop forever (while True) or stop
|
||||
|
||||
|
||||
'''MODE[Multiply]'''
|
||||
def modeMultiply():
|
||||
# Initialize mode variables
|
||||
numBases = 0
|
||||
while numBases <= 0:
|
||||
try:
|
||||
# Get number of bases(times tables) desired
|
||||
numBases = int(input("Number of tables "
|
||||
"(ex: Doing the 6 and 8 tables together would require 2. default 1):"))
|
||||
break
|
||||
except:
|
||||
# If invalid input (non-int) default to one base
|
||||
numBases = 1
|
||||
|
||||
# Initialize list of bases
|
||||
bases = []
|
||||
# Fill list with [numBases] of actual base values via user input
|
||||
for i in range(numBases):
|
||||
while True:
|
||||
try:
|
||||
bases.append(int(input("Base[" + str(i + 1) + "]: ")))
|
||||
break
|
||||
except:
|
||||
print("Invalid input. Must be integer. Returned error code: 3")
|
||||
|
||||
boundMax = 0
|
||||
while True:
|
||||
try:
|
||||
# Get number of bases desired
|
||||
boundMax = int(input("Maximum multiplier: "))
|
||||
break
|
||||
except:
|
||||
print("Invalid input")
|
||||
|
||||
count = 0
|
||||
total = 0
|
||||
fTime = 0
|
||||
fails = 0
|
||||
|
||||
# Main function
|
||||
while True:
|
||||
# Generate Random numbers
|
||||
a = random.choice(bases)
|
||||
b = random.randint(0, int(boundMax))
|
||||
|
||||
# Get current time in millis
|
||||
cTime = millis()
|
||||
|
||||
while True:
|
||||
# Try. Prints error instead of crashing if printing error occurs. Most likely deprecated
|
||||
try:
|
||||
# Get user input. For checking math
|
||||
t = input("Product (" + str(a) + " x " + str(b) + "): ")
|
||||
# End if stop
|
||||
if t == "stop":
|
||||
return resTime(fTime, count, total, fails + 1)
|
||||
elif isnumber(t):
|
||||
# Check that input is same as sum, if so break while True
|
||||
if int(t) == int(a) * int(b):
|
||||
break
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
else:
|
||||
print("Incorrect!")
|
||||
fails += 1
|
||||
except:
|
||||
print("Invalid input. Error code 1")
|
||||
fails += 1
|
||||
|
||||
# Calculate formatted float time (time difference). ref 1
|
||||
fTime = round(((millis() - cTime) / 1000), 3)
|
||||
|
||||
# Update total response times. Count number of times loop has run. For calculating AURT
|
||||
total += fTime
|
||||
count += 1
|
||||
|
||||
# Print answer "Correct" and response time. The function will only get here given a correct answer, otherwise
|
||||
print("Correct! " + resTime(fTime, count, total)) # it will loop forever (while True) or stop
|
||||
|
||||
|
||||
"""
|
||||
THE FOLLOWING CODE IS TWO TIME CALCULATION FUNCTIONS BORROWED FROM Gabriel Staples
|
||||
PLEASE SEE IMPORTANT INFO IN DOCSTRING
|
||||
"""
|
||||
|
||||
"""
|
||||
START OF BORROWED CODE
|
||||
"""
|
||||
|
||||
#-------------------------------------------------------------------
|
||||
#MODULE FUNCTIONS:
|
||||
#-------------------------------------------------------------------
|
||||
#OS-specific low-level timing functions:
|
||||
if (os.name=='nt'): #for Windows:
|
||||
|
||||
def millis():
|
||||
"return a timestamp in milliseconds (ms)"
|
||||
tics = ctypes.c_int64() #use *signed* 64-bit variables; see the "QuadPart" variable here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa383713(v=vs.85).aspx
|
||||
freq = ctypes.c_int64()
|
||||
|
||||
#get ticks on the internal ~2MHz QPC clock
|
||||
ctypes.windll.Kernel32.QueryPerformanceCounter(ctypes.byref(tics))
|
||||
#get the actual freq. of the internal ~2MHz QPC clock
|
||||
ctypes.windll.Kernel32.QueryPerformanceFrequency(ctypes.byref(freq))
|
||||
|
||||
t_ms = tics.value*1e3/freq.value
|
||||
return t_ms
|
||||
|
||||
elif (os.name=='posix'): #for Linux:
|
||||
|
||||
#Constants:
|
||||
CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h> here: https://github.com/torvalds/linux/blob/master/include/uapi/linux/time.h
|
||||
|
||||
#prepare ctype timespec structure of {long, long}
|
||||
#-NB: use c_long (generally signed 32-bit) variables within the timespec C struct, per the definition here: https://github.com/torvalds/linux/blob/master/include/uapi/linux/time.h
|
||||
class timespec(ctypes.Structure):
|
||||
_fields_ = \
|
||||
[
|
||||
('tv_sec', ctypes.c_long),
|
||||
('tv_nsec', ctypes.c_long)
|
||||
]
|
||||
|
||||
#Configure Python access to the clock_gettime C library, via ctypes:
|
||||
#Documentation:
|
||||
#-ctypes.CDLL: https://docs.python.org/3.2/library/ctypes.html
|
||||
#-librt.so.1 with clock_gettime: https://docs.oracle.com/cd/E36784_01/html/E36873/librt-3lib.html #-
|
||||
#-Linux clock_gettime(): http://linux.die.net/man/3/clock_gettime
|
||||
librt = ctypes.CDLL('librt.so.1', use_errno=True)
|
||||
clock_gettime = librt.clock_gettime
|
||||
#specify input arguments and types to the C clock_gettime() function
|
||||
# (int clock_ID, timespec* t)
|
||||
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
|
||||
|
||||
def monotonic_time():
|
||||
"return a timestamp in seconds (sec)"
|
||||
t = timespec()
|
||||
#(Note that clock_gettime() returns 0 for success, or -1 for failure, in
|
||||
# which case errno is set appropriately)
|
||||
#-see here: http://linux.die.net/man/3/clock_gettime
|
||||
if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
|
||||
#if clock_gettime() returns an error
|
||||
errno_ = ctypes.get_errno()
|
||||
raise OSError(errno_, os.strerror(errno_))
|
||||
return t.tv_sec + t.tv_nsec*1e-9 #sec
|
||||
|
||||
def millis():
|
||||
"return a timestamp in milliseconds (ms)"
|
||||
return monotonic_time()*1e3 #ms
|
||||
|
||||
"""
|
||||
END OF BORROWED CODE
|
||||
"""
|
||||
|
||||
#
|
||||
#
|
||||
#
|
||||
'''
|
||||
PROGRAM START
|
||||
'''
|
||||
#
|
||||
#
|
||||
#
|
||||
|
||||
# User input to determine mode
|
||||
flag = input('Select mode: Type[1], Add[2], Subtract[3] or Multiply[4], or "help" for help ')
|
||||
|
||||
if flag == "1":
|
||||
print(modeType())
|
||||
elif flag == "2":
|
||||
print(modeAdd())
|
||||
elif flag == "3":
|
||||
print(modeSubtract())
|
||||
elif flag == "4":
|
||||
print(modeMultiply())
|
||||
elif flag.lower() == "help":
|
||||
print(__doc__)
|
||||
else:
|
||||
print("Invalid mode input")
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
num_ore = 25
|
||||
mb_per_ore = 129
|
||||
mb_per_ingot = 144
|
||||
mb_per_coal = 144
|
||||
|
||||
mb = num_ore * mb_per_ore
|
||||
|
||||
num_ingots = int(mb / mb_per_ingot)
|
||||
num_coal = int(mb / mb_per_coal)
|
||||
lost_mb = mb % mb_per_ingot
|
||||
|
||||
print(f"With {num_ore} ore and {num_coal} coal, you will get {num_ingots} ingots and lose {lost_mb} MB of iron. Total items are {num_ore + num_coal}.")
|
||||
@@ -1 +0,0 @@
|
||||
This project is for setting up a macro program to automate forging in terrafirmacraft.
|
||||
0
tfc-forge-macro/uv.lock → uv.lock
generated
0
tfc-forge-macro/uv.lock → uv.lock
generated
Reference in New Issue
Block a user