Java – Execution of python scripts (application with several modules) on Android

I have a complicated python script (not just a py file) that I would like to integrate into my Java Android application. I don't want to rewrite python scripts on java because they have a lot of plugins with a good community and they do exactly what I need. I'm looking for a way to integrate them into my Android java application. The best I have found is Caquopy sdk (https://chaquo.com/chaquopy/) and it does exactly what I need, but they have a complicated licensing process and are very hostile to developers. , so it's impossible to use them nearby (I don't do it I want to spend a few months and then I found that I couldn't get a license from them). Therefore, I am looking for a more user-friendly solution for developers. I am considering the next options:

  1. render the service entirely on python. use help or broadcast to communicate with the activity. If there is an example, it will help a lot.
  2. wrap python in a lib and create a java service on it
  3. pre-create python code as native lib and use jni

I think # 1 I can do with Kivy. but I couldn't find an example for such a solution: I don't want to use kivy for the activity.

Will appreciate any idea.

2d – Comments on the game Python Turtle Blitz

For some strange reason, I decided to want to be fluent in simple games using Python Turtle Graphics. I'm not a coding newbie, but I still have a long way to go to reach the level I want to get to and I would love some help along the way. I have published the program below in Code Review Stack Exchange but I have not yet received the comments that I would like. I thought maybe people here could give me some advice from the game developer's perspective.

For example, was it crazy to have separate timers for the plane and the bomb? How well did I handle the game reset after the plane crashed or all the towers were destroyed? Is there a better way to do this? In general, how can I improve my implementation in terms of game development concepts and real coding?

There is a repo containing the sounds as well as the program here:

https://github.com/Robin-Andrews/Alien-Blitz-Retro-Game-with-Python-Turtle-Graphics

Thank you in advance for any comments.

# alien_blitz.py

import turtle
import random

try:
    import playsound  # Not part of standard Library.

    SOUND = True
except ImportError:
    SOUND = False

NUM_TOWERS = 20
MAX_TOWER_HEIGHT = 10
CURSOR_SIZE = 20
PLANE_DELAY = 40
BOMB_DELAY = 40
WIDTH = 800
HEIGHT = 600
cell_colors = ("black", "dark green", "brown")


def move_plane():
    global playing
    new_pos = (plane.xcor(), plane.ycor())
    if new_pos(0) > width // 2:
        plane.goto(- width // 2, plane.ycor() - size)
    else:
        plane.goto(plane.xcor() + 12, plane.ycor())

    if check_plane_tower_collision():
        playing = False
        restart(new_level=False)
    elif check_player_wins_level():
        restart(new_level=True)
    else:
        screen.update()
        turtle.ontimer(move_plane, PLANE_DELAY)


def check_player_wins_level():
    if score >= winning_score:
        player_wins_level()
        return True
    return False


def player_wins_level():
    update_score_display()
    if SOUND:
        playsound.playsound("victory.wav")


def check_plane_tower_collision():
    for tower in towers:
        for cell in tower:
            if plane.distance(cell) <= size / 2 + 10:  # Half cell size + half plane height
                plane_tower_collision()
                return True
    return False


def plane_tower_collision():
    bomb.hideturtle()  # If present when plane crashes
    plane.color("red")
    screen.update()
    if SOUND:
        playsound.playsound("plane_crash.wav")


def check_bomb_tower_collision():
    if playing:
        for tower in towers:
            for cell in tower:
                if bomb.distance(cell) <= size / 2 + 5:  # Half cell size + half bomb size
                    bomb_tower_collision(cell)
                    return True
        return False


def bomb_tower_collision(cell):
    global score, high_score
    if SOUND:
        playsound.playsound("bombed.wav", False)
    cell.setx(-1000)
    cell.clear()
    score += 10
    if score > high_score:
        high_score = score
    update_score_display()


def start_bomb_drop():
    # Prevent further key presses until drop is finished tp prevent event stacking.
    screen.onkey(None, "space")
    bomb.goto(plane.xcor(), plane.ycor())
    bomb.showturtle()
    __continue_bomb_drop()


def __continue_bomb_drop():
    global playing
    bomb.goto(bomb.xcor(), bomb.ycor() - 12)
    if check_bomb_tower_collision() or bomb.ycor() < - height // 2 or not playing:
        stop_bomb_drop()
    else:
        turtle.ontimer(__continue_bomb_drop, BOMB_DELAY)


def stop_bomb_drop():
    bomb.hideturtle()
    # It's now safe to allow another bomb drop, so rebind keyboard event.
    screen.onkey(start_bomb_drop, "space")


def update_score_display():
    pen.clear()
    pen.write("Score:{:2} High Score:{:2}".format(score, high_score), align="center", font=("Courier", 24, "normal"))


def get_towers():
    result = ()
    for col in range(-NUM_TOWERS // 2, NUM_TOWERS // 2):
        tower = ()
        for level in range(random.randrange(1, MAX_TOWER_HEIGHT + 1)):
            block = turtle.Turtle(shape="square")
            block.shapesize(size / CURSOR_SIZE)
            block.color(random.choice(cell_colors))
            block.penup()
            block.goto(col * size + offset, - height // 2 + level * size + offset)
            tower.append(block)
        result.append(tower)
    return result


def setup():
    global screen, plane, bomb, pen, high_score, size, offset, height, width, score
    # Screen
    screen = turtle.Screen()
    screen.title("Alien Blitz")
    screen.setup(WIDTH, HEIGHT)
    screen.bgcolor("dark blue")
    screen.listen()
    screen.onkey(start_bomb_drop, "space")
    screen.tracer(0)

    # MISC.
    width = screen.window_width() - 50
    height = screen.window_height() - 50
    size = width / NUM_TOWERS  # Size of tower cells in pixels
    offset = (NUM_TOWERS % 2) * size / 2 + size / 2  # Center even and odd cells

    # Plane
    plane = turtle.Turtle(shape="triangle", visible=False)
    plane.color("yellow")
    plane.shapesize(20 / CURSOR_SIZE, 40 / CURSOR_SIZE)
    plane.penup()
    plane.goto(- width // 2, height // 2)
    plane.showturtle()

    # Bomb
    bomb = turtle.Turtle(shape="circle")
    bomb.hideturtle()
    bomb.color("red")
    bomb.shapesize(0.5)
    bomb.penup()

    # Score Display
    pen = turtle.Turtle()
    pen.hideturtle()
    pen.color("white")
    pen.penup()
    pen.goto(0, 260)

    # Initialise high score
    high_score = 0


def restart(new_level=False):
    global score, high_score, winning_score, towers, playing
    #  Towers list does not exist on first call.
    try:
        for tower in towers:
            for cell in tower:
                cell.setx(-1000)
                cell.clear()
    except NameError:
        pass
    plane.color("yellow")
    towers = get_towers()
    # Here we handle the score for different scenarios for restarting the game - crashed plane or completed level.
    if not new_level:
        score = 0
        winning_score = sum(len(row) for row in towers) * 10
    else:
        winning_score += sum(len(row) for row in towers) * 10
    update_score_display()
    plane.goto(- width // 2, height // 2)
    bomb.goto(- width // 2, height // 2)
    playing = True
    screen.update()
    move_plane()


def main():
    setup()
    restart()


if __name__ == "__main__":
    main()
    turtle.done()


```

python – How to import additional modules into exe with pyinstaller?

[! [enter the description of the image here] [1]] [1] I have a problem generating an exe with pyinstaller, the executable is generated correctly, but when I run it run, it tells me it can't find the modules, I tried to look for a solution in the forums and manipulating the spec file, but it still doesn't give me results, pyinstaller, no matter the modules of the project, below I leave the modules that I use in the project, and an image with the error it gives me when executing the exe file

from PyQt5 import QtCore, QtGui, QtWidgets
from mp3_tagger import VERSION_2, MP3File
import miniaudio
import shutil
import os
import threading as th
import audio_metadata
import time
import pygame
from pygame.locals import *[![introducir la descripción de la imagen aquí][1]][1]


  [1]: https://i.stack.imgur.com/AkZaE.jpg

python – how to print the widget in the tk window by clicking on the button?

I wrote an algorithm for a calendar style that I found online. I would like it to print the algorithm in the tk window on the click of the button after entering a year. unfortunately, this will not be the case. I tested the algorithm alone using this code as an algorithm test tool.

def make_calendar(year, start_day):
    tup =   (('Early Winter', range(1, 37, + 1)),
            ('Mid Winter 37,', range(37, 1, + 1)),
            ('Late Winter   ', range(38, 71, + 1)),
            ('Leap Day      ', range(70, 69 + 1)),#tup(3) is this line i need to delete if not leap year
            ('Late Winter   ', range(71, 74, + 1)),   
            ('Early Spring  ', range(1, 37, + 1)),
            ('Mid Spring 37,', range(37, 1, +1)),
            ('Late Spring   ', range(38, 74, + 1)),
            ('Early Summer  ', range(1, 37, + 1)),
            ('Mid Summer 37,', range(37, 1, +1)),
            ('Late Summer   ', range(38, 74, + 1)),
            ('Early Autumn  ', range(1, 37, + 1)),
            ('Mid Autumn 37,', range(37, 1, +1)),
            ('Late Autumn   ', range(38, 74, + 1)),
            ('Early Fall    ', range(1, 37, + 1)),
            ('Mid Fall 37,  ', range(37, 1, +1)),
            ('Late Fall     ', range(38, 74, + 1)));
    week = ('Mer', 'Ven', 'Ear', 'Mar', 'Jup', 'Sat', 'Ura', 'Nep', 'Plu')
    start_pos = week.index(start_day)
    def is_leap(year): 
        if (not year%4 and year%100 or not year%400): # algorithm to determine leap year
            return True
    if not is_leap(year):
        del tup(3)
    for month, days in tup: 
    # Print month title
        print('{0} {1}'.format(month, year).center(20, ' '))
        # Print Day headings
        print(''.join(('{0:<3}'.format(w) for w in week)))
        # Add spacing for non-zero starting position
        print('{0:<3}'.format('')*start_pos, end='')

        for day in days:
            # Print day
            print('{0!s:<3}'.format(day), end='')
            start_pos += 1
            if start_pos == 9:
                # If start_pos == 9 (Sunday) start new line
                print()
                start_pos = 0 # Reset counter
        print('n')
start_day=(input('Enter start day of the year Mer,Ven,Ear,Mar,Jup,Sat,Ura,Nep,Plu'))
year=int(input('Enter Year'))       
make_calendar(year, start_day)

here i have designed a tkinter window on which the algorithm is supposed to print, but it will not print in the tk window and i am not getting any error message.
So basically the algorithm will work and print in the terminal but when it is coded to work in a tkinter window it does not return anything. the widget i created is useless if the algorithm does not print on it. I have tested the algorithm and it works. I tested the tkinter buttons and they don't seem to print. I do not know how to solve this problem.

import tkinter as tk

    #varContent = inputentry.get() # get what's written in the inputentry entry widget
    #outputtext.delete('0', 'end-1c') # clear the outputtext text widget
    #outputtext.insert(varContent)  # print content
    #these functions may be relevant to the solution I cannot figure out their implementation in this code.

HEIGHT = 700
WIDTH = 800


root = tk.Tk() #APPLICATION IS BETWEEN THIS LINE DOWN
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg='#80c1ff', bd='5')
frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')

button = tk.Button(frame, text="Display Calendar", command=lambda: make_calendar(entry.get()))
button.grid(row=0, column=2)#this makes the buton apear in a grid

label = tk.Label(frame, text="Enter the year")
label.grid(row=0, column=0)#this makes the label apear in a grid 

entry = tk.Entry(frame)
entry.grid(row=0, column=1)#this makes the entry apear in a grid

lower_frame = tk.Frame(root, bg='#80c1ff', bd='5')
lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')

lower_label = tk.Text(lower_frame)
lower_label.place(relwidth=1, relheight=1)#this makes the label apear in a grid 


year=entry.get

def make_calendar(year):
    tup =   (('Early Winter', range(1, 37, + 1)),
            ('Mid Winter 37,', range(37, 1, + 1)),
            ('Late Winter   ', range(38, 71, + 1)),
            ('Leap Day      ', range(70, 69 + 1)),#tup(3) is this line i need to delete if not leap year
            ('Late Winter   ', range(71, 74, + 1)),   
            ('Early Spring  ', range(1, 37, + 1)),
            ('Mid Spring 37,', range(37, 1, +1)),
            ('Late Spring   ', range(38, 74, + 1)),
            ('Early Summer  ', range(1, 37, + 1)),
            ('Mid Summer 37,', range(37, 1, +1)),
            ('Late Summer   ', range(38, 74, + 1)),
            ('Early Autumn  ', range(1, 37, + 1)),
            ('Mid Autumn 37,', range(37, 1, +1)),
            ('Late Autumn   ', range(38, 74, + 1)),
            ('Early Fall    ', range(1, 37, + 1)),
            ('Mid Fall 37,  ', range(37, 1, +1)),
            ('Late Fall     ', range(38, 74, + 1)));
    week = ('Mer  ', 'Ven  ', 'Ear  ', 'Mar  ', 'Jup  ', 'Sat  ', 'Ura  ', 'Nep  ', 'Plu  ')
    start_pos = week.index('Mer  ')
    def is_leap(year): 
            if (not year%4 and year%100 or not year%400): # algorithm to determine leap year
                    return True
    if not is_leap(year):
            del tup(3)
    for month, days in tup: 
        # Print month title
        print('{0} {1}'.format(month, year).center(20, ' '))
                    # Print Day headings
        print(''.join(('{0:<3}'.format(w) for w in week)))
                    # Add spacing for non-zero starting position
        print('{0:<3}'.format('')*start_pos, end='')

        for day in days:
                                # Print day
            print('{0!s:<6}'.format(day), end='')
            start_pos += 1
            if start_pos == 9:
                                        # If start_pos == 9 (Sunday) start new line
                print()
                start_pos = 0 # Reset counter
def make_calendar(year):
    button2 = tk.Button(frame, text="Print Calendar", function=print('n'))
    button2.grid(row=0, column=5)#this makes the buton apear in a grid
start_day=('Mer  ')
make_calendar(year)
root.mainloop()#APPLICATION IS BETWEEN THIS LINE^

stack overflow doesn't allow me to post right now and that seems to be the second most relevant place to ask.

python – the biggest items in the list and their indexes

How do i put indexes, bigger numbers like that
Reply:
clues: 1 0 2
Numbers: 7 5 2

I only managed to display one number in the list at a time, not all
what i have:
Index: 1
Numbers: 7

My code:

list = (5, 7, 2)

ind_num = list.index (max (list))
print (& # 39; Biggest item: & # 39 ;, max (list))
print (& # 39; Index: & # 39 ;, (ind_num))

python – Design of a turn-based dice game

I'm trying to build an irc-bot that serves as the manager of a multiplayer, turn-based, dice-rolling game. The bot listens to all messages on the channel. When the connections, it creates a Game example with all the players, except him, present in the chain.

There are two types of players in the game, regular players and lords. Being a lord is a cumulative property, you can be a lord with one count, with two, and so on.

The purpose of the first round is to assign lords. Each player must roll the dice at least once. If you throw pairs, you have to repeat. The three of you are assigned a lord.

Then you have two more rounds. Each player must roll the dice at least once more. If you launch pairs, you have to repeat, if you launch certain types of reels, you lose all your waiting reels. If you launch other types of reels, you can send a fight to another player. The fight is resolved until one of the two participants fails. It is important the number of rounds that the fight lasts.

I'm trying to build a loop style, along the lines of:

first_round: Round = next(self.game)

for turn in first_round:
    current_player = turn.player
    for dices in turn:
        dices.roll()

for the first round. The other tours must be managed via irc-bot, responding to chat messages. irc-bot has access to the Game example.

But I'm stuck with the code, I don't know how to continue.

class Dices:
    def __init__(self, left, right):
        # Canonical members of dices are ordered being the first the min and the second the max.
        self.left: int = left if left < right else right
        self.right: int = right if left >= right else left

    def roll(self):
        first_roll = random.randint(1, 6)
        second_roll = random.randint(1, 6)

        return Dices(first_roll, second_roll)

    def count_threes(self):
        return (1 if self.left == 3 else 0) + (1 if self.right == 3 else 0)

    def is_pair(self):
        return self.left == self.right

    def __eq__(self, other):
        if isinstance(other, Dices):
            return other.left == self.left and other.right == self.right
        else:
            return False

    def __str__(self):
        return f"({self.left},{self.right})"


class NotRollingDices(Dices):
    def roll(self):
        return NotImplementedError


class Pair(NotRollingDices):
    def __init__(self, num: int):
        super().__init__(num, num)


class Player:
    def __init__(self, name):
        self.name: str = name
        self.dices = Dices(0, 0)
        self.lords: int = 0

    def add_lord(self) -> None:
        self.lords = self.lords + 1

    def is_lord(self) -> bool:
        return self.lords_count() > 0

    def lords_count(self) -> int:
        return self.lords

    def roll(self) -> Dices:
        return self.dices.roll()

    def __str__(self):
        return f""

    def __eq__(self, other):
        if isinstance(other, Player):
            return self.name == other.name
        return False

    def __hash__(self):
        return self.name.__hash__()


class Turn(Iterator(Dices)):
    def __init__(self, player: Player, is_first: bool):
        self.player: Player = player
        self.is_first: bool = is_first
        self.pending_rolls: int = 3
        self.current_roll: Optional(Dices) = None

    def __next__(self) -> Dices:
        if self.pending_rolls == 0:
            raise StopIteration

        self.pending_rolls -= 1
        current_roll = self.player.roll()
        return current_roll

    def __str__(self):
        return f""


class Round(Iterator(Turn)):
    def __init__(self, players: Iterable(Player), is_first: bool):
        self.players = players
        self.is_first: bool = is_first
        self.current_turn = Optional(Turn)

    def __next__(self) -> Turn:
        for player in self.players:
            return Turn(player, self.is_first)
        raise StopIteration


class Game(Iterator(Round)):
    def __init__(self, pending_rounds: int = 3):
        self.players: set = set()
        self.pending_rounds: int = pending_rounds
        self.current_round: Optional(Round) = None

    def add_player(self, player: Player) -> None:
        self.players.add(player)

    def player_by_name(self, name: str) -> Optional(Player):
        for player in self.players:
            if player.name == name:
                return player
        return None

    def lords(self) -> List(Player):
        return (player for player in self.players if player.is_lord())

    def current_round(self) -> Round:
        return self.current_round

    def is_first_round(self):
        return self.pending_rounds == 3

    def __next__(self) -> Round:
        if self.pending_rounds <= 0:
            raise StopIteration

        self.pending_rounds -= 1
        self.current_round = Round(self.players, self.is_first_round())
        return self.current_round

python 3.x – update_or_create () argument after ** must be a mapping, not str

When you create an API using DRF, when you try to perform an PUT on an object, I encounter the following error:

update_or_create() argument after ** must be a mapping, not str

I understand that there must be a conversion from type str for the type mapping, but I don't see how to fix this with my code.

view.py

@api_view(('POST','PUT'))
def post_person(request):
    for index in request.data:
        Person.objects.update_or_create(**index)    

return Response(status=status.HTTP_200_OK)

class PersonViewSet(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

serializers.py

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('url','name','last_name','age','cpf')

    def create(self, validated_data):
        person_obj, created = Person.objects.update_or_create(
            name=validated_data.get('name', None),
            last_name=validated_data.get('last_name', None),
            age=validated_data.get('age', None),
            cpf=validated_data.get('cpf', None),
            defaults={'person_obj': validated_data.get('person_obj', None)})
        return person_obj

How do I run a Mathematica (.m) package from Python using the "Wolfram Client Library for Python"?

This question is about calling a Mathematica package (.m file) from Python using the "Wolfram Client Library for Python" (https://github.com/WolframResearch/WolframClientForPython).

To be concrete, consider the following Mathematica package:

BeginPackage("basicPackage`")
AddTwo::usage = "AddTwo(a, b) returns a+b";
Begin("Private`")
AddTwo(a_, b_) := a + b;
End()
EndPackage()

Goal: Call AddTwo from Python using the Wolfram client library for Python. If it is not currently supported, add this functionality to the library.

Library documentation can be found at: https://reference.wolfram.com/language/WolframClientForPython/index.html.

A similar question, asked before the release of the Wolfram client library for Python, is as follows:
How to run a Mathematica (.m) package from python?

python – A simple animation in pygame

I am following a tutorial on pygame. I realized that the code sample had been written to be easy to understand. I was wondering if I could "improve" the code, focusing on maintaining the same functionality. I have tried, but I'm not really sure if it's an improvement.

This is the original code of the instructions:

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')

WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png') # hosted at https://inventwithpython.com/cat.png
catx = 10
caty = 10
direction = 'right'

while True: # the main game loop
    DISPLAYSURF.fill(WHITE)

    if direction == 'right':
        catx += 5
        if catx == 280:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 220:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
            direction = 'right'

    DISPLAYSURF.blit(catImg, (catx, caty))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

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

This is my "improved" code. Two questions. In general, how can I improve my version and why is this improvement better than my code? And how could the original be improved?

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30
fps_clock = pygame.time.Clock()

window_size = (400,300)
DISPLAYSURF = pygame.display.set_mode(window_size,0,32)
pygame.display.set_caption("Animation test!")

WHITE = (255,255,255)
cat = pygame.image.load('assests/cat.png') # hosted at https://inventwithpython.com/cat.png
direction = 'right'
x_,y_ = 10,10


def listenToQuit():
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

def detectCollision(cat,x,y,window_size):
    return cat.get_size()(0) + x >= window_size(0) or 
        cat.get_size()(1) + y  >= window_size(1) or 
            x <= 0 or y <= 0

def getDirection(direction):
    directions = ('right','down','left','up')
    idx = directions.index(direction)
    idx = 0 if idx + 1 == len(directions) else idx + 1
    return directions(idx)

def getMovement(x,y,direction):
    if direction == 'right':
        return x+5,y
    elif direction == 'down':
        return x , y+5
    elif direction == 'left':
        return x - 5 , y
    elif direction == 'up':
        return x , y - 5

i = 0
while 1:
    DISPLAYSURF.fill(WHITE)

    x,y = getMovement(x_,y_,direction)
    while detectCollision(cat,x,y,window_size):  # if there would be a collision, change direction 
        direction = getDirection(direction)
        x,y = getMovement(x_,y_,direction) # re-calculate movement, now avoiding collision

    x_,y_ = x,y

    DISPLAYSURF.blit(cat,(x,y))
    listenToQuit()

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

I specifically chose not to make the animated object a class. I will try to do it as my next exercise towards myself.

python – Django does not read static "static" files

Well, everything was fine up to a point. Then I don't know what happened, or if I put something wrong and nothing else is working. Django has stopped reading static files.

When I try to enter a page from my app, the following error appears:
insert description of image here

I have checked my code several times but I found no error, the static part is as follows:

{% load static%}




    
    
    
    
    
    
    
    
    
    
    
    

And in the setting.py:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'staticfiles'),
)

What worries me most is that the admin page (http://127.0.0.1:8000/admin) also doesn't work. The following error appears:

insert description of image here

My directories:

insert description of image here

If you can help put an end to this error, thank you very much!