When hold or toggle trigger key and color is detected the code won't click mouse - python

Here's the code that I've been working on and fixing
from os import system, _exit
import mouse
import pyautogui
import pydirectinput
system("mode 80,18 & title Prefire & powershell $H=get-host;$W=$H.ui.rawui;$B=$W.buffersize;$B.width=80;$B.height=9999;$W.buffersize=$B;")
from time import sleep, perf_counter
from ctypes import WinDLL
def exit_():
system("echo Press any key to exit . . . & pause >nul")
_exit(0)
ERROR = "\x1b[38;5;255m[\x1b[31m-\x1b[38;5;255m]"
SUCCESS = "\x1b[38;5;255m[\x1b[32m+\x1b[38;5;255m]"
INFO = "\x1b[38;5;255m[\x1b[35m*\x1b[38;5;255m]"
try:
from PIL.Image import frombytes
from mss import mss
from keyboard import is_pressed, add_hotkey, block_key, unblock_key
except ModuleNotFoundError:
print(f"{INFO} Installing required modules.")
o = system("pip3 install keyboard mss pillow --quiet --no-warn-script-location --disable-pip-version-check")
try:
TRIGGER, HIGHLIGHT = [line.strip() for line in open("config.txt")]
print(f"{SUCCESS} Hotkey: {TRIGGER}\n{SUCCESS} Enemy highlight colour: {HIGHLIGHT}\n")
except (FileNotFoundError, ValueError):
print(f"{ERROR} Missing or invalid config.txt\n")
HIGHLIGHT = input(f"{INFO} Enemy highlight colour\n\n[\x1b[35m1\x1b[38;5;255m] Red (default)\n[\x1b[35m2\x1b[38;5;255m] Purple\n\n> ")
if HIGHLIGHT not in ["1", "2"]:
print(f"{ERROR} Choose 1 or 2 silly.\n")
exit_()
if HIGHLIGHT == "1":
HIGHLIGHT = "red"
elif HIGHLIGHT == "2":
HIGHLIGHT = "purple"
print(f"\n{SUCCESS} Wrote enemy highlight colour to config.txt\n{INFO} Now write your hotkey in config.txt\n")
with open("config.txt", "w") as f:
f.write(f"Replace this first line with your hotkey. e.g. c or ` or even ctrl + alt + z\n{HIGHLIGHT}")
exit_()
if HIGHLIGHT == "red":
R, G, B = (152, 20, 37)
elif HIGHLIGHT == "purple":
R, G, B = (254, 86, 254)
MODE = input(f"{INFO} Mode\n\n[\x1b[35m1\x1b[38;5;255m] Hold\n[\x1b[35m2\x1b[38;5;255m] Toggle\n\n> ")
if MODE not in ["1", "2"]:
print(f"{ERROR} Choose 1 or 2 silly.\n")
exit_()
user32, kernel32, shcore = WinDLL("user32", use_last_error=True), WinDLL("kernel32", use_last_error=True), WinDLL("shcore", use_last_error=True)
shcore.SetProcessDpiAwareness(2)
WIDTH, HEIGHT = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
TOLERANCE, ZONE = 20, 5
GRAB_ZONE = (int(WIDTH / 2 - ZONE), int(HEIGHT / 2 - ZONE), int(WIDTH / 2 + ZONE), int(HEIGHT / 2 + ZONE))
class PopOff:
def __init__(self):
self.active = False
kernel32.Beep(440, 75), kernel32.Beep(200, 100)
def switch(self):
self.active = not self.active
kernel32.Beep(440, 75), kernel32.Beep(700, 100) if self.active else kernel32.Beep(440, 75), kernel32.Beep(200, 100)
def search(self):
start_time = perf_counter()
with mss() as sct:
img = sct.grab(GRAB_ZONE)
pmap = frombytes("RGB", img.size, img.bgra, "raw", "BGRX")
for x in range(0, ZONE * 2):
for y in range(0, ZONE * 2):
r, g, b = pmap.getpixel((x, y))
if R - TOLERANCE < r < R + TOLERANCE and G - TOLERANCE < g < G + TOLERANCE and B - TOLERANCE < b < B + TOLERANCE:
print(f"\x1b[2A{SUCCESS} Reaction time: {int((perf_counter() - start_time) * 1000)}ms")
pyautogui.click(button='left')
break
def hold(self):
while 1:
if is_pressed(TRIGGER):
while is_pressed(TRIGGER):
self.search()
else:
sleep(0.1)
def toggle(self):
add_hotkey(TRIGGER, self.switch)
while 1:
self.search() if self.active else sleep(0.5)
o = system("cls")
if MODE == "1":
PopOff().hold()
elif MODE == "2":
PopOff().toggle()
I have tried various different methods like
using pyautogui.mouseDown() and pyautogui.mouseUp()
using pydirectinput
using pyautogui.click() instead of pyautogui.click(button='left')
using pyautogui.leftClick()
using pyautogui.click('left')
using mouse module such as mouse.click('left') when I use mouse.left the script seem to just crash and the error is 'str' object not callable

Related

How can I make my bars flash colors in stead of a constant color [duplicate]

This question already has answers here:
Neon effect in pygame?
(1 answer)
Bloom Effect in Pygame so that text glows [closed]
(1 answer)
Closed yesterday.
im making a visualizer using pygame and im just messing around with it and now instead of having a constant color on the bars that pygame makes I would like it to either flash different colors or cycle different colors as its playing on screen here is the code im working with and im not sure on how to change the colors instead of the constant color which is a blue color at the moment
import sys, math, wave, numpy, pygame
from pygame.locals import *
from scipy.fftpack import dct
Number = 30 # number of bars
HEIGHT = 600 # HEIGHT of a bar
WIDTH = 40 #WIDTH of a bar
FPS = 15
file_name = sys.argv[0]
status = 'stopped'
fpsclock = pygame.time.Clock()
#screen init, music playback
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode([Number * WIDTH, 50 + HEIGHT])
pygame.display.set_caption('Audio Visualizer')
my_font = pygame.font.SysFont('consolas', 16)
pygame.mixer.music.load("Sharp-Edges-half.cool.wav")
pygame.mixer.music.play()
pygame.mixer.music.set_endevent()
pygame.mixer.music.set_volume(0.2)
status = "Playing"
#process wave data
f = wave.open("Sharp-Edges-half.cool.wav", 'rb')
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
str_data = f.readframes(nframes)
f.close()
wave_data = numpy.fromstring(str_data, dtype = numpy.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
num = nframes
def Visualizer(nums):
num = int(nums)
h = abs(dct(wave_data[0][nframes - num:nframes - num + Number]))
h = [min(HEIGHT, int(i**(1 / 2.5) * HEIGHT / 100)) for i in h]
draw_bars(h)
def vis(status):
global num
if status == "stopped":
num = nframes
return
elif status == "paused":
Visualizer(num)
else:
num -= framerate / FPS
if num > 0:
Visualizer(num)
def get_time():
seconds = max(0, pygame.mixer.music.get_pos() / 1000)
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
hms = ("%02d:%02d:%02d" % (h, m, s))
return hms
def controller(key):
global status
if status == "stopped":
if key == K_RETURN:
pygame.mixer_music.play()
status = "playing"
elif status == "paused":
if key == K_RETURN:
pygame.mixer_music.stop()
status = "stopped"
elif key == K_SPACE:
pygame.mixer.music.unpause()
status = "playing"
elif status == "playing":
if key == K_RETURN:
pygame.mixer.music.stop()
status = "stopped"
elif key == K_SPACE:
pygame.mixer.music.pause()
status = "paused"
def draw_bars(h):
bars = []
for i in h:
bars.append([len(bars) * WIDTH , 50 + HEIGHT - i, WIDTH - 1, i])
for i in bars:
pygame.draw.rect(screen, [5,34,250], i, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN:
controller(event.key)
if num <= 0:
status = "stopped"
name = my_font.render(file_name, True, (255,255,255))
info = my_font.render(status.upper() + "" + get_time(), True, (255,255,255))
screen.fill((0,0,0))
screen.blit(name,(0,0))
screen.blit(info,(0, 18))
fpsclock.tick(FPS)
vis(status)
pygame.display.update()

Python to Exe conversion not working, windll.user32.ReleaseDC failed : return 0

so I got my Python Skript that works perfectly fine when I run it in Thonny.
So I wanted to convert it to a exe to make it easy to execute, for that purpose I found the plugin pyinstaller, when I now convert my file with pyinstaller i do always get the following error:
error
Could it be that it got some kind of problem with my imports, I am importing the following libs: time, win32api, pynput, pyscreeze.
Full Python Code:
#import libs from pynput.mouse import Button, Controller
from pynput.mouse import Button, Controller
from win32api import GetSystemMetrics
import pyscreeze
import time
#class definition
class Btn:
def __init__(self, x, y, r, g, b):
self.x = x
self.y = y
self.color = Color(r, g, b)
class Color:
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Screen:
width = GetSystemMetrics(0)
height = GetSystemMetrics(1)
#helper functions
def percentToPixel(size, percent):
return (size * percent)
def leftClick():
mouse.press(Button.left)
mouse.release(Button.left)
def clickBtn(btn):
mouse.position = (btn.x, btn.y)
leftClick()
#init global variables
#input variables
totalTimesInput = int(input('Total Runs: '))
#init screenSize
screenSize = Screen()
#init mouse
mouse = Controller()
#continue Button
cntBtn = Btn(int(percentToPixel(screenSize.width, 0.7104)), int(percentToPixel(screenSize.height, 0.8258)), 90, 142, 214)
#go Buttons
goBtn1 = Btn(int(percentToPixel(screenSize.width, 0.811)), int(percentToPixel(screenSize.height, 0.679)), 247, 202, 66) # input correct color values for go buttons
goBtn2 = Btn(int(percentToPixel(screenSize.width, 0.896)), int(percentToPixel(screenSize.height, 0.7925)), 247, 202, 66)
#main function
def main():
time.sleep(5)
runCount = 0
print('-- Started --')
isGoBtn = pyscreeze.pixelMatchesColor(goBtn1.x, goBtn1.y, (goBtn1.color.r, goBtn1.color.g, goBtn1.color.b), tolerance=10)
if isGoBtn:
print('\tStarting / Run_Nr.: ' + str(runCount + 1))
clickBtn(goBtn1)
print('\t\tGo_1 Clicked (' + time.strftime("%H:%M:%S") + ')')
time.sleep(0.5)
clickBtn(goBtn2)
print('\t\tGo_2 Clicked (' + time.strftime("%H:%M:%S") + ')')
runCount += 1
while True:
#check for continue button
isCntBtn = pyscreeze.pixelMatchesColor(cntBtn.x, cntBtn.y, (cntBtn.color.r, cntBtn.color.g, cntBtn.color.b), tolerance=10)
#if continue button is visible
if runCount < totalTimesInput:
if isCntBtn:
print('\tStarting / Run_Nr.: ' + str(runCount + 1))
clickBtn(cntBtn)
runCount += 1
print('\t\tContinue clicked (' + time.strftime("%H:%M:%S") + ')')
time.sleep(1)
else:
if isCntBtn:
print('-- Finnished --')
break
#calling main function
main()
Thanks for the help

TypeError: start_new_game() missing 1 required positional argument: 'max_health' [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So I have been trying to figure out why I keep getting this error, even though everything is run from my game_view.py module. Everytime I press the 1 key to start a game and test to see if the players health bar and hit points works, I get this error message. TypeError: start_new_game() missing 1 required positional argument: 'max_health'
The sad part is, is that it reffers me to the start_view which doesn't have anything to do with anything else but running the start screen so players can choose to play solo or with another player. Below is the game_view and start_view so you guys can see where I'm going wrong. I wanted to test this out so this way I can add other enemies, bosses and power-ups later, but running into this error for the past several days is hindering progress. Anyway, code for both will be below. Thanks in advance for any and all help.
start_view:
import arcade
from game_view import GameView
class StartView(arcade.View):
def on_show(self):
# This is run once when we switch to this view
arcade.set_background_color(arcade.csscolor.BLACK)
# Reset the viewport, necessary if we have a scrolling game
arcade.set_viewport(0, self.window.width, 0, self.window.height)
def on_draw(self):
# Draw this view
arcade.start_render()
line_height = 70
line_location = self.window.height - line_height * 2
arcade.draw_text("Space Defense Force",
self.window.width / 2,
line_location,
arcade.color.WHITE,
font_size=50,
anchor_x="center",
font_name="SF Atarian System")
line_location -= line_height
line_location -= line_height
arcade.draw_text("1 - Start One Player Game",
self.window.width / 2,
line_location,
arcade.color.WHITE,
font_size=20,
anchor_x="center",
font_name="SF Atarian System")
# if len(self.window.joysticks) > 1:
# color = arcade.color.WHITE
# else:
# color = arcade.color.GRAY
color = arcade.color.GRAY
line_location -= line_height
arcade.draw_text("2 - Start Two Player Game",
self.window.width / 2,
line_location,
color,
font_size=20,
anchor_x="center",
font_name="SF Atarian System")
line_location -= line_height
line_location -= line_height
color = arcade.color.WHITE
arcade.draw_text("Use joysticks to play, or arrow keys to move and number keys to fire.",
self.window.width / 2,
line_location,
color,
font_size=20,
anchor_x="center",
font_name="SF Atarian System")
def on_key_press(self, symbol: int, modifiers: int):
if symbol == arcade.key.KEY_1:
game_view = GameView()
game_view.start_new_game(1)
self.window.show_view(game_view)
elif symbol == arcade.key.KEY_2:
game_view = GameView()
game_view.start_new_game(2)
self.window.show_view(game_view)
game_view:
import random
import math
import arcade
from health import Health
from game_over_view import GameOverView
from typing import cast
from arcade.experimental.shadertoy import Shadertoy
from constants import *
from asteroid_sprite import AsteroidSprite
from ship_sprite import ShipSprite
from bullet import Bullet
from glow_line import GlowLine
from glow_ball import GlowBall
from explosion import ExplosionMaker
from glow_image_sprite import GlowImageSprite
from window import Window as window
class GameView(arcade.View):
# Main application class
def __init__(self):
super().__init__()
# Sprite lists
self.player_sprite_list = arcade.SpriteList()
self.asteroid_list = arcade.SpriteList()
self.bullet_list = arcade.SpriteList()
self.ship_life_list = arcade.SpriteList()
self.health_list = arcade.SpriteList()
# Sounds
self.laser_sound = arcade.load_sound(":resources:sounds/hurt5.wav")
self.hit_sound1 = arcade.load_sound(":resources:sounds/explosion1.wav")
self.hit_sound2 = arcade.load_sound(":resources:sounds/explosion2.wav")
self.hit_sound3 = arcade.load_sound(":resources:sounds/hit1.wav")
self.hit_sound4 = arcade.load_sound(":resources:sounds/hit2.wav")
self.dead_sound = arcade.load_sound(":resources:sounds/gameover2.wav")
self.glowball_shadertoy = Shadertoy.create_from_file(self.window.get_size(), "glow_ball.glsl")
self.glowline_shadertoy = Shadertoy.create_from_file(self.window.get_size(), "glow_line.glsl")
self.explosion_list = []
# for joystick in self.window.joysticks:
# joystick.push_handlers(self)
def start_new_game(self, player_count, max_health):
#Set up the game and initialize the variables
self.game_over = False
arcade.set_background_color(arcade.csscolor.BLACK)
# Sprite lists
self.player_sprite_list = arcade.SpriteList()
self.asteroid_list = arcade.SpriteList()
self.bullet_list = arcade.SpriteList()
self.ship_life_list = arcade.SpriteList()
self.health_list = arcade.SpriteList()
# if len(self.window.joysticks) > 0:
# joystick = self.window.joysticks[0]
# else:
# joystick = None
joystick = None
player_sprite = ShipSprite(":resources:images/space_shooter/playerShip1_orange.png",
SCALE,
joystick,
player_no=1,
player_count=player_count,
max_health=5)
self.player_sprite_list.append(player_sprite)
self.health_list.append(max_health)
if player_count > 1:
joystick = None
# if len(self.window.joysticks) > 1:
# joystick = self.window.joysticks[1]
# else:
# joystick = None
player_sprite = ShipSprite(":resources:images/space_shooter/playerShip1_green.png",
SCALE,
joystick,
player_no=2,
player_count=player_count,
max_health=5
)
self.player_sprite_list.append(player_sprite)
self.health_list.append(max_health)
# Set up the player
for player in self.player_sprite_list:
player.score = 0
player.lives = 3
# Set up the little icons that represent the player lives.
cur_pos = 10
for i in range(self.player_sprite_list[0].lives):
life = arcade.Sprite(":resources:images/space_shooter/playerLife1_orange.png", SCALE)
life.center_x = cur_pos + life.width
life.center_y = life.height
cur_pos += life.width
self.ship_life_list.append(life)
if len(self.player_sprite_list) > 1:
cur_pos = 100
for i in range(self.player_sprite_list[1].lives):
life = arcade.Sprite(":resources:images/space_shooter/playerLife1_green.png", SCALE)
life.center_x = cur_pos + life.width
life.center_y = life.height
cur_pos += life.width
self.ship_life_list.append(life)
# Make the asteroids
image_list = (":resources:images/space_shooter/meteorGrey_big1.png",
":resources:images/space_shooter/meteorGrey_big2.png",
":resources:images/space_shooter/meteorGrey_big3.png",
":resources:images/space_shooter/meteorGrey_big4.png")
for i in range(STARTING_ASTEROID_COUNT):
image_no = random.randrange(4)
enemy_sprite = AsteroidSprite(image_list[image_no], SCALE)
enemy_sprite.guid = "Asteroid"
enemy_sprite.center_y = random.randrange(BOTTOM_LIMIT, TOP_LIMIT)
enemy_sprite.center_x = random.randrange(LEFT_LIMIT, RIGHT_LIMIT)
enemy_sprite.change_x = random.random() * 2 - 1
enemy_sprite.change_y = random.random() * 2 - 1
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 4
self.asteroid_list.append(enemy_sprite)
def on_draw(self):
# Render the screen.
# This command has to happen before we start drawing
arcade.start_render()
# Draw all the sprites.
self.asteroid_list.draw()
self.ship_life_list.draw()
for bullet in self.bullet_list:
bullet.draw()
self.bullet_list.draw()
for explosion in self.explosion_list:
explosion.render()
self.player_sprite_list.draw()
self.health_list.draw()
# Put the text on the screen.
output = f"Player 1 Score: {self.player_sprite_list[0].score}"
arcade.draw_text(output, 10, 40, arcade.color.AMBER,
font_size=15,
font_name="Arcade")
if len(self.player_sprite_list) > 1:
output = f"Player 2 Score: {self.player_sprite_list[1].score}"
arcade.draw_text(output, 500, 40, arcade.color.AMBER,
font_size=15,
font_name="Arcade")
output = f"Asteroid Count: {len(self.asteroid_list)}"
arcade.draw_text(output, 10, 80, arcade.color.AMBER,
font_size=15,
font_name="Arcade")
for player in health_list:
player.draw_health_number()
player.draw_health_bar()
# def on_joybutton_press(self, joystick, button):
# # What player is this?
# if joystick == self.window.joysticks[0]:
# player_sprite = self.player_sprite_list[0]
# else:
# player_sprite = self.player_sprite_list[1]
# if player_sprite.player_no == 1:
# color = 255, 128, 128
# else:
# color = 128, 255, 128
# if button == 0:
# self.fire_circle(color, player_sprite, player_no=player_sprite.player_no)
# elif button == 1:
# self.fire_line(color, player_sprite, player_no=player_sprite.player_no)
# elif button == 2:
# bullet_sprite = GlowImageSprite(":resources:images/space_shooter/laserBlue01.png",
# SCALE,
# glowcolor=arcade.color.WHITE,
# shadertoy=self.glowball_shadertoy,
# player_no=player_sprite.player_no)
# self.set_bullet_vector(bullet_sprite, 10, player_sprite)
# arcade.play_sound(self.laser_sound)
def on_key_press(self, symbol, modifiers):
# Shoot if the player hit the space bar and we aren't respawning.
if symbol == arcade.key.LEFT:
self.player_sprite_list[0].change_angle = 3
elif symbol == arcade.key.RIGHT:
self.player_sprite_list[0].change_angle = -3
elif symbol == arcade.key.UP:
self.player_sprite_list[0].thrust = 0.15
elif symbol == arcade.key.DOWN:
self.player_sprite_list[0].thrust = -.2
elif symbol == arcade.key.KEY_1:
color = (255, 128, 128)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_2:
color = (128, 255, 128)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_3:
color = (128, 128, 255)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_4:
color = (255, 128, 255)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_5:
color = (255, 255, 255)
self.fire_line(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_6:
color = (64, 255, 64)
self.fire_line(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_7:
bullet_sprite = GlowImageSprite(":resources:images/space_shooter/laserBlue01.png",
SCALE,
glowcolor=arcade.color.WHITE,
shadertoy=self.glowball_shadertoy,
player_no=0)
self.set_bullet_vector(bullet_sprite, 13, self.player_sprite_list[0])
arcade.play_sound(self.laser_sound)
def fire_circle(self, bullet_color, player_sprite, player_no):
bullet_sprite = GlowBall(glowcolor=bullet_color,
radius=5,
shadertoy=self.glowball_shadertoy,
player_no=player_no)
self.set_bullet_vector(bullet_sprite, 5, player_sprite)
arcade.play_sound(self.laser_sound)
def fire_line(self, bullet_color, player_sprite, player_no):
bullet_sprite = GlowLine(glowcolor=bullet_color,
shadertoy=self.glowline_shadertoy,
player=player_sprite,
player_no=player_no)
self.set_bullet_vector(bullet_sprite, 13, player_sprite)
arcade.play_sound(self.laser_sound)
def set_bullet_vector(self, bullet_sprite, bullet_speed, player_sprite):
bullet_sprite.change_y = \
math.cos(math.radians(player_sprite.angle)) * bullet_speed
bullet_sprite.change_x = \
-math.sin(math.radians(player_sprite.angle)) \
* bullet_speed
bullet_sprite.center_x = player_sprite.center_x
bullet_sprite.center_y = player_sprite.center_y
self.bullet_list.append(bullet_sprite)
def on_key_release(self, symbol, modifiers):
# Called whenever a key is released
if symbol == arcade.key.LEFT:
self.player_sprite_list[0].change_angle = 0
elif symbol == arcade.key.RIGHT:
self.player_sprite_list[0].change_angle = 0
elif symbol == arcade.key.UP:
self.player_sprite_list[0].thrust = 0
elif symbol == arcade.key.DOWN:
self.player_sprite_list[0].thrust = 0
def split_asteroid(self, asteroid: AsteroidSprite):
# Split an asteroid into chunks
x = asteroid.center_x
y = asteroid.center_y
if asteroid.size == 4:
for i in range(3):
image_no = random.randrange(2)
image_list = [":resources:images/space_shooter/meteorGrey_med1.png",
":resources:images/space_shooter/meteorGrey_med2.png"]
enemy_sprite = AsteroidSprite(image_list[image_no],
SCALE * 1.5)
enemy_sprite.center_y = y
enemy_sprite.center_x = x
enemy_sprite.change_x = random.random() * 2.5 - 1.25
enemy_sprite.change_y = random.random() * 2.5 - 1.25
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 3
self.asteroid_list.append(enemy_sprite)
self.hit_sound1.play()
elif asteroid.size == 3:
for i in range(3):
image_no = random.randrange(2)
image_list = [":resources:images/space_shooter/meteorGrey_small1.png",
":resources:images/space_shooter/meteorGrey_small2.png"]
enemy_sprite = AsteroidSprite(image_list[image_no],
SCALE * 1.5)
enemy_sprite.center_y = y
enemy_sprite.center_x = x
enemy_sprite.change_x = random.random() * 3 - 1.5
enemy_sprite.change_y = random.random() * 3 - 1.5
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 2
self.asteroid_list.append(enemy_sprite)
self.hit_sound2.play()
elif asteroid.size == 2:
for i in range(3):
image_no = random.randrange(2)
image_list = [":resources:images/space_shooter/meteorGrey_tiny1.png",
":resources:images/space_shooter/meteorGrey_tiny2.png"]
enemy_sprite = AsteroidSprite(image_list[image_no],
SCALE * 1.5)
enemy_sprite.center_y = y
enemy_sprite.center_x = x
enemy_sprite.change_x = random.random() * 3.5 - 1.75
enemy_sprite.change_y = random.random() * 3.5 - 1.75
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 1
self.asteroid_list.append(enemy_sprite)
self.hit_sound3.play()
elif asteroid.size == 1:
self.hit_sound4.play()
def on_update(self, x, delta_time):
# Move everything
self.asteroid_list.update()
self.bullet_list.update()
self.player_sprite_list.update()
self.health_list.update()
explosion_list_copy = self.explosion_list.copy()
for explosion in explosion_list_copy:
explosion.update(x)
if explosion.time > .9:
self.explosion_list.remove(explosion)
for bullet in self.bullet_list:
hit_list = arcade.check_for_collision_with_list(bullet, self.player_sprite_list)
# If it did hit, get rid of sprite
if len(hit_list) > 0:
bullet.remove_from_lists()
for player in hit_list:
if not isinstance(player, ShipSprite):
raise TypeError("List contents must be all ints")
# Remove one health point
player.cur_health -= 1
# Check Health
if player.cur_health <= 0:
arcade.play_sound(self.dead_sound)
view=GameOverView
self.window.show_view(view)
else:
# Not Dead
arcade.play_sound(self.hit_sound1)
assert isinstance(bullet, Bullet)
asteroids = arcade.check_for_collision_with_list(bullet, self.asteroid_list)
if len(asteroids) > 0:
explosion = ExplosionMaker(self.window.get_size(), bullet.position)
self.explosion_list.append(explosion)
for asteroid in asteroids:
assert isinstance(asteroid, AsteroidSprite)
self.player_sprite_list[bullet.player_no - 1].score += 1
self.split_asteroid(cast(AsteroidSprite, asteroid)) # expected AsteroidSprite, got Sprite instead
asteroid.remove_from_sprite_lists()
bullet.remove_from_sprite_lists()
# Remove bullet if it goes off-screen
size = max(bullet.width, bullet.height)
if bullet.center_x < 0 - size:
bullet.remove_from_sprite_lists()
if bullet.center_x > SCREEN_WIDTH + size:
bullet.remove_from_sprite_lists()
if bullet.center_y < 0 - size:
bullet.remove_from_sprite_lists()
if bullet.center_y > SCREEN_HEIGHT + size:
bullet.remove_from_sprite_lists()
for player in self.player_sprite_list:
assert isinstance(player, ShipSprite, max_health)
if not player.respawning:
asteroids = arcade.check_for_collision_with_list(player, self.asteroid_list)
if len(asteroids) > 0:
if player.lives > 0:
player.lives -= 1
player.respawn()
self.split_asteroid(cast(AsteroidSprite, asteroids[0]))
asteroids[0].remove_from_sprite_lists()
self.ship_life_list.pop().remove_from_sprite_lists()
elif len(asteroids) > 0:
if player.health > 0:
player.health -=1
player.respawn()
self.split_asteroid(cast(AsteroidSprite, asteroids[0]))
asteroids[0].remove_from_sprite_lists()
self.ship_list_list.pop().remove_from_sprite_lists()
else:
arcade.play_sound(self.dead_sound)
view = GameOverView()
self.window.show_view(view)
Sorry in advance if I have tons of code to go through. But like I said I am adding some features that wasn't in the Arcade Repository from github. I even set a separte module for the health bar and hit points so this way I can see what conflicts. But the error above has been a royal pain.Thanks again.
P.S. Remarked out joysticks because it was conflicting with another module I built.
As your title says, your start game function requires 2 arguments: player_count and max_healh. And in your code, when using start_new_game, you aren't supplying the max_health argument, thus raising an error.
(function) start_new_game(self, player_count, max_health)

Label Position, Resize Background And Hide Title Bar

I'm trying to better understand Pyglet and I'm using a script posted by Torxed in my previous question. I started to modify it until I reached this point:
import pyglet, datetime, os
from pyglet.gl import *
from collections import OrderedDict
from time import time
from pathlib import Path
key = pyglet.window.key
class main(pyglet.window.Window):
#Variable Display
Fullscreen = False
CountDisplay = 0
setDisplay0 = (1024, 576)
setDisplay1 = (800, 600)
setDisplay2 = (1024, 768)
setDisplay3 = (1280, 720)
setDisplay4 = (1280, 1024)
setDisplay5 = (1366, 768)
setDisplay6 = (1920, 1080)
#Variable Info
infoHidden = False
title = "Pokémon Life And Death: Esploratori Del Proprio Destino"
build = "Versione: 0.0.0"
keyPrint = "Nessuno"
MousekeyPrint = "Nessuno"
infoFullscreen = "Disattivo"
infoDisplay = "1024, 576"
def __init__ (self, width=1024, height=576, fullscreen=False, *args, **kwargs):
super(main, self).__init__(width, height, fullscreen, *args, **kwargs)
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
self.infoScreen = (screen.width, screen.height)
self.xDisplay = int(screen.width / 2 - self.width / 2)
self.yDisplay = int(screen.height / 2 - self.height / 2)
self.set_location(self.xDisplay, self.yDisplay)
self.sprites = OrderedDict()
self.spritesInfo = OrderedDict()
#Information Hidden
#Title
self.spritesInfo["title_label"] = pyglet.text.Label(self.title, x=self.infoPos("x", 0), y=self.infoPos("y", 0))
#Build Version
self.spritesInfo["build_label"] = pyglet.text.Label(self.build, x=self.infoPos("x", 0), y=self.infoPos("y", 20))
#Fullscreen
self.spritesInfo["fullscreen_label"] = pyglet.text.Label("Fullscreen: " + self.infoFullscreen, x=self.infoPos("x", 0), y=self.infoPos("y", 40))
#Display
self.spritesInfo["screen_label"] = pyglet.text.Label("Display: " + self.infoDisplay, x=self.infoPos("x", 0), y=self.infoPos("y", 60))
#FPS
self.spritesInfo["fps_label"] = pyglet.text.Label("FPS: 0", x=self.infoPos("x", 0), y=self.infoPos("y", 80))
self.last_update = time()
self.fps_count = 0
#Mouse Position
self.mouse_x = 0
self.mouse_y = 0
self.spritesInfo["mouse_label"] = pyglet.text.Label(("Mouse Position (X,Y): " + str(self.mouse_x) + "," + str(self.mouse_y)), x=self.infoPos("x", 0), y=self.infoPos("y", 100))
#Player Position
self.player_x = 0
self.player_y = 0
self.spritesInfo["player_label"] = pyglet.text.Label(("Player Position (X,Y): " + str(self.player_x) + "," + str(self.player_y)), x=self.infoPos("x", 0), y=self.infoPos("y", 120))
#Key Press
self.keys = OrderedDict()
self.spritesInfo["key_label"] = pyglet.text.Label(("Key Press: " + self.keyPrint), x=self.infoPos("x", 0), y=self.infoPos("y", 140))
#Mouse Press
self.spritesInfo["MouseKey_label"] = pyglet.text.Label(("Mouse Key Press: " + self.MousekeyPrint), x=self.infoPos("x", 0), y=self.infoPos("y", 160))
self.alive = 1
def infoPos(self, object, ny):
posInfo = self.get_size()
if object is "x":
elab = 10
elif object is "y":
elab = posInfo[1] - 20 - ny
else:
elab = 0
return elab
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_x = x
self.mouse_y = y
def on_mouse_release(self, x, y, button, modifiers):
self.MousekeyPrint = "Nessuno"
def on_mouse_press(self, x, y, button, modifiers):
self.MousekeyPrint = str(button)
def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
self.drag = True
print('Dragging mouse at {}x{}'.format(x, y))
def on_key_release(self, symbol, modifiers):
self.keyPrint = "Nessuno"
try:
del self.keys[symbol]
except:
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE:
self.alive = 0
if symbol == key.F2:
datanow = datetime.datetime.now()
if not Path("Screenshot").is_dir():
os.makedirs("Screenshot")
pyglet.image.get_buffer_manager().get_color_buffer().save("Screenshot/"+str(datanow.day)+"-"+str(datanow.month)+"-"+str(datanow.year)+"_"+str(datanow.hour)+"."+str(datanow.minute)+"."+str(datanow.second)+".png")
if symbol == key.F3:
if self.infoHidden:
self.infoHidden = False
else:
self.infoHidden = True
if symbol == key.F10:
self.CountDisplay += 1
if self.CountDisplay == 1:
size = self.setDisplay1
elif self.CountDisplay == 2:
size = self.setDisplay2
elif self.CountDisplay == 3:
size = self.setDisplay3
elif self.CountDisplay == 4:
size = self.setDisplay4
elif self.CountDisplay == 5:
size = self.setDisplay5
elif self.CountDisplay == 6:
size = self.setDisplay6
else:
self.CountDisplay = 0
size = self.setDisplay0
self.set_size(size[0], size[1])
self.infoDisplay = str(size[0]) + "," + str(size[1])
pos = (int(self.infoScreen[0] / 2 - size[0] / 2), int(self.infoScreen[1] / 2 - size[1] / 2))
self.set_location(pos[0], pos[1])
if symbol == key.F11:
if self.Fullscreen:
self.Fullscreen = False
self.set_fullscreen(False)
self.infoFullscreen = "Disattivo"
else:
self.Fullscreen = True
self.set_fullscreen(True)
self.infoFullscreen = "Attivo"
self.keyPrint = str(symbol)
self.keys[symbol] = True
def pre_render(self):
pass
def render(self):
self.clear()
#FPS
self.fps_count += 1
if time() - self.last_update > 1:
self.spritesInfo["fps_label"].text = "FPS: " + str(self.fps_count)
self.fps_count = 0
self.last_update = time()
#Mouse Position
self.spritesInfo["mouse_label"].text = "Mouse Position (X,Y): " + str(self.mouse_x) + "," + str(self.mouse_y)
#Player Position
self.spritesInfo["player_label"].text = "Player Position (X,Y): " + str(self.player_x) + "," + str(self.player_y)
#Key Press
self.spritesInfo["key_label"].text = "Key Press: " + self.keyPrint
#Mouse Press
self.spritesInfo["MouseKey_label"].text = "Mouse Key Press: " + self.MousekeyPrint
#Fullscreen
self.spritesInfo["fullscreen_label"].text = "Fullscreen: " + self.infoFullscreen
#Display
self.spritesInfo["screen_label"].text = "Display: " + self.infoDisplay
#self.bg.draw()
self.pre_render()
for sprite in self.sprites:
self.sprites[sprite].draw()
if self.infoHidden:
for spriteInfo in self.spritesInfo:
self.spritesInfo[spriteInfo].draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
event = self.dispatch_events()
if __name__ == '__main__':
x = main()
x.run()
But now I find myself in front of a point where I can not proceed in Pyglet alone.
I can not understand how I can change the coordinates of the "label" every time the window size changes.
I would like to be able to use an image as a background and adapt it to the size of the window (basic the image is 1920x1080, ie the maximum window size). The problem is that I did not find much on this subject. I state that what I'm working on is 2D, not 3D. I had found a possible solution in another question, always answered by Torxed on the resizing of an image, but in some tests before this, after having adapted it, it did not work. So I do not know where to bang my head sincerely. In Pygame it was easy to use "pygame.transform.scale", but in Pyglet I would not know.
Finally, I tried both on the Pyglet wiki and on the web, but I did not find anything. How can I delete or hide the window title bar? In Pygame, you could with the flags. Is it possible to do this also with Pyglet?
EDIT:
I forgot to ask another question. When I press a key on the keyboard or mouse, the information displayed with F3 is printed in the corresponding key number. Is there a way to replace the number with the name of the button? For example, 97 is replaced with "A"? Obviously, I mean if there's a way without having to list all the keys and put the "if" statement for everyone.
EDIT2:
It seems like the script posted, the def on_resize (self, width, height) part does not like it very much. Let me explain, if for itself the function works correctly. The problem is that if I insert it, the labels, once pressed F3, do not appear. I tried to test it using print in several places and it seems that the only instruction that is not executed is self.spritesInfo [spriteInfo] .draw ()

Python pygame not responding. Sierpinski triangle and problems with randint

The first problem that im getting is with my random numbers. every other time i try and run the program i get an error with a random number. The program worked and would make a sierpinski triangle every other time until i tried to add color into the equation now the display box pops up then everything freezes
import sys, pygame, random, math, array
####initializes pygame
pygame.init()
#####deffining all my functions
def verticiePos(verticies):
for i in range(2):
screen.set_at(verticies[i], (0,0,255))
def randV(verticies):
v = random.choice(verticies)
return v
def Show(delay):
pygame.display.flip()
pygame.time.delay(delay)
def randPoint(h,w):
yRand = random.randint(0,h-1)
#maxX = ((w - yRand) * 2)
xRand = random.randint(0, w-1)
return (xRand, yRand)
def mainFunc():
verticiePos(verticies)
randPoint(h,w)
def colors(point, maxRed, maxBlue, maxGreen, bv, gv):
howRed = (math.sqrt(point[0]**2 + point[1]**2) / maxRed) * 255
howRed = int(howRed)
howGreen = ((math.sqrt((point[0] - gv[0])**2 + (point[1] - gv[1])**2)) / maxGreen) * 255
howGreen = int(howGreen)
howBlue = ((math.sqrt((point[0] - bv[0])**2 + (point[1] - bv[1])**2)) / maxBlue) * 255
howBlue = int(howBlue)
return (howRed, howGreen, howBlue)
#####global variables
xRand = 0
yRand = 0
howRed = 0
howBlue = 0
howGreen = 0
#####Let the user choose the size of the display and setting screne
w = input("What do you want the width of the dcreen to be: ")
w = int(w)
h = input("What do you want the height of the dcreen to be: ")
h = int(h)
size = [w,h]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Project 1, Spierpinski triangle")
######setting up my verticies and all the functions i made
verticies = [(1,h - 1), (int(w/2), 1), (w-1,h-1)]
gv = verticies[1]
bv = verticies[2]
lengthOne = w
lengthTwo = math.sqrt(((w/2)**2) + (h**2))
if lengthOne >= lengthTwo:
maxRed = lengthOne
maxBlue = lengthOne
else:
maxRed = lengthTwo
maxBlue = lengthTwo
maxGreen = lengthTwo
############################################
mainFunc()
point = [yRand,xRand]
iteration = 0
delay = 2
#######the main loop thats plots points
for i in range(10000):
v = randV(verticies)
#colors(point, maxRed, maxBlue, maxGreen, bv, gv)
point = (int((point[0] + v[0])/2), int((point[1] + v[1])/2))
howRed = (math.sqrt(point[0]**2 + point[1]**2) / maxRed) * 200
howRed = int(howRed)
howGreen = ((math.sqrt((point[0] - gv[0])**2 + (point[1] - gv[1])**2)) / maxGreen) * 200
howGreen = int(howGreen)
howBlue = ((math.sqrt((point[0] - bv[0])**2 + (point[1] - bv[1])**2)) / maxBlue) * 200
howBlue = int(howBlue)
screen.set_at(point,(howRed,howGreen,howBlue))
Show(delay)
iteration = iteration + 1
#####the loop went really fast and was hard to see it coming into shape so i added this
if iteration > 2000:
delay = 0
#howRed,howGreen,howBlue
This is an updated version of the code that works i just need to clean it up now
Problem with random:
You use random.randint(yRand, maxX) in randPoint() and sometimes yRand > maxX
but random.randint(a, b) require a <= b
http://docs.python.org/2/library/random.html#random.randint
Problem with freeze ???
I have not problem with freeze but you have loop for i in range(50000): and it takes 1 minute to finish. At first run I thought that program freeze.
You have no event loop to get keyboard event and stop program with ESC.
Function color() always return (0,0,0) - it is black - so I don't see Sierpinski triangle.
#EDIT:
Sierpinski Triangle with recursion
import pygame
import math
class Sierpinski():
def __init__(self):
h = w = int(input("Triangle size: "))
level = int(input("Recursion level: "))
margin = 50 # add to size to make margin around triangle
# initializes pygame and setting screne
pygame.init()
self.screen = pygame.display.set_mode( (w + margin*2, h + margin*2) ) # self. - to make accessible in all function
pygame.display.set_caption("Sierpinski Triangle - Recursion")
# offset to move triangle to middle of window
const_height = math.sqrt(3)/2 # h = a * sqrt(3)/2 = a * const_height
invert_const_height = 1 - const_height
offset = int(h * invert_const_height / 2) # to move triange up - to middle
# main vertices A, B, C
a = (margin, h + margin - offset)
b = (w + margin, h + margin - offset)
c = (w/2 + margin, int(h * invert_const_height) + margin - offset)
self.screen.set_at(a, (255,255,255))
self.screen.set_at(b, (255,255,255))
self.screen.set_at(c, (255,255,255))
# recursion
self.drawTriangle(a, b, c, level)
# main loop (in game)
clock = pygame.time.Clock()
running = True
while running:
# keyboard & mouse event
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# move objects - nothing to do here
# draw object & redraw on screen
pygame.display.set_caption("Sierpinski Triangle - Recursion [FPS: %f]" % (clock.get_fps()))
pygame.display.update()
# frametime
clock.tick(25) # max 25 Frames Per Second
# end program
pygame.quit()
#-------------------------------------------------------
def drawTriangle(self, a, b, c, level):
if level == 0:
return
ab = self.middlePoint(a, b)
ac = self.middlePoint(a, c)
bc = self.middlePoint(b, c)
self.screen.set_at(ab, (255,255,255))
self.screen.set_at(bc, (255,255,255))
self.screen.set_at(ac, (255,255,255))
self.drawTriangle(a, ab, ac, level-1)
self.drawTriangle(b, ab, bc, level-1)
self.drawTriangle(c, bc, ac, level-1)
#-------------------------------------------------------
def middlePoint(self, a, b):
x = (a[0] + b[0])/2
y = (a[1] + b[1])/2
return (x,y)
#----------------------------------------------------------------------
if __name__ == '__main__':
Sierpinski()

Categories