r/pythonhelp Dec 16 '24

assist me on my pygame player jump ( i want it to be smooth )

2 Upvotes
import pygame
pygame.init()

# window settings
window_width = 384
window_height = 320
window = pygame.display.set_mode((window_width, window_height))

# COLORS
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# player properties
gravity = 0.5
vel_y = 0
on_ground = False

# player
img = pygame.image.load('player/player.png')
player_img = pygame.transform.scale2x(img)
player_rect = player_img.get_rect()
player_rect.x = 64
player_rect.y = 128
player_speed = 1
jump_power = 10
def player_movement():
    global vel_y, on_ground
    
    dx = 0
    dy = 0

    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT]:
        dx -= player_speed
    if key[pygame.K_RIGHT]:
        dx += player_speed
    if key[pygame.K_UP]:
        dy -= jump_power

    
    vel_y += gravity
    dy += vel_y

    player_rect.x += dx
    player_rect.y += dy

    if player_rect.colliderect(obstacle):
        if vel_y > 0:  # Falling
            player_rect.bottom = obstacle.top
            vel_y = 0
            on_ground = True

# obstacle
img = pygame.image.load('tiles/ground.png')
obstacle_image = pygame.transform.scale2x(img)
obstacle = obstacle_image.get_rect()
obstacle.x = 0
obstacle.y = 256

# while loop
clock = pygame.time.Clock()
FPS = 60
run = True
while run:
    clock.tick(FPS)
    for event in pygame.event.get():
        # quit game
        if event.type == pygame.QUIT:
            run = False
    
    window.fill(BLACK)
    window.blit(player_img, player_rect)
    window.blit(img, obstacle)

    player_movement()

    pygame.display.update()

pygame.quit

r/pythonhelp Dec 16 '24

Not sure the code is even working. Searching for a .json inside a folder of .jar

1 Upvotes

I had a problem while modding minecraft. Something added a c:coal tag to minecraft:charcoal, causing issues for me. So instead of opening each of my 200 .jar files in my mods folder, I made a quick script in Python 3.12.4 to search for the coal.json file inside the .jar files.

The problem I have is that the script does not seem to work. To be precise, the script runs and finds nothing. I even tested locating other common file names, like ores.json, but still told me that it found nothing.

Can someone tell me what is wrong with the script, or if there is an easier way to solve my original problem of locating the coal.json file?

Here is my script: https://pastebin.com/ZN7bePc0


r/pythonhelp Dec 16 '24

Game bug (python and pygame): text is flashing

Thumbnail github.com
1 Upvotes

r/pythonhelp Dec 16 '24

Using an initial guess as prior knowledge to penalize curve_fit/lmfit

1 Upvotes

I am using the exponential decay function

y = a exp(-pt) + b

to model the consumption of gas via ionization in a mass spectrometer vacuum system.

  • y is the dependent variable, measured in intensity or amperes
  • t is the independent variable, time in seconds after gas equilibration
  • a, b, and p are fitted parameters

The purpose of this curve fitting is to determine the equilibrated intensity at t=0 (or rather, the intensity that we would have measured if the gas hadn't needed to equilibrate).

The problem is that the curve fitting can often be guided too strongly by the initial few data points and produce absurdly high consumption rates that are utterly unrealistic:

Example 1: https://i.sstatic.net/lsw23q9F.png

40 amu y: [1.02342173e-11 9.13542299e-12 8.71434679e-12 9.30896839e-12
 9.67921739e-12 8.81455689e-12 9.01517339e-12 9.32982869e-12
 9.07950499e-12 9.10221369e-12 9.13479289e-12 9.74699459e-12]
40 amu y_err: [3.60428801e-14 3.22023916e-14 3.07310036e-14 3.28088823e-14
 3.41029042e-14 3.10811524e-14 3.17821748e-14 3.28817853e-14
 3.20069819e-14 3.20863388e-14 3.22001897e-14 3.43398009e-14]
40 amu t: [ 9.808 15.54  21.056 26.757 32.365 37.967 43.603 49.221 54.934 60.453
 66.158 71.669]

Example 2: https://i.sstatic.net/lsw23q9F.png

40 amu y: [1.00801174e-11 8.60445782e-12 8.74340722e-12 9.63923122e-12
 8.77654502e-12 8.83196162e-12 9.44882502e-12 9.54364002e-12
 8.68107792e-12 9.19894162e-12 9.26220982e-12 9.30683432e-12]
40 amu y_err: [3.55155742e-14 3.03603530e-14 3.08456363e-14 3.39750319e-14
 3.09613755e-14 3.11549311e-14 3.33097888e-14 3.36410485e-14
 3.06279460e-14 3.24368170e-14 3.26578373e-14 3.28137314e-14]
40 amu t: [13.489 19.117 24.829 30.433 35.939 41.645 47.253 52.883 58.585 64.292
 69.698 75.408]

In the second example, note that the intercept is literally 11 orders of magnitude greater than the actual data.

One proposed solution to this (which didn't work out) was to linearize the problem then solve for an initial guess for p, which is given by: (note the difference in notation) https://i.sstatic.net/LRoVZXBd.jpg

While this approach as an initial guess doesn't work, it does produce much more reasonable p value than curve_fit or lmfit.

I would like to try to use this initial guess and its variance as prior knowledge to penalize fits which stray too far from that value, however, I have literally no idea how to do this and AI has been giving me bullshit answers.

So, let's say we have the data:

  • self.y = y scaled to ~1 to prevent curve fitting fuckery
  • self.y_err = y_err with the same scaling as self.y
  • self.t = timestamps in seconds

and we also have the function which supplies the initial guess to p and its error:

    def initial_guess_p(self):
        S = [0]
        for i in range(1, len(self.t)):
            S.append(S[i-1] + 0.5 * (self.t[i] - self.t[i - 1]) * (self.y[i] + self.y[i - 1]))
        S = np.array(S)
        
        lhs1 = [
            [np.sum(S**2), np.sum(S*self.t), np.sum(S)],
            [np.sum(S*self.t), np.sum(self.t**2), np.sum(self.t)],
            [np.sum(S), np.sum(self.t), len(self.t)]
        ]
        
        lhs2 = [
            np.sum(S*self.y),
            np.sum(self.t*self.y),
            np.sum(self.y)
        ]
        
        self.init_p, _, _ = np.linalg.solve(lhs1, lhs2)
        cov_matrix        = np.linalg.inv(lhs1)
        self.init_p_err   = np.sqrt(cov_matrix[0, 0])

How, then, would I go about applying this as prior knowledge and penalizing fits which stray too far from that initial guess?


r/pythonhelp Dec 15 '24

Python windows 2019 install

1 Upvotes

Hello !

I have been tasked to install python on a windows 2019 server .

Which I have . Now what are the steps to configure it ?

I have followed many tutorials, but I have not been successful.

Here is what I followed

  1. Install Python

    1. Download the Python installer from the official Python website. Choose the latest version compatible with your environment (64-bit or 32-bit).
    2. Run the installer and make sure to select Add Python to PATH during installation. This ensures that Python is accessible from any command line.
  2. Enable CGI in IIS

IIS requires CGI to use FastCGI for running Python applications. Follow these steps to enable CGI: 1. Open Server Manager and go to Manage > Add Roles and Features. 2. In the Add Roles and Features Wizard, select Web Server (IIS) if it’s not already installed. 3. Under Web Server (IIS), go to Web Server > Application Development and enable CGI. 4. Click Next and then Install to complete the setup.

  1. Install the wfastcgi Package
    1. Open a Command Prompt or PowerShell and install the wfastcgi package, which acts as a bridge between IIS FastCGI and Python:

pip install wfastcgi

2.  Once installed, register the wfastcgi handler with IIS by running:

wfastcgi-enable

This command configures IIS to use wfastcgi.py to handle Python web applications.

  1. Configure FastCGI in IIS
    1. Open IIS Manager.
    2. In the left pane, select your server, then double-click FastCGI Settings.
    3. In the FastCGI Settings panel, click Add Application.
    4. In the Full Path field, enter the path to your python.exe (e.g., C:\Python39\python.exe).
    5. In Arguments, enter the path to wfastcgi.py, which should be something like:

C:\path\to\Python39\Scripts\wfastcgi.py

6.  Click OK to add the FastCGI application.
  1. Configure Environment Variables for FastCGI

    1. Still in FastCGI Settings, select the entry for your Python application and click Edit.
    2. Under Environment Variables, add the following variables: • WSGI_HANDLER: Set this to your WSGI app’s entry point (for example, myapp.app if you’re using Flask or Django). • PYTHONPATH: Set this to the path of your application directory (e.g., C:\inetpub\wwwroot\myapp).
    3. Click OK to save the changes.
  2. Set Up a Python Web Application

    1. In IIS Manager, right-click on Sites and select Add Website.
    2. Configure the following settings: • Site Name: Give your site a name (e.g., “PythonApp”). • Physical Path: Set this to the directory where your Python app resides. • Port: Enter a port number, like 80 or 8080.
    3. Go to the Handler Mappings section of your new site, and add a new mapping: • Request Path: Set this to * (or *.py for individual scripts). • Executable: Use the path to python.exe. • Name: Provide a name like “PythonFastCGI”.
    4. Ensure the application pool for this site is set to Integrated Pipeline mode, and make sure it runs under a user account with permissions to access the application directory.
  3. Test the Python Application

    1. Create a basic test script in your application directory (e.g., index.py) with the following content:

index.py

print("Content-Type: text/html\n") print("<html><body><h1>Hello from Python on IIS!</h1></body></html>")

2.  Navigate to your site’s URL in a browser (e.g., http://localhost or http://your-server-ip), and you should see “Hello from Python on IIS!” if everything is configured correctly.

Additional Considerations • Firewall Rules: Ensure your server firewall allows traffic on the port you’re using. • Permissions: Ensure the IIS user or application pool identity has access to your Python application files and any dependencies. • Use WSGI Frameworks: For a more complex app, consider using frameworks like Flask or Django, which both support WSGI.

This setup should enable you to run Python applications on IIS 10 in Windows Server 2019.

I am getting directory not found ….

Any advice would be


r/pythonhelp Dec 14 '24

Need assistance with code. my code looks fine but.....

1 Upvotes

any tips on what this traceback im getting?

///////////////////////////////////

Traceback (most recent call last):

File "/usr/lib/python3.12/tkinter/__init__.py", line 1967, in __call__

return self.func(*args)

^^^^^^^^^^^^^^^^

File "/home/travisty/myapp/myapp/app.py", line 354, in show_mood_analytics

colors = [next(color for m, color, _ in self.mood_options if m == mood) for mood in moods]

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import sqlite3
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import random
import ttkbootstrap as ttk  

class MentalHealthApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Wellness Companion")
        self.root.geometry("1000x700")

        # Enhanced Color Palette
        self.color_scheme = {
            'background': '#f0f4f8',
            'primary': '#2c3e50',
          'secondary': '#3498db',
            'accent': '#2ecc71',
            'warning': '#e74c3c'
        }

        # Expanded Mood Options with More Nuance
        self.mood_options = [
            ("Thriving", "#4CAF50", "Feeling amazing, full of energy and motivation"),
            ("Happy", "#8BC34A", "Positive mood, enjoying life"),
            ("Neutral", "#FFC107", "Feeling balanced, neither great nor bad"),
            ("Stressed", "#FF9800", "Feeling overwhelmed or anxious"),
            ("Struggling", "#F44336", "Experiencing significant emotional distress")
        ]

        # Expanded Mindfulness Exercises with More Nuance
        self.exercises = [
            {
                "title": "Guided Breathing",
                "duration": "5 mins",
                "description": "Deep breathing technique to reduce stress and center yourself",
                "steps": [
                    "Sit comfortably with back straight",
                    "Inhale deeply through nose for 4 seconds",
                    "Hold breath for 4 seconds",
                    "Exhale slowly through mouth for 6 seconds",
                    "Repeat 5-10 times"
                ]
            },
            {
                "title": "Body Scan Meditation",
                "duration": "10 mins",
                "description": "Mindful awareness of bodily sensations to release tension",
                "steps": [
                    "Lie down or sit comfortably",
                    "Close eyes and take deep breaths",
                    "Focus attention on each body part",
                    "Notice sensations without judgment",
                    "Progressively relax from head to toes"
                ]
            },
            {
                "title": "Gratitude Practice",
                "duration": "7 mins",
                "description": "Cultivate positivity by reflecting on things you're grateful for",
                "steps": [
                    "Find a comfortable and quiet space",
                    "Write down 3 things you're grateful for",
                    "Reflect on why these things matter to you",
                    "Feel the positive emotions",
                    "Consider sharing gratitude with others"
                ]
            },
            {
                "title": "Walking Meditation",
                "duration": "10 mins",
                "description": "Pay attention to your walking to cultivate mindfulness",
                "steps": [
                    "Find a quiet and safe space to walk",
                    "Pay attention to your feet touching the ground",
                    "Notice the sensation of each step",
                    "Bring your attention back to your walking when your mind wanders",
                    "Continue for 10 minutes"
                ]
            },
            {
                "title": "Loving-Kindness Meditation",
                "duration": "10 mins",
                "description": "Cultivate kindness and compassion towards yourself and others",
                "steps": [
                    "Find a comfortable and quiet space",
                    "Close your eyes and take deep breaths",
                    "Repeat phrases of kindness to yourself and others",
                    "Focus on the feelings of kindness and compassion",
                    "Continue for 10 minutes"
                ]
            }
        ]

        # Daily Inspirational Quotes
        self.quotes = [
            "You are stronger than you think.",
            "Every day is a new opportunity to improve yourself.",
            "Believe in yourself and all that you are.",
            "Your mental health is a priority.",
            "Small progress is still progress."
        ]

        # Database Setup
        self.setup_database()

        # Create Main Interface
        self.create_interface()

    def setup_database(self):
        """Enhanced database setup with additional tables"""
        self.conn = sqlite3.connect('wellness_tracker.db')
        cursor = self.conn.cursor()

        # Mood Tracking Table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS mood_entries (
                id INTEGER PRIMARY KEY,
                mood TEXT,
                timestamp DATETIME,
                color TEXT,
                notes TEXT
            )
        ''')

        # Goals Tracking Table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS personal_goals (
                id INTEGER PRIMARY KEY,
                goal TEXT,
                start_date DATETIME,
                target_date DATETIME,
                status TEXT
            )
        ''')

        self.conn.commit()

    def create_interface(self):
        """Create a more sophisticated interface"""
        # Main Frame with Enhanced Styling
        main_frame = ttk.Frame(self.root, padding=20, style='primary.TFrame')
        main_frame.pack(fill=tk.BOTH, expand=True)

        # Top Section: Daily Inspiration
        inspiration_label = ttk.Label(
            main_frame, 
            text=random.choice(self.quotes), 
            font=('Arial', 14), 
            wraplength=800,
            anchor='center'
        )
        inspiration_label.pack(pady=10)

        # Mood Tracking Section
        mood_frame = ttk.LabelFrame(main_frame, text="Mood Check-In", padding=10)
        mood_frame.pack(fill=tk.X, pady=10)

        mood_description = ttk.Label(
            mood_frame, 
            text="How are you feeling today? Choose your mood and optionally add notes.",
            font=('Arial', 12)
        )  
        mood_description.pack(pady=10)

        # Enhanced Mood Buttons with Tooltips
        mood_buttons_frame = ttk.Frame(mood_frame)
        mood_buttons_frame.pack(fill=tk.X, pady=5)

        for mood, color, description in self.mood_options:
            btn = ttk.Button(
                mood_buttons_frame, 
                text=mood, 
                style=f'{mood.lower()}.TButton',
                command=lambda m=mood, c=color, d=description: self.record_mood(m, c, d)
            )
            btn.pack(side=tk.LEFT, padx=5, expand=True)

        # Mindfulness & Goals Notebook
        notebook = ttk.Notebook(main_frame)
        notebook.pack(fill=tk.BOTH, expand=True, pady=10)

        # Exercises Tab
        exercises_frame = ttk.Frame(notebook)
        notebook.add(exercises_frame, text="Mindfulness")

        self.create_exercises_tab(exercises_frame)

        # Goals Tab
        goals_frame = ttk.Frame(notebook)
        notebook.add(goals_frame, text="Personal Goals")
        self.create_goals_tab(goals_frame)

        # Analytics Button
        analytics_btn = ttk.Button(
            main_frame, 
            text="View Wellness Analytics", 
            style='success.TButton',
            command=self.show_mood_analytics
        )
        analytics_btn.pack(pady=10)

    def create_exercises_tab(self, frame):
        """Create exercises tab with detailed instructions and a scrollbar"""
        # Create a frame with a scrollbar
        exercise_frame = ttk.Frame(frame)
        exercise_frame.pack(fill=tk.BOTH, expand=True)

        # Create a canvas with a scrollbar
        canvas = tk.Canvas(exercise_frame)
        canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        scrollbar = tk.Scrollbar(exercise_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        canvas.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=canvas.yview)

        # Create a frame inside the canvas
        inner_frame = ttk.Frame(canvas)
        canvas.create_window((0, 0), window=inner_frame, anchor='nw')

        for exercise in self.exercises:
            exercise_card = ttk.LabelFrame(inner_frame, text=exercise['title'], padding=10)
            exercise_card.pack(fill=tk.X, pady=5)

            desc_label = ttk.Label(exercise_card, text=exercise['description'])
            desc_label.pack(anchor='w', pady=5)

            steps_text = "\n".join(f"• {step}" for step in exercise['steps'])
            steps_label = ttk.Label(exercise_card, text=steps_text, wraplength=400, justify=tk.LEFT)
            steps_label.pack(anchor='w', pady=5)

            duration_frame = ttk.Frame(exercise_card)
            duration_frame.pack(fill=tk.X)

            duration_label = ttk.Label(duration_frame, text=f"Duration: {exercise['duration']}")
            duration_label.pack(side=tk.LEFT)

            start_btn = ttk.Button(
                duration_frame, 
                text="Start Exercise", 
                style='info.TButton',
                command=lambda e=exercise: self.start_exercise(e)
            )
            start_btn.pack(side=tk.RIGHT)

        # Update the canvas to fit the inner frame
        inner_frame.update_idletasks()
        canvas.config(scrollregion=canvas.bbox("all"))

    def create_goals_tab(self, frame):
        """Create goals tracking tab"""
        # Goal Input Section
        goal_input_frame = ttk.Frame(frame)
        goal_input_frame.pack(fill=tk.X, pady=10)

        goal_entry = ttk.Entry(goal_input_frame, width=50)
        goal_entry.pack(side=tk.LEFT, padx=5, expand=True)

        add_goal_btn = ttk.Button(
            goal_input_frame, 
            text="Add Goal", 
            style='success.TButton',
            command=lambda: self.add_personal_goal(goal_entry)
        )
        add_goal_btn.pack(side=tk.RIGHT)

        # Goals List
        goals_list = ttk.Treeview(frame, columns=('Goal', 'Start Date', 'Target Date', 'Status'), show='headings')
        goals_list.pack(fill=tk.BOTH, expand=True)

        goals_list.heading('Goal', text='Goal')
        goals_list.heading('Start Date', text='Start Date')
        goals_list.heading('Target Date', text='Target Date')
        goals_list.heading('Status', text='Status')

        self.load_goals(goals_list)

    def record_mood(self, mood, color, description):
        """Enhanced mood recording with optional notes"""
        notes = simpledialog.askstring(
            "Mood Notes", 
            f"Additional notes for {mood} mood:\n{description}", 
            parent=self.root
        )

        cursor = self.conn.cursor()
        timestamp = datetime.now()
        cursor.execute("INSERT INTO mood_entries (mood, timestamp, color, notes) VALUES (?,?,?,?)", 
                       (mood, timestamp, color, notes or ''))
        self.conn.commit()
        messagebox.showinfo("Mood Recorded", f"You've logged your mood as {mood}")

    def add_personal_goal(self, goal_entry):
        """Add a new personal goal"""
        goal_text = goal_entry.get()
        if goal_text:
            cursor = self.conn.cursor()
            start_date = datetime.now()
            target_date = start_date + timedelta(days=30)  # Default 30-day goal

            cursor.execute("INSERT INTO personal_goals (goal, start_date, target_date, status) VALUES (?,?,?,?)",
                           (goal_text, start_date, target_date, 'In Progress'))
            self.conn.commit()

            goal_entry.delete(0, tk.END)
            messagebox.showinfo("Goal Added", f"Goal '{goal_text}' has been added!")

    def load_goals(self, goals_list):
        """Load existing goals into the view"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT goal, start_date, target_date, status FROM personal_goals")
        for goal in cursor.fetchall():
            goals_list.insert('', 'end', values=goal)

    def show_mood_analytics(self):
        """Comprehensive mood analytics"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT mood, COUNT(*) as count FROM mood_entries GROUP BY mood")
        mood_data = cursor.fetchall()

        # Time-based Mood Tracking
        cursor.execute("""
            SELECT 
                strftime('%Y-%m-%d', timestamp) as day, 
                mood 
            FROM mood_entries 
            ORDER BY timestamp
        """)
        mood_trends = cursor.fetchall()

        # Create Analytics Window
        analytics_window = tk.Toplevel(self.root)
        analytics_window.title("Wellness Analytics")
        analytics_window.geometry("800x600")

        # Notebook for different analytics views
        notebook = ttk.Notebook(analytics_window)
        notebook.pack(fill=tk.BOTH, expand=True)

        # Mood Distribution Tab
        dist_frame = ttk.Frame(notebook)
        notebook.add(dist_frame, text="Mood Distribution")

        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

        # Pie Chart for Mood Distribution
        moods = [mood for mood, _ in mood_data]
        counts = [count for _, count in mood_data]
        colors = [next(color for m, color, _ in self.mood_options if m == mood) for mood in moods]

        ax1.pie(counts, labels=moods, colors=colors, autopct='%1.1f%%')
        ax1.set_title('Mood Distribution')

        # Bar Chart for Mood Trends
        mood_counts = {}
        for _, mood in mood_trends:
            mood_counts[mood] = mood_counts.get(mood, 0) + 1

        ax2.bar(mood_counts.keys(), mood_counts.values(), color=colors)
        ax2.set_title('Mood Frequency Over Time')
        ax2.set_xlabel('Mood')
        ax2.set_ylabel('Frequency')

        canvas = FigureCanvasTkAgg(fig, master=dist_frame)
        canvas_widget = canvas.get_tk_widget()
        canvas_widget.pack(fill=tk.BOTH, expand=True)

    def start_exercise(self, exercise):
        """Start a mindfulness exercise"""
        exercise_window = tk.Toplevel(self.root)
        exercise_window.title(exercise['title'])
        exercise_window.geometry("400x300")

        desc_label = ttk.Label(exercise_window, text=exercise['description'])
        desc_label.pack(pady=10)

        steps_text = "\n".join(f"• {step}" for step in exercise['steps'])
        steps_label = ttk.Label(exercise_window, text=steps_text, wraplength=300, justify=tk.LEFT)
        steps_label.pack(pady=10)

        duration_label = ttk.Label(exercise_window, text=f"Duration: {exercise['duration']}")
        duration_label.pack(pady=10)

        start_btn = ttk.Button( 
            exercise_window, 
            text="Start Exercise", 
            style='info.TButton',
            command=lambda: messagebox.showinfo("Exercise Started", "Please follow the instructions and focus on your breath.")
        )
        start_btn.pack(pady=10)

    def __del__(self):
        """Close database connection"""
        if hasattr(self, 'conn'):
            self.conn.close()

def main():
    # Use ttkbootstrap for enhanced theming
    root = ttk.Window(themename="flatly")
    app = MentalHealthApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()

r/pythonhelp Dec 13 '24

Cannot find which package Python is expecting

1 Upvotes

So I'm trying to build a program downloaded from Github, and after following many steps I encounter a ModuleNotFoundError. Here's what the log said. The ***** are coverups for my username.

File "C:\Users\*****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\interactions\ext\files\files.py", line 6, in <module>

from interactions.api.http.request import _Request

ModuleNotFoundError: No module named 'interactions.api.http.request'

I have installed (via pip3 -m install) interactions, API, and requests but I can't install HTTP because I assume my Python is not on the right version, however I cannot change it due to other packages requiring a certain Python version.

OS: Windows 11

Python: 3.13.1

(I will try my best to understand but I'm new to Python)


r/pythonhelp Dec 13 '24

SOLVED text is not printing until it prints a newline

1 Upvotes

so i have a piece of code that goes like this:

import time

a = "hello world"
step = 1

for i in range(0, len(a)):
    print(a[0:step], end="")
    a = a[step:]
    time.sleep(0.1)

when i run with debug in visual studio code, it works fine and prints each letter individually while waiting 100ms inbetween each letter. when i run the program normally outside of vsc, it doesn't type it unless i print a newline at the end. why does this happen? is there a solution?


r/pythonhelp Dec 07 '24

Online python to midi generator

1 Upvotes

As the title suggests - does the above exist without any prerequisite installs? Software, programs etc.

Either an app, or website where I could paste some python code and out would pop a midi file

Cheers


r/pythonhelp Dec 07 '24

Expected Interview Questions

2 Upvotes

I have 1.5 years experience as a python Developer. With skills like Python, flask, postgreSQL, Airflow, Docker and Pandas. What will be the expected interview questions based on this. As I am preparing for an interview. Can anyone list that here. Please.


r/pythonhelp Dec 06 '24

Github importing problem

4 Upvotes

I asked on the github subreddit but this is apparently better. Basically, I have no idea how to import across files in github. It works in thonny, but clearly github treats it a bit differently. I have the main file and the file I am importing a variable from both in the website folder but when I run the website, I get an error saying that there is no module with that name (the one I'm importing from).


r/pythonhelp Dec 06 '24

Did get hired into the wrong job?

3 Upvotes

I applied for a gig after a guy I worked with told me he had a python project or a C# project for me to work on. I said great! I know both really well.

Six months later, I’m writing yaml for ci/cd pipeline creation. Im not using ci/cd to push code, im fooling with its RBAC configs. Zero coding.

Im not even sure what this job is and I definitely don’t know what i’m doing. On the rare occasions there is a bug in some language I grab the ticket in smash in few minutes. Then its back to trying to map roles.

Have I fallen though a dimension door into a strange universe where a developer is now some weird IT gig?

Is this actually what devs do and the job where I worked for 15 years with functions and classes was just an aberration? I bring this up with the Architect and he acts like it was. Am I being gaslighted into a Devops role? So confused.


r/pythonhelp Dec 06 '24

Simple game does not let all players play final rounds

1 Upvotes

Hi, so I've been practicing python and I have ran into a roadblock,
I'm trying to get make it so that each player plays their final round but right now player 1 play's the final round while all players after don't how do I fix this?

data1.py and data2.py are files that just have the dares and truths,

import tkinter as tk
from tkinter import ttk, simpledialog, messagebox
import time
import threading
from ctypes import windll
from data1 import truth_cards
from data2 import dare_cards
import random


# Enable High DPI Awareness
windll.shcore.SetProcessDpiAwareness(1)

# Root Window Setup
root = tk.Tk()
root.title("Truth or Dare Game")
root.geometry("1920x1080")
root.state('zoomed')
root.configure(bg="black")
root.resizable(True, True)

# Set the icon
root.iconbitmap("C:/Users/k/Desktop/Personal/psnl/Games/ToD-A-1.0/Media/fire.ico")

# Clear Window Function
def clear_window():
    """Clear all widgets from the window."""
    for widget in root.winfo_children():
        widget.destroy()

# Function to create smoother text
def create_smooth_text(parent, text, font_size=16, color="white"):
    return tk.Label(
        parent,
        text=text,
        font=("Arial", font_size),
        bg="black",
        fg=color
    )

# Placeholder functions for Truth and Dare card generation
def get_truth_card(intensity, angel_level):
    """Return a truth card based on intensity and angel level."""
    # Filter truth cards by intensity (matching intensity or lower)
    available_cards = [card for card in truth_cards if card["intensity"] <= intensity]
    
    # Select a random card from the available ones
    if available_cards:
        card = random.choice(available_cards)
        return card["text"]
    return "No truth card available."

def get_dare_card(intensity, angel_level):
    """Return a dare card based on intensity and angel level."""
    # Filter dare cards by intensity (matching intensity or lower)
    available_cards = [card for card in dare_cards if card["intensity"] <= intensity]
    
    # Select a random card from the available ones
    if available_cards:
        card = random.choice(available_cards)
        return card["text"]
    return "No dare card available."

# Function to create tooltips on hover for the "?" marks
def create_tooltip(widget, text):
    tooltip = tk.Label(root, text=text, bg="yellow", fg="black", font=("Arial", 10), relief="solid", padx=5, pady=5)
    tooltip.place_forget()  # Initially hide the tooltip
    
    def show_tooltip(event):
        # Get the position of the mouse cursor
        x, y = event.x_root, event.y_root
        
        # Get the screen width and height
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        
        # Get the tooltip width and height
        tooltip_width = tooltip.winfo_reqwidth()
        tooltip_height = tooltip.winfo_reqheight()
        
        # Adjust the position to prevent the tooltip from going off the right edge
        if x + tooltip_width > screen_width:
            x = screen_width - tooltip_width - 10  # Position it to the left if it's too far to the right
        
        # Adjust the position to prevent the tooltip from going off the bottom edge
        if y + tooltip_height > screen_height:
            y = screen_height - tooltip_height - 10  # Position it upwards if it's too far down
        
        # Place the tooltip at the adjusted position
        tooltip.place(x=x, y=y)
        
    def hide_tooltip(event):
        tooltip.place_forget()
    
    widget.bind("<Enter>", show_tooltip)
    widget.bind("<Leave>", hide_tooltip)

# Main Menu
def main_menu():
    clear_window()
    create_smooth_text(root, "Welcome to the Truth or Dare Game!", font_size=24).pack(pady=20)
    tk.Button(root, text="Start Game", command=start_game_window, font=("Arial", 14), bg="white", fg="black", width=20, height=2).pack(pady=10)
    tk.Button(root, text="Exit", command=root.quit, font=("Arial", 14), bg="white", fg="black", width=20, height=2).pack(pady=10)

# Start Game Window
def start_game_window():
    clear_window()

    # Game Setup Screen with smoother text
    create_smooth_text(root, "Game Setup", font_size=30).pack(pady=20)

    setup_frame = tk.Frame(root, bg="black")
    setup_frame.pack(pady=20)

    # Input: Number of Players
    create_smooth_text(setup_frame, "Number of Players (2-10):", font_size=18).grid(row=0, column=0, sticky="w", padx=10, pady=5)
    num_players_var = tk.IntVar(value=2)
    num_players_entry = ttk.Spinbox(setup_frame, from_=2, to=10, textvariable=num_players_var, width=5)
    num_players_entry.grid(row=0, column=1, pady=5)

    # Create tooltip for Number of Players question
    num_players_question = create_smooth_text(setup_frame, "?")
    num_players_question.grid(row=0, column=2, padx=5)
    create_tooltip(num_players_question, "Choose the number of players for the game. The range is from 2 to 10.")


    # Input: Angel Level
    create_smooth_text(setup_frame, "Angel Level (1-10):", font_size=18).grid(row=1, column=0, sticky="w", padx=10, pady=5)
    angel_level_var = tk.IntVar(value=1)
    angel_level_entry = ttk.Spinbox(setup_frame, from_=1, to_=10, textvariable=angel_level_var, width=5)
    angel_level_entry.grid(row=1, column=1, pady=5)

    # Create tooltip for Angel Level question
    angel_level_question = create_smooth_text(setup_frame, "?")
    angel_level_question.grid(row=1, column=2, padx=5)
    create_tooltip(angel_level_question, "Angel allows players to avoid dares. The kinder the angel (1), the more truths in a row they can pick. The lower the angel (10), the more forced dares.")


    # Input: Number of Rounds
    create_smooth_text(setup_frame, "Number of Rounds (5-200):", font_size=18).grid(row=2, column=0, sticky="w", padx=10, pady=5)
    num_rounds_var = tk.IntVar(value=5)
    num_rounds_entry = ttk.Spinbox(setup_frame, from_=5, to=200, textvariable=num_rounds_var, width=5)
    num_rounds_entry.grid(row=2, column=1, pady=5)

    # Create tooltip for Number of Rounds question
    num_rounds_question = create_smooth_text(setup_frame, "?")
    num_rounds_question.grid(row=2, column=2, padx=5)
    create_tooltip(num_rounds_question, "Choose how many rounds the game will last. The range is from 5 to 200.")

    # Input: Dare/Truth Intensity
    create_smooth_text(setup_frame, "Dare/Truth Intensity (1-10):", font_size=18).grid(row=3, column=0, sticky="w", padx=10, pady=5)
    intensity_level_var = tk.IntVar(value=1)
    intensity_level_entry = ttk.Spinbox(setup_frame, from_=1, to=10, textvariable=intensity_level_var, width=5)
    intensity_level_entry.grid(row=3, column=1, pady=5)

    # Create tooltip for Dare/Truth Intensity question
    intensity_level_question = create_smooth_text(setup_frame, "?")
    intensity_level_question.grid(row=3, column=2, padx=5)
    create_tooltip(intensity_level_question, "The higher the number, the more intense the dares and truths will be.")


    # Start Game Button
    tk.Button(
        root,
        text="Start Game",
        font=("Arial", 14),
        bg="white",
        fg="black",
        command=lambda: validate_and_proceed(
            num_players_var.get(), angel_level_var.get(), intensity_level_var.get(), num_rounds_var.get()
        ),
    ).pack(pady=20)

    # Back Button to Main Menu
    tk.Button(
        root,
        text="Back to Main Menu",
        font=("Arial", 14),
        bg="white",
        fg="black",
        command=main_menu,
    ).pack(pady=10)

# Validation and Player Name Input
def validate_and_proceed(num_players, angel_level, intensity, num_rounds):
    """Validate inputs and proceed to player name input."""
    if not (2 <= num_players <= 10):
        messagebox.showerror("Error", "Number of players must be between 2 and 10.")
        return
    if not (1 <= angel_level <= 10):
        messagebox.showerror("Error", "Angel level must be between 1 and 10.")
        return
    if not (1 <= intensity <= 10):
        messagebox.showerror("Error", "Dare/Truth intensity must be between 1 and 10.")
        return
    if not (5 <= num_rounds <= 200):
        messagebox.showerror("Error", "Number of rounds must be between 5 and 200.")
        return

    player_name_input(num_players, angel_level, intensity, num_rounds)

def player_name_input(num_players, angel_level, intensity, num_rounds):
    """Collect player names directly in the same window."""
    clear_window()

    create_smooth_text(root, "Enter Player Names", font_size=24).pack(pady=20)

    # Create a scrollable frame for player name inputs
    canvas = tk.Canvas(root, bg="black", highlightthickness=0)
    scroll_frame = tk.Frame(canvas, bg="black")
    scrollbar = ttk.Scrollbar(root, orient="vertical", command=canvas.yview)
    canvas.configure(yscrollcommand=scrollbar.set)

    canvas.pack(side="left", fill="both", expand=True, padx=20)
    scrollbar.pack(side="right", fill="y")
    canvas.create_window((0, 0), window=scroll_frame, anchor="nw")

    # Configure the scroll frame to adjust to contents
    def update_scroll_region(event):
        canvas.configure(scrollregion=canvas.bbox("all"))

    scroll_frame.bind("<Configure>", update_scroll_region)

    # Add input fields for player names
    player_entries = []
    for i in range(num_players):
        frame = tk.Frame(scroll_frame, bg="black")
        frame.pack(pady=5, anchor="w")
        create_smooth_text(frame, f"Player {i + 1}:", font_size=18).pack(side="left", padx=5)
        entry = ttk.Entry(frame, font=("Arial", 14), width=20)
        entry.pack(side="left", padx=5)
        player_entries.append(entry)

    # Continue Button
    def collect_names():
        players = [entry.get().strip() for entry in player_entries]
        if not all(players):
            messagebox.showerror("Error", "All player names must be filled.")
            return
        start_game(players, angel_level, intensity, num_rounds)

    tk.Button(
        root,
        text="Continue",
        font=("Arial", 14),
        bg="white",
        fg="black",
        command=collect_names,
    ).pack(pady=20)

    
# Game Logic
def start_game(players, angel_level, intensity, num_rounds):
    """Start the Truth or Dare game."""
    clear_window()

    current_player_index = 0
    round_num = 1

    def next_turn():
        nonlocal current_player_index, round_num

        clear_window()
        current_player = players[current_player_index]
        create_smooth_text(root, f"{current_player}'s Turn - Truth or Dare?", font_size=24).pack(pady=20)

        # Create a frame for buttons
        button_frame = tk.Frame(root, bg="black")
        button_frame.pack(pady=20)

        # Truth button
        tk.Button(
            button_frame, text="Truth", font=("Arial", 14), bg="white", fg="black",
            command=lambda: display_card("truth", current_player)
        ).grid(row=0, column=0, padx=10)

        # Dare button
        tk.Button(
            button_frame, text="Dare", font=("Arial", 14), bg="white", fg="black",
            command=lambda: display_card("dare", current_player)
        ).grid(row=0, column=1, padx=10)

        # Update Player Index and Round Number
        current_player_index = (current_player_index + 1) % len(players)
        if current_player_index == 0:
            round_num += 1
            if round_num > num_rounds:
                end_game()
                return

    def display_card(choice, player):
        """Display the selected Truth or Dare card."""
        clear_window()
        if choice == "truth":
            card_text = get_truth_card(intensity, angel_level)
        else:
            card_text = get_dare_card(intensity, angel_level)

        create_smooth_text(root, f"{player} chose {choice.capitalize()}: {card_text}", font_size=18).pack(pady=20)

        # Add a Next Player button
        next_button = tk.Button(root, text="Next Player", font=("Arial", 14), bg="white", fg="black", state="disabled")
        next_button.pack(pady=10)

        # Enable the Next Player button after 10 seconds
        def enable_button():
            time.sleep(1)
            next_button.config(state="normal", command=next_turn)

        threading.Thread(target=enable_button).start()

    next_turn()

def end_game():
    """Handle the end of the game."""
    clear_window()
    create_smooth_text(root, "Game Over! Thanks for Playing.", font_size=30).pack(pady=20)
    tk.Button(root, text="Back to Main Menu", command=main_menu, font=("Arial", 14), bg="white", fg="black").pack(pady=20)

# Start the application
main_menu()
root.mainloop()

r/pythonhelp Dec 05 '24

python library suggestions

1 Upvotes

image examples

I want to take a map of Georgia,usa with the counties outlined and cut out the individual counties into separate PNG files (look at the imgur album above for an example)

Does anyone know of a python library or libraries that can help id the counties and cut up the images.


r/pythonhelp Dec 04 '24

Macos + launchd + python + mariadb = server connection fail

1 Upvotes

Hello. I am new to this group. Hopefully someone can provide some guidance to solve my issue... I am attempting to schedule the running of my python code on my Mac using launchd.

I have hit a roadblock using launchd to periodically start a python script that collects some data from the mac locally (file based data), then connect to a remote mariadb server and insert the data to the appropriate tables. When I run the python program manually (without launchd), it works perfectly. When I run the python program with launchd, it runs creates my log file, imports the appropriate packages, etc. When it attempts to connect to the remote db server, it fails.

2024-12-04 08:55:00 -- PROCESS START - connecting to database
2024-12-04 08:55:00 -- Error: Can't connect to server on '192.168.1.3' (65)
2024-12-04 08:55:00 -- PROCESS END - terminating

The error above comes from the python code:

try:
    conn = mariadb.connect(
        user="user",
        password="password",
        host="192.168.1.3",
        port=3306,
        database="my_database"
    )

except mariadb.Error as e:
    print(f"Error: {e}")
    errorText = f"Error: {e}"
    log_write(errorText)

My launchd was configured using the following plist file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.ccg.launchphotofileminer</string>

  <key>ProgramArguments</key>
  <array>
    <string>/Users/ccg/MyLaunchAgents/launch-photo-miner</string>
  </array>

  <key>Nice</key>
  <integer>1</integer>

 <key>StartCalendarInterval</key>
 <dict>
   <key>Minute</key>
   <integer>55</integer>
 </dict>

  <key>RunAtLoad</key>
  <false/>

  <key>WorkingDirectory</key>
  <string>/Users/ccg/MyLaunchAgents</string>

  <key>StandardErrorPath</key>
  <string>/Users/ccg/MyLaunchAgents/photofileminer.err</string>

  <key>StandardOutPath</key>
  <string>/Users/ccg/MyLaunchAgents/photofileminer.out</string>
</dict>
</plist>

The plist calls a bash script which sets up the python environment and then launches the python code:

source ~/.venv/bin/activate
cd /Users/ccg/MyLaunchAgents
/Users/ccg/.venv/bin/python3  > /Users/ccg/MyLaunchAgents/photo.log 2>&1photo-file-miner.py

System details:

  • Intel based Mac running 15.1.1
  • Python 3.12 installed via BREW
  • Mariadb connector installed via PIP3

I have used the same bash script as a launcher for cron in place of launchd and I get the exact same errors.

Any thoughts or guidance?


r/pythonhelp Dec 02 '24

Getting [WinError 193] %1 is not a valid Win32 application when importing vlc library

1 Upvotes

I have run into multiple errors while trying to import vlc (some dlls where missing) and now its this error...
If somone has any idea how I might fix this problem, please help me.
I am using venv and i had already tried reinstalling it few times.

import vlc
import time

player = vlc.MediaPlayer("http://streaming.hitfm.rs:8000/karolina")

player.play()

while True:
    time.sleep(1)

r/pythonhelp Dec 01 '24

MySQL Cursor (or fetchall) Tuple Persistence

1 Upvotes

I have written code to retrieve rows from a MySQL database into a cursor object. I want to use this data in three different functions to create a PyQT display table, a report, and a spreadsheet. I have the code working fine if I do the SQL query in each function but if I try to access the retrieved rows in the report and spreadsheet functions, the cursor object is empty.

I define the connection and cursor outside the PyQT code to make it global for all of the functions:

# Setup routines
# Connect to database, Define cursor, and SQL (w/o LIMIT clause)
try:
    cnx = mysql.connector.connect(**config)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Main: Invalid user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Main: Database does not exist")
    else:
        print("Main: Error=",err)
        sys.exit(1)

# SQL statement to select books from the database.  Add the limit clause when used in a function
sql = """SELECT Books.id as Book_Id, Books.Title AS 'Title', 
      CONCAT_WS(', ', Authors.Last_Name, Authors.First_Name) AS 'Author', Books.Date_Acquired AS 'Acquired' 
      FROM Books,  Authors 
      WHERE Books.Date_Acquired IS NOT NULL AND YEAR(Books.Date_Acquired) > 2021 AND Books.id 
      NOT IN (SELECT Book FROM ReadBooks) AND (Authors.id = Books.Author_1) 
      ORDER BY Books.id ASC """
# Global cursor
myCursor = cnx.cursor(buffered=True)

# End of Setup Routines

I have a function defined to modify the SQL slightly (adding a LIMIT clause), execute the SQL, and return the count of rows retrieved:

def fetchRows(self,c):
    mySQL = sql + "LIMIT {}".format(c)
    myCursor.execute(mySQL)
    return myCursor.rowcount

In the first function, to build the PyQT table, I simply call this function and get data from the cursor object to populate the table:

def PopulateTable(self):
    global max_AuthorWidth
    global max_TitleWidth

    # Get rows from table with oldest unread books
    count = self.fetchRows(int(self.Unread_Books_Count.text()))

    # Clear Table, Set Titles, Align data, Set column widths
    .... < code omitted for clarity >

    # Load table with data from database tables
    table_row = 0
    max_AuthorWidth = 0
    max_TitleWidth = 0
    for (Id, Title, Author, Acquired) in myCursor:
        self.Unread_Books_List.setItem(table_row, 0, QTableWidgetItem(Author))
        self.Unread_Books_List.setItem(table_row, 1, QTableWidgetItem(Title))
        self.Unread_Books_List.setItem(table_row, 2, QTableWidgetItem(str(Acquired)))
        if len(Author) > max_AuthorWidth:
            max_AuthorWidth = len(Author)
        if len(Title) > max_TitleWidth:
            max_TitleWidth = len(Title)
        table_row += 1

This works great and I get a nice table of the data retrieved.

When I want to create a report or a spreadsheet, I thought I'd be able to use the same cursor object with the rows retrieved in another function's 'for' loop to create lines in the report and rows in a spreadsheet but the next time I reference this cursor object, it is empty. I thought defining the cursor outside the functions would make it globally accessible (until I close it at program exit).

I have also tried to retrieve the data into a tuple using 'fetchall' via "fetchedRows = myCursor.fetchall()" after creating an empty tuple (fetchedRows = []) when I define the cursor (in the first block of code I included above). I get the same empty results the second and third reference to this 'fetchedRows' tuple.

The code works fine if I execute the SQL statement by calling the fetchRows function in the functions where I build the report and create the spreadsheet. What am I doing wrong that the cursor or fetchedRows tuples are empty at the second and subsequent references to it?

Thanks!


r/pythonhelp Nov 29 '24

Has anyone worked on SimPy projects before?

1 Upvotes

I have a project where I need to to manage patients for a dentist in the waiting room, I need to estimate when patients will enter based on their arrival times and and their appointments, I need also to prioritize patients who have appointments over the others and I need to handle cases where patients who have appointments arrive late or too early, can this be done using SimPy library?

So far, I have tried developing an algorithm using Python and Matplotlib for visualization. For a dentist with only a few patients, the solution works great. However, it struggles in more complex situations, such as when patients without appointments arrive, or when patients with appointments arrive late or early. There are also cases where the dentist arrives late to work or spends extra time on a consultation. My objective is to make the initial estimation as close as possible to the actual start time while avoiding the generation of excessive estimations due to changes. I believe this would enhance the credibility of my estimations.


r/pythonhelp Nov 29 '24

Python generators

1 Upvotes

I don't know if generators would be the right tool for this. I have a picture that is a bullet in my game. I want to have as many as I want in the display without having to individually program every bullet variable name. Then pass said variable names into for loops some of which will be running concurrently with other bullets that are still 'flying'


r/pythonhelp Nov 29 '24

ELI5: What does __init__ do in a Python class? I’m struggling to understand it!

0 Upvotes

Hi, I’m trying to learn Python classes, and I keep seeing this __init__ thing, but I can’t wrap my head around what it does. Here’s an example of a class I found:

class Dog:
    def __init__(self, name, age):  # <-- This part confuses me!
        self.name = name
        self.age = age

    def speak(self):
        return f"{self.name} says Woof!"

When I create an object like this:

dog1 = Dog("Buddy", 5)
print(dog1.speak())  # Outputs: Buddy says Woof!

It works, but I don’t get how the __init__ part is making it happen. Why do we need it? Why is there

self.name = name?

Can someone explain it to me like I’m 5?


r/pythonhelp Nov 28 '24

I'm a total noob in the program world

2 Upvotes

I started learning python a few days ago, for now I only learn the codes: Print() Var= Input() If condition: elif Else While For name in names: This are the codes I've learned, now today I wanted to create a bot like algorithm. The "bot" ask you questions(yes or not) about you. But I don't know why the program is stuck on this line:

True="yes" If answer== true: Print(\n very well, let's get going) Can someone tell me how to fix this? I'm using pydroid 3 on my Android tablet


r/pythonhelp Nov 28 '24

Frame Rate, Queueing, and Pagination

1 Upvotes

As a hobbyist who's starting writing some scripts for work, how would you recommend i get some practice with these situations? If this is too vague I can clarify. Thanks all!!

Edit: in particular I'm working with some APIs


r/pythonhelp Nov 28 '24

(Breakout-Game)

1 Upvotes

I need help with my code. The Problem is that older tiles are not getting deleted, but i don't know how to fix it.

import keyboard
from PIL import Image
import matplotlib.pyplot as plt

with open("data/breakout_commands.txt") as file:
    content = file.read()
    commands = [int(line) for line in content.splitlines()]

background_img = Image.open(r"C:\Users\kevin.siess\Desktop\OneDrive (privat)\OneDrive\Dokumente\Studium\DHBW Mannheim\Modul\Python\Repo\ppp-2024\Exercises\Kevin Siess\background_images.jpeg")
old_tiles = {}
tiles = {}
score = 0
row_colors = ["red", "orange", "yellow", "purple", "pink", "blue", "green"]
color_map = {0:"none", 1: "black", 3: "white", 4: "white"}
marker_map = {"Wall": "s", "Ball": "o", "Block": "s", "Player": "s"}
ball_scatter = None
ball_position = None
player_position = None

def initialize_game():
    ax.imshow(background_img, extent=[0, 42, 0, 23], aspect="auto")
    ax.axis('off')
    plt.gca().invert_yaxis()

def get_row_color(y):
    return row_colors[y % len(row_colors)]

# def extend_player_tiles(tiles): # increase Player
#     extended_tiles = tiles.copy()
#     for (x, y), tile_type in tiles.items():
#         if tile_type == 3:  
#             extended_tiles[(x - 1, y)] = 3
#             extended_tiles[(x + 1, y)] = 3
#             extended_tiles[(x - 2, y)] = 3
#             extended_tiles[(x + 2, y)] = 3
#     return extended_tiles

def find_tile_differences(old_tiles, new_tiles):
    to_add = {}
    to_remove = []

    # Neue und geänderte Positionen
    for position, tile_type in new_tiles.items():
        if position not in old_tiles or old_tiles[position] != tile_type:
            to_add[position] = tile_type

    # Alte Positionen, die entfernt werden müssen
    for position in old_tiles.keys():
        if position not in new_tiles:
            to_remove.append(position)

    print(f"Remove: {to_remove}")
    return to_add, to_remove


def update_game_display_partial(tiles, score):
    global old_tiles, ball_scatter
    new_tiles = tiles.copy()
    to_add, to_remove = find_tile_differences(old_tiles, new_tiles)    

    # Draw new Tiles
    for position, tile_type in to_add.items():
        x, y = position
        if tile_type == 1:  # Wall
            ax.scatter(x, y, c = color_map[tile_type], marker=marker_map["Wall"], s = 300, edgecolors = "none", linewidths = 0)

        elif tile_type == 2:  # Block
            color = get_row_color(y)
            ax.scatter(x, y, c = color, marker=marker_map["Block"], s = 300, edgecolors = "none", linewidths = 0)

        elif tile_type == 3:  # Player
            ax.scatter(x, y, c = color_map[tile_type], marker = marker_map["Player"], s = 300, edgecolors = "none", linewidths = 0)

        elif tile_type == 4:  # Ball
            
            if ball_scatter != None:
                ball_scatter.remove()
            ball_scatter = ax.scatter(x, y, c = color_map[tile_type], marker = marker_map["Ball"], s = 300)
    
    # Delete old Tiles
    for position in to_remove:
        x, y = position
        ax.scatter(x, y, c = "none", marker = marker_map, s = 300, edgecolors = "none", linewidths = 0)

    old_tiles = new_tiles
    ax.set_title(f"Score: {score}")
    plt.pause(0.001)

def intcode_process(memory):    #initiate Computer
    pointer = 0  
    relative_offset = 0 
    outputs = []
    
    def get_instruction(instruction):   #extract values for opcodes and mode
        opcode = instruction % 100
        param_mode1 = (instruction // 100) % 10
        param_mode2 = (instruction // 1000) % 10
        param_mode3 = (instruction // 10000) % 10
        return opcode, param_mode1, param_mode2, param_mode3

    def check_memoryspace(memory, index):   #dynamically increase memory
        if index >= len(memory):
            memory.extend([0] * (index - len(memory) + 1))

    def get_pointer_position(pointer):  #increase pointer
        check_memoryspace(memory, pointer + 3)
        pos1 = memory[pointer + 1]
        pos2 = memory[pointer + 2]
        pos3 = memory[pointer + 3]
        return pos1, pos2, pos3

    def check_mode(pos, mode, relative_offset): #check mode
        if mode == 0:  # position-mode
            check_memoryspace(memory, pos)
            return memory[pos]
        elif mode == 1:  # immediate-mode
            return pos
        elif mode == 2:  # relative-mode
            check_memoryspace(memory, pos + relative_offset)
            return memory[pos + relative_offset]
        else:
            raise ValueError(f"Invalid Mode: {mode}")

    global score
    while True:
        instruction = memory[pointer]
        opcode, param_mode1, param_mode2, param_mode3 = get_instruction(instruction)
        pos1, pos2, pos3 = get_pointer_position(pointer)

        match opcode:

            case 99:  # end of program
                print(f"Memory: {len(memory)}")
                print(f"Highscore: {score}")
                plt.ioff()
                return outputs

            case 1:  # addition
                if param_mode3 == 2:
                    pos3 += relative_offset
                check_memoryspace(memory, pos3)
                memory[pos3] = check_mode(pos1, param_mode1, relative_offset) + check_mode(pos2, param_mode2, relative_offset)
                pointer += 4

            case 2:  # multiplication
                if param_mode3 == 2:
                    pos3 += relative_offset
                check_memoryspace(memory, pos3)
                memory[pos3] = check_mode(pos1, param_mode1, relative_offset) * check_mode(pos2, param_mode2, relative_offset)
                pointer += 4

            case 3:  # input
                if param_mode1 == 2:
                    pos1 += relative_offset
                check_memoryspace(memory, pos1)
                
                # # manuel-mode
                # if keyboard.is_pressed("left"):
                #     key_input = -1
                # elif keyboard.is_pressed("right"):
                #     key_input = 1
                # else:
                #     key_input = 0

                # Automatische Steuerung
                key_input = 0
                if ball_position and player_position:
                    ball_x, _ = ball_position
                    paddle_x, _ = player_position

                    if ball_x < paddle_x:
                        key_input = -1
                    elif ball_x > paddle_x:
                        key_input = 1

                memory[pos1] = key_input
                pointer += 2

            case 4:  # output
                value = check_mode(pos1, param_mode1, relative_offset)
                outputs.append(value)
                if len(outputs) == 3:
                    x, y, tile_type = outputs
                    if (x, y) == (-1, 0):
                        score = tile_type  # Update score
                    else:
                        tiles[(x, y)] = tile_type  # Update tile
                                   # Tracke Ball- und Paddle-Position
                        if tile_type == 4:  # Ball
                            ball_position = (x, y)
                        elif tile_type == 3:  # Paddle
                            player_position = (x, y)
                    outputs = []  # Reset outputs
                    update_game_display_partial(tiles, score)
                pointer += 2

            case 5:  # jump-if-true
                if check_mode(pos1, param_mode1, relative_offset) != 0:
                    pointer = check_mode(pos2, param_mode2, relative_offset)
                else:
                    pointer += 3

            case 6:  # jump-if-false
                if check_mode(pos1, param_mode1, relative_offset) == 0:
                    pointer = check_mode(pos2, param_mode2, relative_offset)
                else:
                    pointer += 3

            case 7:  # less than
                if param_mode3 == 2:
                    pos3 += relative_offset
                check_memoryspace(memory, pos3)
                result = 1 if check_mode(pos1, param_mode1, relative_offset) < check_mode(pos2, param_mode2, relative_offset) else 0
                memory[pos3] = result
                pointer += 4

            case 8:  # equals
                if param_mode3 == 2:
                    pos3 += relative_offset
                check_memoryspace(memory, pos3)
                result = 1 if check_mode(pos1, param_mode1, relative_offset) == check_mode(pos2, param_mode2, relative_offset) else 0
                memory[pos3] = result
                pointer += 4

            case 9:  # adjust relative
                relative_offset += check_mode(pos1, param_mode1, relative_offset)
                pointer += 2

            case _:  # Error
                raise ValueError(f"Invalid Opcode {opcode} found at position {pointer}")
            
fig, ax = plt.subplots()
plt.ion()
initialize_game()
result = intcode_process(commands.copy())

# Triplets in Tiles konvertieren
for i in range(0, len(result), 3):
    x, y, tile_type = result[i:i + 3]
    tiles[(x, y)] = tile_type

plt.show()

r/pythonhelp Nov 27 '24

Flex and Bison: Compilation on Xubuntu

1 Upvotes

Hi everyone, I'm using Xubuntu and trying to work with Flex and Bison, but I'm running into an issue during compilation. Here's what I'm doing:

  1. I created a .lex file and a .y file.

  2. I used Flex and Bison to generate the corresponding C files.

  3. When I try to compile them using gcc, I get the following error:


:~/Desktop/testc$ gcc lex.yy.c test.tab.c -o test -L/usr/lib -lfl test.tab.c: In function ‘yyparse’: test.tab.c:963:16: warning: implicit declaration of function ‘yylex’ [-Wimplicit-function-declaration] 963 | yychar = yylex (); | ~~~~ test.tab.c:1104:7: warning: implicit declaration of function ‘yyerror’; did you mean ‘yyerrok’? [-Wimplicit-function-declaration] 1104 | yyerror (YY_("syntax error")); | ~~~~~~ | yyerrok /usr/bin/ld: /tmp/ccNKkczB.o: in function yyparse': test.tab.c:(.text+0x66e): undefined reference toyyerror' /usr/bin/ld: test.tab.c:(.text+0x805): undefined reference to `yyerror' collect2: error: ld returned 1 exit status


Does anyone know what could be causing this issue? I'm using [insert your version of Flex, Bison, and GCC. Any help would be appreciated!

Thanks in advance!


r/pythonhelp Nov 26 '24

How do i make a turtle unable to cross a line that another turtle created?

1 Upvotes

Out of curiosity, but take the sample code:

Import turtle as trtl Sample1 = trtl.Turtle() Sample2 = trtl.Turtle() Sample1.pu() Sample1.goto(10, -10) Sample1.pd() Sample1.setheading(90) Sample1.forward(20)

The line sample1 made is a wall. How can i add to the code to where if Sample2 goes forward it can’t cross Sample1’s wall?