Issue while using a timer function in a threading context - python

While working on a game for my final project in a class I’m taking I was trying to figure out how to use a timer but still be able to interact with other running code, in my research I came across threading and it’s worked so far, but the issue is that when it comes to practice, the timer doesn’t work but it rather rapidly repeats itself and I don’t know how to slow it down like I want. I’ve tried swapping the interval number for anything else but it doesn’t matter what it is, it remains to do the same thing.
-also I understand the code is messy, I’m a student and I’m still learning. I’m sure there are much better ways to do a lot of the things I have done. Also this is my first question on Stack overflow so I hope I’m doing this right
Its on lines 129 & 130
timer = threading.Timer(1, clickers)
timer.start
import turtle as trtl
import threading
import time
wn = trtl.Screen()
wn.bgpic("clouds.png")
font_setup = ("Arial", 15, "normal")
font_setup2 = ("Arial", 20, "bold")
sun_img = "sun.gif"
wn.addshape("sun.gif")
sun = trtl.Turtle(shape = sun_img)
sun.penup()
sun.goto(0, 175)
clkr_img = "rocketship.gif"
wn.addshape("rocketship.gif")
clkr = trtl.Turtle(shape = clkr_img)
clkr.penup()
clkr.left(90)
clkr.goto(0,-110)
moneya = trtl.Turtle()
moneya.hideturtle()
moneya.penup()
moneya.goto(-180, -180)
money = 0
upg1price = trtl.Turtle()
upg1price.hideturtle()
upg1price.penup()
upg1price.goto(63,-20)
csup = trtl.Turtle()
csup.hideturtle()
csup.penup()
csup.goto(63,-50)
broke = trtl.Turtle()
broke.hideturtle()
shoptf = 0
broke.penup()
broke.goto(-170,-30)
broke.pencolor("red")
shop_img = "cart.gif"
wn.addshape("cart.gif")
shop = trtl.Turtle(shape = shop_img)
shop.shapesize(0.5)
shop.penup()
shop.goto(150,150)
back_img = "backk.gif"
wn.addshape("backk.gif")
back = trtl.Turtle(shape = back_img)
back.penup()
back.hideturtle()
back.goto(-110,135)
ugrd_img = "upgrade1.gif"
wn.addshape("upgrade1.gif")
ugrd = trtl.Turtle(shape = ugrd_img)
ugrd.penup()
ugrd.goto(0,-10)
ugrd.hideturtle()
cs_img = "clicksla.gif"
wn.addshape("clicksla.gif")
cs = trtl.Turtle(shape = cs_img)
cs.penup()
cs.goto(0, -40)
cs.hideturtle()
dmg = 5
wn.addshape("rktboom.gif")
clkrdmg = 0
price = 50
price2= 75
fmvmnt = 1
def gostore(x,y):
global price
upg1price.write("$" + str(round(price)), font=font_setup)
csup.write("$" + str(round(price2)), font=font_setup)
back.showturtle()
clkr.hideturtle()
shop.hideturtle()
ugrd.showturtle()
cs.showturtle()
sun.hideturtle()
wn.bgpic("storefront.png")
percentnumb2 = 50
percentnumb = 25
def upgrade1(x,y):
global money,dmg,price,percent,fmvmnt
if (money < price):
broke.write("You cant afford!", font=font_setup2)
time.sleep(3)
broke.clear()
else:
money = money - round(price)
moneya.clear()
moneya.write("MONEY: $" + str(money), font=font_setup)
dmg = dmg + 5
fmvmnt = fmvmnt + 1
upg1price.clear()
percent = (percentnumb*price)/100
price = round(price) + percent
upg1price.write("$" + str(round(price)), font=font_setup)
clik = 0
mor = 0
timer = None
def clickers(x,y):
global money,price2,percent2,clik,clkrdmg,timer,clkr_img
if (money < price2):
broke.write("You cant afford!", font=font_setup2)
time.sleep(3)
broke.clear()
else:
money = money - round(price2)
moneya.clear()
moneya.write("MONEY: $" + str(money), font=font_setup)
clik = clik + 1
clkrdmg = clkrdmg + 5
csup.clear()
percent2 = (percentnumb2*price2)/100
price2 = round(price2) + percent2
csup.write("$" + str(round(price2)), font=font_setup)
while clik >= 1:
money = money + clkrdmg
moneya.clear()
moneya.write("MONEY: $" + str(money), font=font_setup)
clkr.forward(1)
if (abs(clkr.ycor() - sun.ycor()) < 5):
clkr.shape("rktboom.gif")
time.sleep(1)
clkr.hideturtle()
clkr.shape("rocketship.gif")
clkr.goto(0, -100)
clkr.showturtle()
timer = threading.Timer(1, clickers)
timer.start
def gainpoint(x,y):
global money,dmg,fmvmnt
money = money + dmg
moneya.clear()
moneya.write("MONEY: $" + str(money), font=font_setup)
if (abs(clkr.ycor() - sun.ycor()) < 5):
clkr.goto(0, -100)
clkr.forward(fmvmnt)
def backclick(x,y):
wn.bgpic("clouds.png")
upg1price.clear()
csup.clear()
broke.clear()
back.hideturtle()
clkr.showturtle()
shop.showturtle()
ugrd.hideturtle()
sun.showturtle()
moneya.clear()
cs.hideturtle()
clkr.onclick(gainpoint)
cs.onclick(clickers)
shop.onclick(gostore)
back.onclick(backclick)
ugrd.onclick(upgrade1)
wn.listen()
wn.mainloop()

Related

How to fix this red and blue stripe in python RBGMatrix on raspberry Pi

2 months ago i ordered 3 RBG Matrix panel + an ada fruit matrix bonnet for Raspberrypi to setup a matrix display showing my google Calendar. suddenly the display shows a big redstripe in the upper half of the display. i also cant control the brightness. if the brightness is to low nothing but the red stripe is visisible.i ordered a second copy of the bonnet hoping i incedently destroyed something while sodering or due to too high currents of my powersuply (actually 5V max 0.7A, used to be higher, 12v). at software level i tried i few different args with no difference.
here dome images
at the beginning of the project everything was fine, no stripe nothing, then suddenly
i use 1 matrix P4 matrix from adafruit and one without brand from ebay
thank you for helping me
regards Anika
currently use RGBMAtrix lib with
sudo python3 time.py --led-cols=64 --led-gpio-mapping=adafruit-hat-pwm --led-slowdown-gpio=5 --led-no-drop-privs --led-pwm-bits=1 --led-chain=2 --led-panel-type=FM6126A --led-pixel-mapper=Rotate:180
this i the python code for drive 2 matrixes in chain
#!/usr/bin/env python
# Display a runtext with double-buffering.
from samplebase import SampleBase
from rgbmatrix import graphics, RGBMatrix, RGBMatrixOptions
from datetime import datetime, timedelta
import requests, json, time, _thread
##################################################################################################
##################################################################################################
##################################################################################################
class Color():
GREEN = graphics.Color(0 , 255, 0)
BLACK = graphics.Color(0 , 0 , 0)
##################################################################################################
##################################################################################################
##################################################################################################
class Pref(SampleBase):
#TEXT_TIME_REVERSED = False
#FIRST_EVENT_DETAILS = False
INLINE_TIME = True
INLINE_TIME_COL = 6.5
BEGIN_SECOND_DETAIL = 60
MINUTE_COUNT_MAX = 60
MINUTE_BLINK_MAX = 15
NIGHT_OFF = 22
DAY_ON = 4
##################################################################################################
##################################################################################################
##################################################################################################
class MatrixCal(SampleBase):
def __init__(self, *args, **kwargs):
super(MatrixCal, self).__init__(*args, **kwargs)
#self.parser.add_argument("-t", "--text", help="The text to scroll on the RGB LED panel", default="Hello world!")
def run(self):
#make canvas and grafics
offscreen_canvas = self.matrix.CreateFrameCanvas()
secondary_canvas = self.matrix.CreateFrameCanvas()
#font
font_height = 8
font_width = 5
font = graphics.Font()
font.LoadFont("../../../fonts/5x8_custom.bdf")
global data, dt0
data = {"events":[], "annc":[], "todos":[]}
data_ttl = 1 #minute
data_error_retry = 10#mintes
#some vars
format_date_time_second = '%Y-%m-%dT%H:%M:%S'
format_time = "%H:%M"
pos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
skip_next_event = False
screen_width = offscreen_canvas.width
screen_height = offscreen_canvas.height
screen_main = screen_width
if Pref.INLINE_TIME: screen_main = screen_width - font_width*Pref.INLINE_TIME_COL
tlen = 0
f_dub_ev = False
f_gehen_ev = False
f_no_blink = False
# DEF ###################################################################################
def drawText(_x, _y, _text, _color=Color.GREEN, _font=font):
return graphics.DrawText(offscreen_canvas, _font, _x, _y,_color, _text)
def drawLine(_x, _y, _w, _h, _color):
graphics.DrawLine(offscreen_canvas, _x, _y, _w, _h, _color)
def clearArea(x, y, w, h, _color=Color.BLACK):
for j in range(0, h):
graphics.DrawLine(offscreen_canvas, x, y+j, x+w-1, y+j, _color)
def showMinuteCount(time_diff, ev):
#show minutes count
if dt_start>dt0 and (time_diff<=Pref.MINUTE_COUNT_MAX or ('description' in ev and "display_type_duration" in ev['description'])):
if sec%2==0 and time_diff<=Pref.MINUTE_BLINK_MAX and not f_no_blink :
return ""
else:
if time_diff==0:return "jetzt"
else: return "ʼn{: >2d}mʼn".format(time_diff)
elif dt_start<dt0 or ('description' in ev and "display_type_duration" in ev['description']):
time_diff = int((dt_end-dt0).seconds/60)
if time_diff<=Pref.MINUTE_COUNT_MAX:
return str(time_diff) + "mʼn"
else:
if "schlafen" in ev['summary']:
return "noch " + str(dt_end-dt0)[0:4] +"h"
return "-"+dt_end.strftime("%H:%M")
else:
return dt_start.strftime("%H:%M")
def getData(a):
#api access
deploment_id = "THATS_CONFIDENTIAL"
access_token = "THAT_TOO"
url = "https://script.google.com/macros/s/"+deploment_id+"/exec?token="+access_token
next_data_load = datetime.now();
global data
while True:
#load data from api
dt0 = datetime.now()
if(dt0 > next_data_load):
print(dt0.strftime("%H:%M:%S") + " aquiring new data. next in " + str(data_ttl)+" Minute")
try:
r = requests.get(url)
r.raise_for_status()
data = json.loads(r.text)['data']
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
data['annc'].append({"type":"warning", "text":"HTTP " + str(errh.response.status_code) + " - Es gab ein Problem beim empfangen der Daten"})
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
data['annc'].append({"type":"warning", "text":"Es gab ein Problem bei der Verbindung"})
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
data['annc'].append({"type":"warning", "text":"Zeitüberschreitung beim laden der Daten"})
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
data['annc'].append({"type":"warning", "text":"Es gab ein Problem beim laden der Daten"})
except Exception as err:
print ("OOps: Something unexpected happend",err)
finally:
next_data_load = datetime.now() + timedelta(minutes=data_ttl);
#end if
time.sleep(1)
#end while
#end def getData
#def getWeather():
#Nachmittags wird es bewölkt. 🌡 min 13°C, max 23°C, ⌀ 20°C
#########################################################################################
#start data thread
_thread.start_new_thread(getData,(99,))
#data thread
while True:
offscreen_canvas.Clear()
if len(data['todos'])>0:screen_main=64
else: screen_main = screen_width
#determine whether main screen is large enought to display events with inline time
Pref.INLINE_TIME=screen_main>64;
#current date and time
dt0 = datetime.now()
sec = int(datetime.now().strftime("%S"))
hour = int(datetime.now().strftime("%H"))
ms = int(datetime.now().strftime("%f")[:-3])
#nacht abschaltung von helligkeit
#if False and Pref.NIGHT_OFF <= hour or hour < Pref.DAY_ON: self.matrix.brightness = 10
#else:
#self.matrix.brightness = 80
#reset screen vars
screen_y = font_height-1
detail_line = not Pref.INLINE_TIME
#print max 4 independet lines
index = 0
line = 0
#when no data available dim screen and only print time
if len(data['events'])==0:
#self.matrix.brightness = 10
graphics.DrawText(offscreen_canvas, font, screen_width-( 5 *font_width), font_height-1 ,Color.GREEN, datetime.now().strftime("%H:%M"))
else:
for todo in data['todos']:
t_title = todo['title']
if index==0:
clearArea(screen_main, 0, screen_width-screen_main, 8, Color.GREEN)
graphics.DrawText(offscreen_canvas, font, screen_width-( 12 *font_width), font_height-1 ,Color.BLACK, datetime.now().strftime("%d.%m. %H:%M"))
screen_y += font_height
#runtext optimization
if len(t_title)*font_width>screen_main-16: t_title = t_title+" "+t_title
else: pos[index+4] = screen_main + font_width+2
#display todo title
tlen = drawText(pos[index+4], screen_y, t_title)
clearArea(0, 8, screen_main+8, 32)
#move line if its longer then screen
if tlen > screen_main-16:
pos[index+4] -= 1
if (tlen/2-(font_width))*-1+screen_main+8> pos[index+4]:
pos[index+4] = screen_main + font_width+12
#graphics.DrawText(secondary_canvas, font, pos[index+4], screen_y ,Color.GREEN, todo['title'])
#graphics.DrawText(offscreen_canvas, font, screen_main+2, 15 ,Color.GREEN, "-")
graphics.DrawText(offscreen_canvas, font, screen_main+2, 15 ,Color.GREEN, "-")
if len(data['todos'])>1:graphics.DrawText(offscreen_canvas, font, screen_main+2, 23 ,Color.GREEN, "-")
if len(data['todos'])>2:graphics.DrawText(offscreen_canvas, font, screen_main+2, 31 ,Color.GREEN, "-")
drawLine(screen_main, 0, screen_main, screen_height, Color.GREEN)
screen_y += font_height
t_title = ""
index +=1
if screen_y>32:break
#end for todo
if len(data['todos'])>0:
clearArea(0, screen_main, screen_width-screen_main, screen_height)
#reset screen_y
screen_y = font_height-1
index =0
for ev in data['events']:
#events params
dt_start = datetime.strptime(ev['begin'][0:18], format_date_time_second)
dt_end = datetime.strptime(ev['end'][0:18], format_date_time_second)
time_diff = int((dt_start-dt0).seconds/60)
ev_summary = ev['summary']
#skip ended events or when event is from main cal and dark blue
if dt_end<=dt0 or time_diff==0 or ev_summary.startswith('#') or ('color' in ev and ev['color'] == 9): continue
#parallel events
b0 = data['events'][index]['begin']==data['events'][index+1]['begin']
b1 = (datetime.strptime(data['events'][index]['begin'][0:18], format_date_time_second)<dt0 and datetime.strptime(data['events'][index+1]['begin'][0:18], format_date_time_second)<dt0)
if (b0 or b1) and data['events'][index]['end']==data['events'][index+1]['end']:
f_dub_ev = True
index +=1 #skip ev
continue
#event details
if f_dub_ev: ev_summary = data['events'][index-1]['summary'] + " & " + ev_summary;
#skip gehen event and attach it to next event
if ev_summary.replace(">", "")=="gehen":
f_gehen_ev = True
data['events'][index+1]['travel_start'] = ev['begin']
continue
if ev_summary.startswith("-"):f_no_blink = True
#replace control chars
if ev_summary.startswith(">"):
#minute_blink_max = 15
ev_summary = ev_summary[1:len(ev_summary)]
ev_summary = ev_summary.replace(">>", "")
ev_summary = ev_summary.replace("schlafen>", "schlafen")
if f_no_blink:ev_summary = ev_summary[1:len(ev_summary)]
#runtext optimization
if len(ev_summary)*font_width>screen_main and (line>1 and f_dub_ev): ev_summary = ev_summary+" "+ev_summary
else: pos[line] = 0
#display main
tlen = drawText(pos[line], screen_y, ev_summary)
#move line if its longer then screen
if tlen > screen_main and (detail_line or Pref.INLINE_TIME):
pos[line] -= 1
if (tlen/2-(font_width))*-1>pos[line]:
pos[line] = font_width+4
#calculate time difference
# show second detail line when time time has come
if time_diff<=Pref.BEGIN_SECOND_DETAIL or dt_start<dt0 and dt_end>dt0: detail_line=not Pref.INLINE_TIME
if Pref.INLINE_TIME:
x = screen_width-( Pref.INLINE_TIME_COL *font_width)
clearArea(x, screen_y-7, Pref.INLINE_TIME_COL*font_width, font_height)
text = showMinuteCount(time_diff, ev)
x = screen_width-( len(text) *font_width)
drawText (x, screen_y, text)
if detail_line or Pref.INLINE_TIME:
if detail_line:
detail_line = False
screen_y += font_height
text = showMinuteCount(time_diff, ev)
if 'travel_start' in ev:
if Pref.INLINE_TIME: screen_y += font_height
blink_go = 15
if data['events'][index-1]['summary']=='>>>gehen': blink_go = 60
dt_travel = datetime.strptime(ev['travel_start'][0:18], format_date_time_second)
travel_diff = int((dt_travel-dt0).seconds/60)
hz=sec%20<=9
if travel_diff<=15: hz=sec%2==0;
#elif travel_diff<15: hz=sec%4<=1;
if Pref.INLINE_TIME:text = ""
else: text = " >"+text
if travel_diff <= Pref.MINUTE_COUNT_MAX:
if hz and travel_diff<=blink_go :
#text = text
if not Pref.INLINE_TIME:text = "gehen" + text
#wechsel blinken gehen mit zeit/"jetzt"
elif not Pref.INLINE_TIME:
if travel_diff==0: text="jetzt" + text
else: text= str(travel_diff) + "mʼn" + text
#wechsel blinken gehen in zeit/jetzt gehen mit leerzeile
elif Pref.INLINE_TIME:
if travel_diff<=0 : text="jetzt gehen"
else: text= "gehen ʼn{: >2d}mʼn".format(travel_diff)
elif not Pref.INLINE_TIME:
text = dt_travel.strftime("%H:%M") + text
else:
text = "gehen "+dt_travel.strftime("%H:%M")
#draw the text to the line
tl = int(len(text))
drawText( screen_main-( tl *font_width), screen_y, text)
#end if detail_line or Pref.INLINE_TIME:
f_dub_ev = False
f_gehen_ev = False
f_no_blink = False
#incrementation & loop break conditions
index +=1
line +=1
screen_y += font_height
if screen_y>screen_height:break
#end for
#end else of events len == 0
#annc = [{"type":"warning", "text":"Es dd"}]
#runtext announcement
if len(data['annc'])>0 and False:
#clear last line
clearArea(0, screen_height-font_height, screen_width, 8)
#get text, double it for smooth runtext animation
annc_text = data['annc'][0]['text']
annc_text = annc_text+" "+annc_text
alen = len(annc_text)*font_width
pos[-1] -= 1
if (alen/2-(2*font_width))*-1>pos[-1]:
pos[-1] = 2*font_width+4
graphics.DrawText(offscreen_canvas, font, pos[-1], screen_height-1 ,Color.GREEN, annc_text)
clearArea(0, screen_height-font_height, 8, 8)
#graphics.DrawText(offscreen_canvas, font, 0, screen_height-1 ,Color.GREEN, "ⓘ")
graphics.DrawText(offscreen_canvas, font, 0, screen_height-1 ,Color.GREEN, "⚠")
#offscreen_canvas = self.matrix.SwapOnVSync(secondary_canvas)
offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas)
time.sleep(0.07)
#end while
#end def run(self)
# Main function
if __name__ == "__main__":
mcal = MatrixCal()
if (not mcal.process()):
mcal.print_help()

How to stop the sound in pgzrun (Pygame Zero) when my game ends?

the sound plays right now for eternity and I only want it to play once when the game ends. I've looked it up everywhere but I really cannot find any good and helpful solution to this problem.
I use pygame zero.
Here is my code for my game:
import pgzrun
from random import randint
'''
music
music = pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(-1)
'''
#mixer
music.play("music")
music.set_volume(0.3)
sounds.effect1.set_volume(0.2)
sounds.effect2.set_volume(0.3)
BREDD = 400
HOJD = 400
summa = 0
spelet_slut = False
rav = Actor("fox")
rav.pos = 100,100
mynt = Actor("coin")
mynt.pos = 200,200
apple = Actor("apple")
apple.pos = 300,300
def draw():
screen.fill("blue")
rav.draw()
mynt.draw()
apple.draw()
screen.draw.text("Summa: " + str(summa), color="black", topleft=(10,10))
if spelet_slut:
music.stop()
screen.fill("red")
screen.draw.text("Slutsumma: " + str(summa), topleft=(10,10), fontsize=60)
sounds.lose.play()
def placera_mynt():
mynt.x = randint(20, (BREDD - 20))
mynt.y = randint(20, (HOJD - 20))
def placera_apple():
apple.x = randint(20, (BREDD - 20))
apple.y = randint(20, (HOJD - 20))
def tiden_slut():
global spelet_slut
spelet_slut = True
def update():
global summa
if keyboard.left:
rav.x = rav.x - 4
elif keyboard.right:
rav.x = rav.x + 4
elif keyboard.up:
rav.y = rav.y - 4
elif keyboard.down:
rav.y = rav.y + 4
insamlade_mynt = rav.colliderect(mynt)
insamlade_apple = rav.colliderect(apple)
if insamlade_mynt:
summa = summa + 10
sounds.effect1.play()
placera_mynt()
elif insamlade_apple:
summa = summa + 10
sounds.effect2.play()
placera_apple()
clock.schedule(tiden_slut, 5)
placera_mynt()
placera_apple()
pgzrun.go()
instead of music.play("music") use music.play_once("music")
music.play(): Play a music track from the given file. The track will loop indefinitely.
music.play_once: Similar to play(), but the music will stop after playing through once.
try: music.stop() to stop the music
you can read more about there here:
https://pygame-zero.readthedocs.io/en/stable/builtins.html#music
Press Ctrl + Q
You must read author's GitHub for details.

Chrome T-Rex-Game Reinforcement learning showing no improvement

I would like to create an AI for the Chrome-No-Internet-Dino-Game. Therefore I adapted this Github-Repository to fit my needs. I used the following formula to calculate the new Q:
Source: https://en.wikipedia.org/wiki/Q-learning
My problem now is that even after ~ 2.000.000 iterations my game score is not increasing.
You can find the game file here: https://pastebin.com/XrwQ0suJ
QLearning.py:
import pickle
import Game_headless
import Game
import numpy as np
from collections import defaultdict
rewardAlive = 1
rewardKill = -10000
alpha = 0.2 # Learningrate
gamma = 0.9 # Discount
Q = defaultdict(lambda: [0, 0, 0]) # 0 = Jump / 1 = Duck / 2 = Do Nothing
oldState = None
oldAction = None
gameCounter = 0
gameScores = []
def paramsToState(params):
cactus1X = round(params["cactus1X"] / 10) * 10
cactus2X = round(params["cactus2X"] / 10) * 10
cactus1Height = params["cactus1Height"]
cactus2Height = params["cactus2Height"]
pteraX = round(params["pteraX"] / 10) * 10
pteraY = params["pteraY"]
playerY = round(params["playerY"] / 10) * 10
gamespeed = params["gamespeed"]
return str(cactus1X) + "_" + str(cactus2X) + "_" + str(cactus1Height) + "_" + \
str(cactus2Height) + "_" + str(pteraX) + "_" + str(pteraY) + "_" + \
str(playerY) + "_" + str(gamespeed)
def shouldEmulateKeyPress(params): # 0 = Jump / 1 = Duck / 2 = Do Nothing
global oldState
global oldAction
state = paramsToState(params)
oldState = state
estReward = Q[state]
action = estReward.index(max(estReward))
if oldAction is None:
oldAction = action
return action
# Previous action was successful
# -> Update Q
prevReward = Q[oldState]
prevReward[oldAction] = (1 - alpha) * prevReward[oldAction] + \
alpha * (rewardAlive + gamma * max(estReward))
Q[oldState] = prevReward
oldAction = action
return action
def onGameOver(score):
# Previous action was NOT successful
# -> Update Q
global oldState
global oldAction
global gameCounter
global gameScores
gameScores.append(score)
if gameCounter % 10000 == 0:
print(f"{gameCounter} : {np.mean(gameScores[-100:])}")
prevReward = Q[oldState]
prevReward[oldAction] = (1 - alpha) * prevReward[oldAction] + \
alpha * rewardKill
Q[oldState] = prevReward
oldState = None
oldAction = None
if gameCounter % 10000 == 0:
with open("Q\\" + str(gameCounter) + ".pickle", "wb") as file:
pickle.dump(dict(Q), file)
gameCounter += 1
Game_headless.main(shouldEmulateKeyPress, onGameOver)
On every frame the gameplay() function from Game_headless.py calls shouldEmulateKeyPress(). Said function then returns 0 for Jump, 1 for duck and 2 for nothing.
I tried adjusting the constants, but that didn't show any effect.
If you any questions, please don't hesitate to ask me!
Thank you in advance!
Someone on Reddit did this, did you take a look at their code? https://www.reddit.com/r/MachineLearning/comments/8iujuu/p_tfrex_ai_learns_to_play_google_chromes_dinosaur/
I was able to fix the problem, but I don't really know what the mistake was. I added a return statement at the end the gameplay function, and somehow it works now.

Stop loss and Take profit question in Quantopian

I need to set a stop loss and take profit to every trade I make in Quantopian. This is the code I have at the moment but it's not working as intended.
The order logic (to enter a short or long trade) is scheduled only once per day while the take profit or stop loss should be checked every minute.
import talib as ta
import pandas
risk_per_trade = 500
factor_tp = 2
factor_sl = 2
Bars_count = 60
def initialize(context):
context.stocks = [sid(4265), sid(5061)]
schedule_function(orderlogic,date_rules.every_day(), time_rules.market_open(hours=0, minutes=10))
def orderlogic(context, data):
hist = data.history(context.stocks,['price','high','low','close','open'], bar_count=Bars_count, frequency='1d')
for stock in context.stocks:
atr = ta.ATR(hist['high'][stock],hist['low'][stock],hist['close'][stock],timeperiod=14)
sma_20 = ta.SMA(hist['close'][stock], timeperiod=20)
stop_size = factor_sl * atr[-1]
amount_shares = round(risk_per_trade / stop_size)
open_orders = get_open_orders()
LongCondition = hist['price'][stock][-1] < sma_20[-1]
SellCondition = hist['price'][stock][-1] > sma_20[-1]
if LongCondition and stock not in open_orders and context.portfolio.positions[stock].amount ==0:
order(stock, amount_shares)
elif SellCondition and stock not in open_orders and context.portfolio.positions[stock].amount ==0:
order(stock, -1 * amount_shares)
def handle_data(context,data):
# record(leverage=context.account.leverage)
for axion in context.stocks:
current_price = data.current(axion, 'price')
position = context.portfolio.positions[axion].amount
price_position = context.portfolio.positions[axion].cost_basis
pnl = ( current_price - price_position ) * position
if position > 0 and current_price > price_position:
if pnl >= factor_tp * risk_per_trade:
order_target_percent(axion, 0)
log.info("Buy with Take Profit hit " + str(axion.symbol))
if position > 0 and current_price < price_position:
if pnl <= -risk_per_trade:
order_target_percent(axion, 0)
log.info("Buy with Stop Loss hit " + str(axion.symbol))
if position < 0 and current_price < price_position:
if -pnl >= factor_tp * risk_per_trade:
order_target_percent(axion, 0)
log.info("Sell with Take Profit hit " + str(axion.symbol))
if position < 0 and current_price > price_position:
if pnl >= risk_per_trade:
order_target_percent(axion, 0)
log.info("Sell with Stop Loss hit " + str(axion.symbol))

chatroom quiz bot: How to repeat quiz during idle time?

I am working on a quit bot in Python. Now I want to know how I can repeat the question after a certain idle time.
These are my global variables:
QUIZ_FILE = 'static/questions.txt'
QUIZ_TOTAL_LINES = 29
QUIZ_TIME_LIMIT = 40
QUIZ_IDLE_LIMIT = 3000000
QUIZ_RECURSIVE_MAX = 3000000
QUIZ_CURRENT_ANSWER = {}
QUIZ_CURRENT_HINT = {}
QUIZ_CURRENT_HINT_NEW = {}
QUIZ_CURRENT_TIME = {}
QUIZ_IDLENESS = {}
QUIZ_IDLE_ANSWER = {}
QUIZ_START = {}
QUIZ_IDLE_ANSWER_FIRSR = {}
QUIZ_NOWORD = '*'
MODE = 'M1'
PTS = 'P2'
ACC = 'A2'
Bot Time settings
import threading
HELP = u'help of command > "!quiz"'
def sectomin(time):
m = 0
s = 0
if time >= 60:
m = time / 60
if (m * 60) != 0:
s = time - (m * 60)
else:
s = 0
else:
m = 0
s = time
return str(m)+u'min. in '+str(s)+u'sec.'
def quiz_timer(groupchat, start_time):
global QUIZ_TIME_LIMIT
global QUIZ_CURRENT_TIME
time.sleep(QUIZ_TIME_LIMIT)
if QUIZ_CURRENT_TIME.has_key(groupchat) and QUIZ_CURRENT_ANSWER.has_key(groupchat) and start_time == QUIZ_CURRENT_TIME[groupchat]:
QUIZ_CURRENT_ANSWER[groupchat]
msg(groupchat, u'(!) time out! ' + sectomin(QUIZ_TIME_LIMIT) + u' passed.\nCorrect answer: ' + QUIZ_CURRENT_ANSWER[groupchat])
if QUIZ_IDLENESS.has_key(groupchat):
QUIZ_IDLENESS[groupchat] += 1
else:
QUIZ_IDLENESS[groupchat] = 1
if QUIZ_IDLENESS[groupchat] >= QUIZ_IDLE_LIMIT:
msg(groupchat, u'(!) quiz will be automatically completed for inaction! ' + str(QUIZ_IDLE_LIMIT) + ' unanswered questions.')
del QUIZ_CURRENT_ANSWER[groupchat]
quiz_list_scores(groupchat)
else:
quiz_ask_question(groupchat)
Method of asking question
def quiz_ask_question(groupchat):
global answer
global QUIZ_CURRENT_TIME
global question
global QUIZ_IDLE_ANSWER
global QUIZ_IDLE_ANSWER_FIRSR
QUIZ_IDLE_ANSWER = {groupchat:{}}
(question, answer) = quiz_new_question()
QUIZ_CURRENT_ANSWER[groupchat] = answer
QUIZ_CURRENT_HINT[groupchat] = None
QUIZ_CURRENT_HINT_NEW[groupchat] = None
QUIZ_CURRENT_TIME[groupchat] = time.time()
threading.Thread(None, quiz_timer, 'gch'+str(random.randrange(0,9999)), (groupchat, QUIZ_CURRENT_TIME[groupchat])).start()
msg(groupchat, u'(?) question: \n' + question)
I want to automatically recall the question every few seconds during sleep/idle time.
I cannot make it to work so that the bot can ask questions between QUIZ_TIME_LIMIT = 40 automatically.
Code to recall question on request
def handler_quiz_resend(type, source, body):
global question
groupchat = source[1]
if QUIZ_CURRENT_ANSWER.has_key(groupchat):
res = u'(*) current question: \n'+question
reply(type, source, res)
else:
reply(type, source, u'no quiz, '+HELP)

Categories

Resources