Got this Arkanoid clone code from internet however even after installing pygame binary still doesn' t want to work ("ImportError: No module named 'Models'"). I am using Spyder Python 3.5 and i cloned all repo from there https://github.com/Killavus/PyGame-Arkanoid
import pygame
import sys
import math
import random
from pygame.locals import *
import GameModule
from GameModule.Models import *
from GameModule.Constants import *
class Game:
def playSound( self, fileName ):
sound = pygame.mixer.Sound(fileName)
sound.play()
def __init__(self):
pygame.init()
pygame.mixer.init(11025)
self.actualState = states["START"]
self.display = pygame.display.set_mode( gfx["screen"] )
pygame.display.set_caption( "Arkanoid v" + version )
# 4 basic objects, which define the game
## Painter - drawing actual situation on screen
## Mapper - loading the map
## Status - holding stance of the game: points, lifes, actual powerups etc
## Objects - holding actual game's objects: balls, bricks, pad etc
self.objects = GameModule.Objects()
self.mapper = GameModule.Mapper( self.objects )
self.status = Status()
self.painter = GameModule.Painter( self.display, self.objects, self.status )
self.lastState = None
self.fps = pygame.time.Clock()
self.newLevel()
def loop(self):
self.fps.tick( gfx["framerate"] )
for event in pygame.event.get():
self.handleGlobalEvents( event )
self.handleEvents( event )
self.handleKeyboard()
self.updateState()
if self.actualState != states["GAMEOVER"]:
self.painter.draw()
else:
self.display.fill( (0,0,0) )
bigFont = pygame.font.SysFont( "sans-serif", 32 )
gameOver = bigFont.render( "GAME OVER!", True, (255,255,255) )
smallFont = pygame.font.SysFont( "sans-serif", 18 )
points = smallFont.render( "Punktow: " + str(self.status.points), True, (255,255,255) )
self.display.blit( gameOver, (gfx["screen"][0]/2 - gameOver.get_size()[0]/2, gfx["screen"][1]/2 - gameOver.get_size()[1]/2) )
self.display.blit( points, (gfx["screen"][0]/2 - points.get_size()[0]/2, gfx["screen"][1]/2 - gameOver.get_size()[1]/2 - 40) )
pygame.display.update()
def handleEvents( self, event ):
if self.actualState != states["PAUSE"]:
if event.type == KEYDOWN:
if event.key == K_p:
self.lastState = self.actualState
self.actualState = states["PAUSE"]
self.painter.paused = True
else:
if event.type == KEYDOWN:
if event.key == K_p:
self.actualState = self.lastState
self.painter.paused = False
if self.actualState == states["START"]:
if event.type == KEYDOWN:
if event.key == K_SPACE:
self.actualState = states["PROGRESS"]
(self.objects.balls())[0].speedChange( int( math.copysign( 5., float(self.objects.pad().lastMove) ) ), -5 )
def handleGlobalEvents( self, event ):
if event.type == QUIT:
sys.exit()
def handleKeyboard(self):
pressed = pygame.key.get_pressed()
if self.actualState == states["PROGRESS"] or self.actualState == states["START"]:
if pressed[K_LEFT]:
if self.objects.pad().move(-10) and self.actualState == states["START"]:
(self.objects.balls())[0].move(-10,0)
if pressed[K_RIGHT]:
if self.objects.pad().move(10) and self.actualState == states["START"]:
(self.objects.balls())[0].move(10,0)
def updateState(self):
if self.actualState == states["PAUSE"]:
return
if self.actualState == states["PROGRESS"]:
self.objects.updatePowerups()
for ball in self.objects.balls():
speed = ball.speed()
ball.move( speed[0], speed[1] )
if ball.collideWithWall():
pos = ball.pos()
if pos[0] == 0 or pos[0] >= gfx["screen"][0] - ball.image.get_size()[0] - 1:
ball.xInvert()
if pos[1] == 0:
ball.yInvert()
if pos[1] >= gfx["screen"][1] - ball.image.get_size()[1] - 1:
self.status.lives -= 1
self.actualState = states["START"]
self.playSound( "Resources/snd/chord.wav" )
while len(self.objects.balls()) != 1:
self.objects.removeBall((self.objects.balls())[0])
for powerup in self.objects.powerups():
self.objects.deletePowerup(powerup)
self.objects.balls()[0].reset()
self.objects.pad().reset()
for obj in self.objects.grid():
if ball.collision(obj):
self.status.points += 100
if obj.realx <= ball.position[0] and obj.realx + gfx["grid"][0] >= ball.position[0]:
ball.yInvert()
if obj.realy <= ball.position[1] and obj.realy + gfx["grid"][1] >= ball.position[1]:
ball.xInvert()
self.handleBrickCollision(obj)
if ball.collision(self.objects.pad()):
ball.yInvert()
if self.objects.pad().position[1] <= ball.position[1] and self.objects.pad().position[1] + gfx["grid"][1] >= ball.position[1]:
ball.xInvert()
for powerup in self.objects.powerups():
pad = self.objects.pad()
if powerup.collision(pad):
self.objects.deletePowerup(powerup)
self.generatePowerup()
if powerup.y == gfx["screen"][1] - 1 - powerup.image.get_size()[1]:
self.objects.deletePowerup(powerup)
if self.status.lives == 0:
self.actualState = states["GAMEOVER"]
if self.objects.grid() == []:
self.status.level += 1
if len(levels) == self.status.level:
self.actualStatus = states["GAMEOVER"]
else:
self.newLevel()
for modifier in self.status.modifiers:
modifier[1] -= 1
if modifier[1] == 0:
if modifier[0] == "big_pad":
self.objects.pad().setWidth(3)
del modifier
def generatePowerup(self):
r = random.randint(1,3)
# 3 possible powerups:
# 1 - +1 life
# 2 - for 30 sec the pad is larger
# 3 - additional ball
print (r)
if r == 1:
self.status.lives += 1
elif r == 2:
self.status.modifiers.append( [ "big_pad", gfx["framerate"] * 30 ] )
self.objects.pad().setWidth(5)
elif r == 3:
ball = Ball()
ball.position[0] = self.objects.pad().position[0] + (gfx["grid"][0]*self.objects.pad().gridWidth/2)
ball.speedChange( int( math.copysign( 5., float(self.objects.pad().lastMove) ) ), -5 )
self.objects.addBall(ball)
def handleBrickCollision(self,obj):
brickType = obj.getType()
if brickType == "simple":
self.objects.setGrid( obj.x, obj.y, None )
rand = random.randint( 0, 9 )
if rand == 9: # 1/10 chance for powerup
self.objects.spawnPowerup( obj.x, obj.y )
elif brickType == "solid":
self.objects.setGrid( obj.x, obj.y, SimpleBrick(obj.x,obj.y) )
elif brickType == "ghost":
newType = random.randint( 0, 1 )
if newType == 0:
self.objects.setGrid( obj.x, obj.y, SimpleBrick(obj.x,obj.y) )
elif newType == 1:
self.objects.setGrid( obj.x, obj.y, SolidBrick(obj.x,obj.y) )
self.playSound( "Resources/snd/ding.wav" )
def newLevel(self):
self.playSound( "Resources/snd/tada.wav" )
self.mapper.load( self.status.level )
self.objects.pad().reset()
while len(self.objects.balls()) != 1:
self.objects.removeBall((self.objects.balls())[0])
self.objects.balls()[0].reset()
self.actualState = states["START"]
class Status:
def __init__(self):
self.level = 0
self.points = 0
self.lives = startState["lives"]
self.modifiers = []
game = Game()
while True:
game.loop()
Related
Please help me, i cannot understand why X_synthetic_df returns hundreds of rows with 0 values. All of the rows have normal values fine until row 1745. From that row, all the other row values contain nothing but zeros
def nearest_neighbors(nominal_columns, numeric_columns, df, row, k):
def distance(row1, row2):
distance = 0
for col in nominal_columns:
if row1[col] != row2[col]:
distance += 1
for col in numeric_columns:
distance += (row1[col] - row2[col])**2
return distance**0.5
distances = []
for i in range(len(df)):
r = df.iloc[i]
if r.equals(row):
continue
d = distance(row, r)
if(d!=0):
distances.append((d, i))
distances.sort()
nearest = [i for d, i in distances[:k]]
return nearest
def smotenc(X, y, nominal_cols, numeric_cols, k=5, seed=None):
minority_class = y[y==1]
majority_class = y[y==0]
minority_samples = X[y == 1]
minority_target = y[y == 1]
n_synthetic_samples = len(majority_class)-len(minority_class)
synthetic_samples = np.zeros((n_synthetic_samples, X.shape[1]))
if seed is not None:
np.random.seed(seed)
for i in range(len(minority_samples)):
nn = nearest_neighbors(nominal_cols, numeric_cols, minority_samples, minority_samples.iloc[i], k=k)
for j in range(min(k, n_synthetic_samples - i*k)):
nn_idx = int(np.random.choice(a=nn))
diff = minority_samples.iloc[(nn_idx)] - minority_samples.iloc[i]
print(diff)
if (diff == 0).all():
continue
synthetic_sample = minority_samples.iloc[i] + np.random.rand() * diff
synthetic_samples[(i*k)+j, :] = synthetic_sample
X_resampled = pd.concat([X[y == 1], pd.DataFrame(synthetic_samples,columns=X.columns)], axis=0)
y_resampled = np.concatenate((y[y == 1], [1] * n_synthetic_samples))
return X_resampled, y_resampled
minority_features = df_nominal.columns.get_indexer(df_nominal.columns)
synthetic = smotenc(check_x.head(3000),check_y.head(3000),nominal_cols,numeric_cols,seed = None)
X_synthetic_df = synthetic[0]
X_synthetic_df = pd.DataFrame(X_synthetic_df,columns = X.columns)
I was a dataframe with n synthetic samples, where n is the difference between the majority samples and minority class samples
My program uses the minimax-algorithm to choose the most otimal move against the human player in tic-tac-toe. (this is working)
After that I tried to implement the alpha-beta-pruning to optimize the time the algorithm needs in order to get the optimal move. (this doesnt work)
I know why the Error is raised, but I dont get why the Error is raised by 'alpha' and 'beta' and not by 'board' or 'minX' or 'minY' too.
I think the Variables I declared should all be global variables, should they?
Error:
UnboundLocalError: local Variable 'beta' referenced before assignment
#Global Variables
values = [0,1,2]
minX = 0
minY = 0
alpha = -999
beta = 999
global alpha
global beta
board = [["-" for x in range(3)] for y in range(3)]
#ausgabe
def ausgabe():
for zeile in range(3):
for spalte in range(3):
print("|"+str(board[zeile][spalte]),end="")
print("|")
#auswertung
#liefert 0, wenn O gewonnen hat
#liefert 2, wenn X gewonnen hat
#liefert 1, wenn es unentschieden ausgeht
#liefert -1 wenn noch nicht klar
def auswertung():
for i in ("X", "O"):
for x in range(3):
if board[x][0] == i and board[x][1] == i and board[x][2] == i:
return i
for y in range(3):
if board[0][y] == i and board[1][y] == i and board[2][y] == i:
return i
if board[0][0] == i and board[1][1] == i and board[2][2] == i:
return i
if board[0][2] == i and board[1][1] == i and board[2][0] == i:
return i
for zeile in range(3):
for spalte in range(3):
if board[zeile][spalte] == "-":
return -1
return 1
#max
def max():
temp = auswertung()
if temp != -1:
if temp == "X":
return 2
elif temp == "O":
return 0
else:
return temp
maximalwert = -999
for x in range(3):
for y in range(3):
if board[x][y] == "-":
board[x][y] = "X"
temp = alpha
alpha = beta
beta = temp
if alpha < beta:
break
wert = min()
board[x][y] = "-"
if wert > maximalwert:
maximalwert = wert
return maximalwert
#min
def min():
temp = auswertung()
if temp != -1:
if temp == "X":
return 2
elif temp == "O":
return 0
else:
return temp
minimalwert = 999
for x in range(3):
for y in range(3):
if board[x][y] == "-":
board[x][y] = "O"
temp = beta
beta = alpha
alpha = temp
if alpha > beta:
break
wert = max()
board[x][y] = "-"
if wert < minimalwert:
minimalwert = wert
return minimalwert
#wo befindet sich das min
def minWo():
temp = auswertung()
if temp != -1:
if temp == "X":
return 2
elif temp == "O":
return 0
else:
return temp
global minX
global minY
minimalwert = 999
for x in range(3):
for y in range(3):
if board[x][y] == "-":
board[x][y] = "O"
temp = beta
beta = alpha
alpha = temp
if alpha > beta:
break
wert = max()
board[x][y] = "-"
if wert < minimalwert:
minX = x
minY = y
minimalwert = wert
return minimalwert
def user_input():
while True:
try:
number1 = int(input("number1: "))
number2 = int(input("number2: "))
if number1 in values and number2 in values:
if board[number1][number2] == "-":
return number1, number2
else:
print("Invalid Input!\ttry again")
except ValueError:
print("Invalid Input!\ttry again")
def game_still_going():
winner = auswertung()
if winner == "X" or winner == "O":
print("Player "+winner+" won the game")
return False
elif winner == 1:
print("It's a draw")
return False
return True
def play_game():
while game_still_going():
number1,number2 = user_input()
board[number1][number2] = "X"
minWo()
board[minX][minY] = "O"
ausgabe()
play_game()
You should set alpha respective beta to -999 and 999 instead of maximalwert, that should work. Look at the pseudo code for minimax.
I am using a Pico as part of my dissertation along with an Arduino Due for a low cost fully autonomous UAV.
Anyway to the point, the code was working before I added the GPS part but now even if I take it out the ultrasonics won't work correctly. only shows the left sensor and doesn't continue on to the GPS.
I was also trying to use the multithreader with no joy :(
Any help or suggestions would be great.
Its a bit messy I know not quite got round to polishing it.
from machine import Pin
import utime, _thread, machine
import os
from rp2 import PIO, StateMachine, asm_pio
#print sys info
print(os.uname())
led_onboard = machine.Pin(25, machine.Pin.OUT)
led_onboard.value(0) # onboard LED OFF for 0.5 sec
utime.sleep(0.5)
led_onboard.value(1)
uart = machine.UART(0, baudrate=9600)
ser = machine.UART(1, baudrate=9600)
print(uart)
print(ser)
baton = _thread.allocate_lock()
rcvChar = b""
trigger = Pin(3, Pin.OUT) #left
echo = Pin(2, Pin.IN)
trigger2 = Pin(6, Pin.OUT) #right
echo2 = Pin(7, Pin.IN)
trigger4 = Pin(9, Pin.OUT) #backward
echo4 = Pin(8, Pin.IN)
def decode(coord):
#Converts DDDMM.MMMMM > DD deg MM.MMMMM min
x = coord.split(".")
head = x[0]
tail = x[1]
deg = head[0:-2]
min = head[-2:]
return deg + " deg " + min + "." + tail + " min"
def ultraleft():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
Ldistance = (timepassed * 0.0343) / 2
utime.sleep(0.1)
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
Ldistance2 = (timepassed * 0.0343) / 2
newLdist = (Ldistance + Ldistance2) / 2
if newLdist > 120:
newLdist = 120
elif newLdist <= 100:
print("Distance Left less than 100")
return True
print("The distance Left from object is ",newLdist,"cm")
def ultraright():
trigger2.low()
utime.sleep_us(2)
trigger2.high()
utime.sleep_us(5)
trigger2.low()
while echo2.value() == 0:
signaloff2 = utime.ticks_us()
while echo2.value() == 1:
signalon2 = utime.ticks_us()
timepassed2 = signalon2 - signaloff2
Rdistance = (timepassed2 * 0.0343) / 2
utime.sleep(0.1)
trigger2.low()
utime.sleep_us(2)
trigger2.high()
utime.sleep_us(5)
trigger2.low()
while echo2.value() == 0:
signaloff2 = utime.ticks_us()
while echo2.value() == 1:
signalon2 = utime.ticks_us()
timepassed2 = signalon2 - signaloff2
Rdistance2 = (timepassed2 * 0.0343) / 2
newRdist = (Rdistance + Rdistance2) / 2
if newRdist > 120:
newRdist = 120
elif newRdist <= 100:
print("Distance Right less than 100")
return True
print("The distance Right from object is ",newRdist,"cm")
def ultradwn():
trigger4.low()
utime.sleep_us(2)
trigger4.high()
utime.sleep_us(5)
trigger4.low()
while echo4.value() == 0:
signaloff4 = utime.ticks_us()
while echo4.value() == 1:
signalon4 = utime.ticks_us()
timepassed4 = signalon4 - signaloff4
Ddistance = (timepassed4 * 0.0343) / 2
utime.sleep(0.1)
trigger4.low()
utime.sleep_us(2)
trigger4.high()
utime.sleep_us(5)
trigger4.low()
while echo4.value() == 0:
signaloff4 = utime.ticks_us()
while echo4.value() == 1:
signalon4 = utime.ticks_us()
timepassed4 = signalon4 - signaloff4
Ddistance2 = (timepassed4 * 0.0343) / 2
newDdist = (Ddistance + Ddistance2) / 2
if newDdist > 120:
newDdist = 120
elif newDdist >20 :
print("Distance Down is greater than 20")
x = 1
#uart.write("D20")
#uart.write("\n")
#print("Sent TO Height")
return True
elif newDdist <12 :
print("Distance Down is less than 12")
x = 2
#uart.write("D12")
#uart.write("\n")
#print("Sent Landed")
return True
print("The distance Down from object is ",newDdist,"cm")
def gps():
while True:
#baton.acquire()
rcvChar = ser.readline()
gps_data =rcvChar.decode("ASCII")
data = gps_data
if (data[0:6] == "$GPRMC"):
sdata = data.split(",")
if (sdata[2] == 'V'):
print("no satellite data available")
print ("---Parsing GPRMC---")
time = sdata[1][0:2] + ":" + sdata[1][2:4] + ":" + sdata[1][4:6]
lat = decode(sdata[3]) #latitude
dirLat = sdata[4] #latitude direction N/S
lon = decode(sdata[5]) #longitute
dirLon = sdata[6] #longitude direction E/W
speed = sdata[7] #Speed in knots
trCourse = sdata[8] #True course
date = sdata[9][0:2] + "/" + sdata[9][2:4] + "/" + sdata[9][4:6]#date
print ("time : %s, latitude : %s(%s), longitude : %s(%s), speed : %s, True Course : %s, Date : %s" % (time,lat,dirLat,lon,dirLon,speed,trCourse,date))
#baton.acquire()
#_thread.start_new_thread(gps(), ())
while True:
x = 0
#baton.acquire()
ultraleft()
utime.sleep(0.1)
ultraright()
utime.sleep(0.1)
ultradwn()
utime.sleep(0.1)
if ultraleft():
uart.write("LO")
uart.write("\n")
print("Sent Left")
utime.sleep(1)
if ultraright():
uart.write("RO")
uart.write("\n")
print("Sent Right")
uart.sendbreak()
utime.sleep(1)
if ultradwn():
if x == 1:
uart.write("D20")
uart.write("\n")
print("Sent TO Height")
utime.sleep(1)
if x == 2:
uart.write("D12")
uart.write("\n")
print("Sent Landed")
utime.sleep(1)
utime.sleep(1)
gps()
#baton.release()
class getPageObj:
#staticmethod
def getIDByLabel(driver, form_type, label_name):
#driver = webdriver.Chrome(executable_path="D:\\chromedriver.exe")
if label_name.find("[") == -1:
xpath_exp = "//label[text()='"+label_name+"'][1]"
else:
label_sub_str = label_name[:label_name.find("[")]
label_indx_str = label_name[label_name.find("["):label_name.find("]") + 1]
xpath_exp = "//label[text()='" + label_sub_str + "']"+label_indx_str
if len(driver.find_elements_by_xpath(xpath_exp)) > 0:
if form_type == "Form":
id=getPageObj()
attr_id = id.getAttrValueByXPath(driver, xpath_exp, "for")
return attr_id
else:
id=getPageObj()
attr_id = id.getAttrValueByXPath(driver, xpath_exp, "for")
return attr_id
I'm studding tensorflow and I wrote some code but it does not work good.
the data was downloaded from uci:http://archive.ics.uci.edu/ml/datasets/Bank+Marketing
I want to find the client who will subscribe a term deposit,but the result matched is 0.
I use 3 layers neural network and sigmod for output.
My code is like this,please help me.
hidden_layer1 = 200
hidden_layer2 = 200
x = tf.placeholder(tf.float32,[None,16])
y = tf.placeholder(tf.float32,[None,1])
Weights_L1 = tf.Variable(tf.random_normal([16,hidden_layer1]))
biases_L1 = tf.Variable(tf.random_normal([1,hidden_layer1]))
Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
L1=tf.nn.relu(Wx_plus_b_L1)
Weights_L2 = tf.Variable( tf.random_normal([hidden_layer1,1]))
biases_L2 = tf.Variable( tf.random_normal([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2
pred = tf.nn.sigmoid(Wx_plus_b_L2)
loss = tf.reduce_mean(tf.square(y-pred))
learning_rate=0.05
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
pred_correct = tf.equal(y,pred)
accuracy = tf.reduce_mean(tf.cast(pred_correct,tf.float32))
batch_num = 0
with tf.Session() as ss:
ss.run(tf.global_variables_initializer())
for step in range(500):
ss.run(train_step,feed_dict={x:bank_train_x,y:bank_train_y})
if step%100==0:
batch_num = batch_num +1
acc1 = ss.run(accuracy,feed_dict={x:bank_train_x,y:bank_train_y})
print("train acc"+ str(step) + ", " + str(acc1) +" , batch_num:" + str(batch_num))
#print(ss.run(learning_rate,feed_dict={global_:step}))
p = ss.run(pred,feed_dict={x:bank_train_x,y:bank_train_y})
acc2 = ss.run(accuracy,feed_dict={x:bank_test_x,y:bank_test_y})
print("test acc" + str(acc2))
def calc(pred,y):
l = y.shape[0]
a = 0
b=0
c=0
d=0
for i in range(l):
if (p[i] >0.5 and y[i] == 0):
a = a +1
elif (p[i] >0.5 and y[i] == 1):
b = b+1
elif (p[i] <0.5 and y[i] == 0):
c = c+1
elif (p[i] <0.5 and y[i] == 1):
d = d +1
print(a,b,c,d)
calc(p,bank_train_y)
#the result is 169 0 34959 4629