Multiplayer glitching in smallbasic - multiplayer

I've been working on a Multiplayer game (again) and I've got a problem with glitching.
If you Start it up and join the server on two Computers, you will notice that the ships will kind of glitch around a bit. I think this is due to the messages sent being received at irregular times and the ships getting updated before they are in the right position.
I need help figuring out the solution to it! Thanks!
http://www.mediafire.com/download/xf7ez07dxmh0hq3/Multiplayer_start.zip
Here is the code:
Server:
TextWindow.Write("Enter the Port to host on:")
Port = TextWindow.Read()
TextWindow.WriteLine(IOTCPServer.StartServer(Port))
IOTCPServer.OnClientConnect = OnClientConnect
IOTCPServer.OnMessageRecieved = OnMessageRecieved
Timer.Tick = SendClientnumbers
Timer.Interval = 1000
Sub OnClientConnect
NumClients = NumClients + 1
Clients = IOTCPServer.GetClients()
Info["Type"] = "Cc"
Info["Info"] = Clients
TextWindow.WriteLine(Info)
For i = 1 To Array.GetItemCount(Clients)
IOTCPServer.SendMessage(Info,Clients[i])
EndFor
EndSub
Sub OnMessageRecieved
For i = 1 To NumClients
IOTCPServer.SendMessage(IOTCPServer.LastMessageData,Clients[i-1])
EndFor
EndSub
Sub SendClientnumbers
For u = 1 To NumClients
Info2["T"] = "N"
Info2["UN"] = u
IOTCPServer.SendMessage(Info2,Clients[u-1])
EndFor
EndSub
Client:
GraphicsWindow.Width = 800
GraphicsWindow.Height = 600
TextWindow.Write("Enter the port: ")
Port = TextWindow.Read()
TextWindow.Write("Enter the IP: ")
ServIp = TextWindow.Read()
TextWindow.Hide()
IOTCPClient.Connect(ServIp,Port)
IOTCPClient.OnMessageRecieved = OnMessageRecieved
Ip = IOTCPClient.IP
NumOfShips = 3
For i = 1 to NumOfShips
Ship[i] = Shapes.AddImage(Program.Directory + "/Ship1.png")
Shipx[i] = GraphicsWindow.Width / 2
Shipy[i] = GraphicsWindow.Height - 200
ShipMass[i] = 5
ShipF[i] = 0
ShipRotForce[i] = 1500
ElapsedMill[i] = Clock.ElapsedMilliseconds
EndFor
GraphicsWindow.DrawImage(Program.Directory + "/Space.jpg",0,-50)
Keybind[1] = "Up"
Keybind[2] = "Down"
Keybind[3] = "Right"
Keybind[4] = "Left"
Keybind[5] = "Space"
For KeyUpNum = 1 To 4
Key[KeyUpNum] = "Up"
EndFor
'UserNum = 1
GraphicsWindow.KeyDown = OnKeyDown
GraphicsWindow.KeyUp = OnKeyUp
While UserNum = ""
Program.Delay(100)
Time = Time + 100
If Time > 5000 Then
GraphicsWindow.ShowMessage("Could not get reply from host at: "+ServIp+":"+Port,"")
Program.Delay(1000)
Program.End()
EndIf
EndWhile
While 1 = 1
Program.Delay(5)
'TextWindow.Clear()
For i = 1 To NumOfShips
TimeElapsed[i] = (Clock.ElapsedMilliseconds - ElapsedMill[i]) / 1000
ElapsedMill[i] = Clock.ElapsedMilliseconds
ShipAccel[i] = (ShipF[i]/ShipMass[i])
AngleAccel[i] = (AngleF[i]/ShipMass[i])
VelocityX[i] = VelocityX[i] + ((ShipAccel[i] * TimeElapsed[i]) * Math.Cos(Math.GetRadians(Angle[i]+90))) '<--- Find the Horizontal (X) Velocity
VelocityY[i] = VelocityY[i] + ((ShipAccel[i] * TimeElapsed[i]) * Math.Sin(Math.GetRadians(Angle[i]+90))) '<--- Find the Vertical (Y) Velocity
AngleVel[i] = AngleVel[i] + (AngleAccel[i] * TimeElapsed[i])
Shipx[i] = Shipx[i] + (VelocityX[i] * TimeElapsed[i])
Shipy[i] = Shipy[i] + (VelocityY[i] * TimeElapsed[i])
Angle[i] = Angle[i] + (AngleVel[i] * TimeElapsed[i])
Shapes.Move(Ship[i],Shipx[i],Shipy[i])
Shapes.Rotate(Ship[i],Angle[i])
EndFor
CheckKeyStrokes()
EndWhile
Sub OnKeyDown
For KeydownNum = 1 To Array.GetItemCount(Keybind)
If GraphicsWindow.LastKey = Keybind[KeydownNum] Then
Key[KeydownNum] = "Down"
EndIf
EndFor
EndSub
Sub OnKeyUp
For KeyUpNum = 1 To Array.GetItemCount(Keybind)
If GraphicsWindow.LastKey = Keybind[KeyUpNum] Then
Key[KeyUpNum] = "Up"
EndIf
EndFor
EndSub
Sub CheckKeyStrokes
If Key[3] = "Down" And AngleF[UserNum] <> ShipRotForce[UserNum] Then
AngleF[UserNum] = ShipRotForce[UserNum]
ForceChange()
EndIf
If Key[4] = "Down" And AngleF[UserNum] <> -ShipRotForce[UserNum] Then
AngleF[UserNum] = -ShipRotForce[UserNum]
ForceChange()
EndIf
If Key[3] = "Up" And Key[4] = "Up" And AngleF[UserNum] <> 0 Then
AngleF[UserNum] = 0
ForceChange()
EndIf
If Key[2] = "Down" And ShipF[UserNum] <> 1500 Then
ShipF[UserNum] = 1500
ForceChange()
EndIf
If Key[1] = "Down" And ShipF[UserNum] <> -1500 Then
ShipF[UserNum] = -1500
ForceChange()
EndIf
If Key[1] = "Up" And Key[2] = "Up" And ShipF[UserNum] <> 0 Then
ShipF[UserNum] = 0
ForceChange()
EndIf
If Key[5] = "Down" Then
TextWindow.WriteLine("Checking...")
SendServerCheck()
EndIf
EndSub
Sub ForceChange
If Angle[UserNum] > 360 Then
Angle[UserNum] = Angle[UserNum] - 360
EndIf
If Angle[UserNum] < 0 Then
Angle[UserNum] = Angle[UserNum] + 360
EndIf
Position["x"] = Math.Round(Shipx[UserNum]*10000)/10000
Position["y"] = Math.Round(Shipy[UserNum]*10000)/10000
Info["T"] = "FU" 'Type
Info["N"] = UserNum 'Num
Info["P"] = Position
Info["VX"] = Math.Round(VelocityX[UserNum]*10000)/10000
Info["VY"] = Math.Round(VelocityY[UserNum]*10000)/10000
Info["A"] = Math.Round(Angle[UserNum]*10000)/10000
Info["AV"] = Math.Round(AngleVel[UserNum]*10000)/10000
Info["F"] = Math.Round(ShipF[UserNum]*10000)/10000 'Force
Info["N"] = UserNum 'Num
Info["AF"] = Math.Round(AngleF[UserNum]*10000)/10000 ' Angle
IOTCPClient.SendMessage(Info)
EndSub
Sub OnMessageRecieved
RecInfo = IOTCPClient.LastMessageData
If RecInfo["T"] = "N" Then
UserNum = RecInfo["UN"]
EndIf
If RecInfo["N"] <> UserNum Then
If RecInfo["T"] = "FU" Then
Pos = RecInfo["P"]
Shipx[RecInfo["N"]] = Pos["x"]
Shipy[RecInfo["N"]] = Pos["y"]
VelocityX[RecInfo["N"]] = RecInfo["VX"]
VelocityY[RecInfo["N"]] = RecInfo["VY"]
Angle[RecInfo["N"]] = RecInfo["A"]
AngleVel[RecInfo["N"]] = RecInfo["AV"]
ShipF[RecInfo["N"]] = RecInfo["F"]
AngleF[RecInfo["N"]] = RecInfo["AF"]
EndIf
EndIf
If RecInfo["T"] = "CH" Then
If RecInfo["N"] = UserNum Then
TextWindow.WriteLine("Connected to Server!!!")
EndIf
EndIF
EndSub
Sub SendServerCheck
Info["T"] = "CH"
IOTCPClient.SendMessage(Info)
EndSub
Sub SendPosInfo
Position["x"] = Math.Round(Shipx[UserNum]*10000)/10000
Position["y"] = Math.Round(Shipy[UserNum]*10000)/10000
Info["T"] = "PU" 'Type
Info["N"] = UserNum 'Num
Info["P"] = Position
Info["VX"] = Math.Round(VelocityX[UserNum]*10000)/10000
Info["VY"] = Math.Round(VelocityY[UserNum]*10000)/10000
Info["A"] = Math.Round(Angle[UserNum]*10000)/10000
Info["AV"] = Math.Round(AngleVel[UserNum]*10000)/10000
IOTCPClient.SendMessage(Info)
EndSub

Related

Space Invaders Game - How can I make it so that the aliens move down for a set distance, then change direction when they drop? [duplicate]

This question already has answers here:
Is it possible to implement gradual movement of an object to given coordinates in Pygame?
(1 answer)
How to make a circle move diagonally from corner to corner in pygame
(1 answer)
How to move the object in squared path repeatedly?
(1 answer)
Closed 5 months ago.
Currently i'm making Space invaders, and I'm having trouble making the aliens move properly from to the side and down the screen. The aliens are supposed to move one direction, then once they hit the edge of the screen they're meant to go down the screen a little bit, then change direction, and repeat this until they get to the bottom of the screen where the player is. So far this is what I have as a part of my code...
for element in smallInvaders:
element.move_ip(dx,dy)
for element in smallInvaders:
if element.bottom > 100:
dy = 0
dx = 1
if element.right >= width or element.left <= 0:
dy += 0.5
dx = 0
invaderDirSwapped = True
for element in medInvaders:
element.move_ip(dx,dy)
if not invaderDirSwapped:
for element in medInvaders:
if element.right >= width or element.left <= 0:
dy += 0.5
dx = 0
invaderDirSwapped = True
for element in bigInvaders:
element.move_ip(dx,dy)
if not invaderDirSwapped:
for element in bigInvaders:
if element.right >= width or element.left <= 0 :
dy += 0.5
dx = 0
invaderDirSwapped = True
Essentially, smallInvaders, medInvaders and bigInvaders are all lists, where each object in the list is a rect object, that act as the aliens. I tried to make it so that I change the direction y value (dy) when the aliens touch the side of the screen (they're originally moving to the left as dx is -1, and dy is 0 initially), then the dy value gets put to 0, when the y value of the aliens hits a specific amount, but this doesn't seem to work, as the next time through when the aliens go from right to left, they either get stuck, or phase off the side of the screen. I understand both if statements are being executed at the same time, but i'm stuck on what to do because of it, and if there are any other solutions towards fixing the problem.
here's my full code...
import pygame
import sys
import time
import random
#initialize pygame
pygame.mixer.init()
pygame.init()
width = 800
height = 600
# set the size for the surface (screen)
screen = pygame.display.set_mode((width, height),pygame.FULLSCREEN)
width = screen.get_width()
height = screen.get_height()
print(width)
print(height)
# set the caption for the screen
pygame.display.set_caption("Space Invaders")
score = 0
def checkCollision(missles, type, score, invader_kill):
for missle in missles:
collision = missle.collidelist((type))
if collision > -1:
type.pop(collision)
invader_kill.play()
missles.remove(missle)
missle.move_ip(0,missleSpeed)
pygame.draw.rect(screen, WHITE, missle,0)
# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)
shoot_sound = pygame.mixer.Sound("Music-sfx/shoot.wav")
invader_kill = pygame.mixer.Sound("Music-sfx/invaderkilled.wav")
ship_kill = pygame.mixer.Sound("Music-sfx/explosion.wav")
clock = pygame.time.Clock()
FPS = 60
s = 25
#load and scale images
smallInvaderImg = pygame.image.load("images/smallinvader.png")
smallInvaderImg = pygame.transform.scale(smallInvaderImg,(s,s))
medInvaderImg = pygame.image.load("images/crabinvader.png")
medInvaderImg = pygame.transform.scale(medInvaderImg, (s,s))
bigInvaderImg = pygame.image.load("images/biginvader.png")
bigInvaderImg = pygame.transform.scale(bigInvaderImg, (s,s))
shipImg = pygame.image.load("images/ship.png")
shipImg = pygame.transform.scale(shipImg, (60,60))
shieldImg = pygame.image.load("images/shield.png")
shieldImg = pygame.transform.scale(shieldImg , (80,55))
smallInvaders = []
medInvaders = []
bigInvaders = []
enemiesMap = ["sssssssssss",
"mmmmmmmmmmm",
"mmmmmmmmmmm",
"bbbbbbbbbbb"]
invadertype = [smallInvaders,medInvaders,bigInvaders]
dx = -1
dy = 0
x = 240
y = 45
gap = 10
for element in enemiesMap:
for char in element:
if char == "s":
smallInvaders.append(pygame.Rect(x,y,s,s))
elif char == "m":
medInvaders.append(pygame.Rect(x,y,s,s))
elif char == "b":
bigInvaders.append(pygame.Rect(x,y,s,s))
x += s + gap
y += s + gap
x = 240
ship = pygame.Rect(width/2,525,60,60)
shield1 = pygame.Rect(40,370,80,60)
shield2 = pygame.Rect(250,370,80,60)
shield3 = pygame.Rect(460,370,80,60)
shield4 = pygame.Rect(670,370,80,60)
if ship.right == width:
ship.right = width
#missles
maxMissles = 3
missleSpeed = -6
missleWidth = 5
missleHeight = 30
enemmissleWidth = 5
enemmissleHeight = 25
missles = []
missleFired = False
lives = 3
playbutton = pygame.Rect(width/2,height/2,200,90)
playbutton.center = (width/2,height/2)
quitbutton = pygame.Rect(width/2,height/2,200,90)
quitbutton.center = (width/2,height/2+110)
playagn = pygame.Rect(width/2,height/2,235,90)
playagn.center = (width/2,height/2)
playword = pygame.font.Font("pixeltext.ttf", 35)
title = pygame.font.Font("pixeltext.ttf", 80)
quitword = pygame.font.Font("pixeltext.ttf",35)
endscreen = pygame.font.Font("pixeltext.ttf", 90)
playagaintext = pygame.font.Font("pixeltext.ttf", 35)
gameover = pygame.font.Font("pixeltext.ttf",120 )
livestext = pygame.font.Font("pixeltext.ttf",25)
enemMissleFire = False
enemmislist = []
enemymissle = (pygame.Rect(ship.centerx,y,enemmissleWidth,enemmissleHeight))
Cont = False
invaderDirSwapped = False
screenControl = 0
main = True
while main:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
main = False
for element in smallInvaders:
element.move_ip(dx,dy)
for element in smallInvaders:
if element.bottom > 100:
dy = 0
dx = 1
if element.right >= width or element.left <= 0:
dy += 0.5
dx = 0
invaderDirSwapped = True
for element in medInvaders:
element.move_ip(dx,dy)
if not invaderDirSwapped:
for element in medInvaders:
if element.right >= width or element.left <= 0:
dy += 0.5
dx = 0
invaderDirSwapped = True
for element in bigInvaders:
element.move_ip(dx,dy)
if not invaderDirSwapped:
for element in bigInvaders:
if element.right >= width or element.left <= 0 :
dy += 0.5
dx = 0
invaderDirSwapped = True
key_input = pygame.key.get_pressed()
if key_input[pygame.K_RIGHT] and ship.right < width:
ship.move_ip(4,0)
if key_input[pygame.K_LEFT] and ship.left > 0:
ship.move_ip(-4,0)
if key_input[pygame.K_SPACE] and not missleFired:
missleFired = True
enemmissleFire = True
shoot_sound.play()
missles.append(pygame.Rect(ship.centerx,ship.top,missleWidth,missleHeight))
if screenControl == 0:
screen.fill(BLACK)
texttitle = title.render("SPACE INVADERS", True, WHITE)
textrect = texttitle.get_rect()
textrect.center = (width/2, 100)
screen.blit(texttitle,textrect)
if playbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
screenControl = 1
lives = 3
pygame.draw.rect(screen,WHITE,(playbutton), 0)
if playbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE, (playbutton), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE,(quitbutton), 0)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,quitbutton,4)
textplay = playword.render("PLAY", True, BLUE)
textrect2 = textplay.get_rect()
textrect2.center = (width/2,height/2)
screen.blit(textplay,textrect2)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
if screenControl == 1:
screen.fill(BLACK)
if len(missles) > 0:
if missleFired and missles[-1].bottom < (ship.top - 120) and not key_input[pygame.K_SPACE]:
missleFired = False
if len(missles) == 0:
missleFired = False
for invader in smallInvaders:
screen.blit(smallInvaderImg, invader)
for invader in medInvaders:
screen.blit(medInvaderImg, invader)
for invader in bigInvaders:
screen.blit(bigInvaderImg, invader)
screen.blit(shipImg,ship)
screen.blit(shieldImg,shield1)
screen.blit(shieldImg,shield2)
screen.blit(shieldImg,shield3)
screen.blit(shieldImg,shield4)
allinvaders = [smallInvaders,medInvaders,bigInvaders]
randinvader = random.choice(allinvaders)
if randinvader == smallInvaders:
if len(smallInvaders) >= 1:
abc = random.choice(smallInvaders)
elif randinvader == medInvaders:
if len(medInvaders) >= 1:
abc = random.choice(medInvaders)
elif randinvader == bigInvaders:
if len(bigInvaders) >= 1:
abc = random.choice(bigInvaders)
move and draw missles
enemMissleFire = False
if not enemMissleFire:
if enemymissle.colliderect(ship):
lives -= 1
print(f"Lives: {lives}")
enemymissle.center = (abc.centerx,abc.centery)
time.sleep(0.5)
if enemymissle.top > height:
enemymissle.center = (abc.centerx,abc.centery)
if lives == 0:
ship_kill.play()
screenControl = 3
enemymissle.move_ip(0,-missleSpeed + 1)
pygame.draw.rect(screen, WHITE, enemymissle,0)
liveval = livestext.render(f"Lives: {str(lives)}", True, WHITE)
textlives = liveval.get_rect()
textlives.center = (65,20)
screen.blit(liveval,textlives)
checkCollision(missles,smallInvaders,score,invader_kill)
checkCollision(missles,medInvaders,score,invader_kill)
checkCollision(missles,bigInvaders,score,invader_kill)
if smallInvaders == [] and medInvaders == [] and bigInvaders == []:
screenControl = 2
if screenControl == 2:
screen.fill(BLACK)
if playagn.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
print("GAME START")
screenControl = 1
lives = 3
pygame.draw.rect(screen,WHITE,(playagn),0)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE, (quitbutton),0)
if playagn.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(playagn), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(quitbutton),4)
textend = endscreen.render("YOU WON!", True, WHITE)
textrect4 = textend.get_rect()
textrect4.center = (width/2, 150)
screen.blit(textend,textrect4)
textplayagn = playagaintext.render("PLAY AGAIN", True, BLUE)
textrect5 = textplayagn.get_rect()
textrect5.center = (width/2,height/2)
screen.blit(textplayagn,textrect5)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
if screenControl == 3:
screen.fill(BLACK)
textgameovr = gameover.render("GAME OVER", True, WHITE)
textrect6 = textgameovr.get_rect()
textrect6.center = (width/2,110)
screen.blit(textgameovr,textrect6)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE, (quitbutton),0)
if playagn.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
print("GAME START")
screenControl = 1
lives = 3
pygame.draw.rect(screen,WHITE,(playagn),0)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(quitbutton),4)
if playagn.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(playagn), 4)
textplayagn = playagaintext.render("PLAY AGAIN", True, BLUE)
textrect5 = textplayagn.get_rect()
textrect5.center = (width/2,height/2)
screen.blit(textplayagn,textrect5)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
pygame.display.update()

GLPK output formats

I am new to GLPK, so my apologies in advance if I'm missing something simple!
I have a largeish LP that I am feeding through GLPK to model an energy market. I'm running the following command line to GLPK to process this:
winglpk-4.65\glpk-4.65\w64\glpsol --lp problem.lp --data ExampleDataFile.dat --output results2.txt
When I open the resulting text file I can see the outputs, which all look sensible. I have one big problem: each record is split over two rows, making it very difficult to clean the file. See an extract below:
No. Row name St Activity Lower bound Upper bound Marginal
------ ------------ -- ------------- ------------- ------------- -------------
1 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1990)_
NS 0 0 = < eps
2 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1991)_
NS 0 0 = < eps
3 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1992)_
NS 0 0 = < eps
4 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1993)_
NS 0 0 = < eps
5 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1994)_
NS 0 0 = < eps
6 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1995)_
NS 0 0 = < eps
7 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1996)_
NS 0 0 = < eps
8 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1997)_
NS 0 0 = < eps
9 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1998)_
NS 0 0 = < eps
10 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1999)_
NS 0 0 = < eps
11 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2000)_
NS 0 0 = < eps
12 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2001)_
NS 0 0 = < eps
13 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2002)_
NS 0 0 = < eps
14 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2003)_
NS 0 0 = < eps
15 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2004)_
NS 0 0 = < eps
I would be very grateful of any suggestions for either:
How I can get each record in the output text file onto a single row, or
Ideas on how to clean / post-process the existing text file output.
I'm sure I'm missing something simple here, but the output is in a very unhelpful format at the moment!
Thanks!
I wrote a Python parser for the GLPK output file. It is not beautiful and not save (try-catch) but it is working (for pure simplex problems).
You can call it on output file:
outp = GLPKOutput('myoutputfile')
print(outp)
val1 = outp.getCol('mycolvar','Activity')
val2 = outp.getRow('myrowname','Upper_bound') # row names should be defined
The class is as follows:
class GLPKOutput:
def __init__(self,filename):
self.rows = {}
self.columns = {}
self.nRows = 0
self.nCols = 0
self.nNonZeros = 0
self.Status = ""
self.Objective = ""
self.rowHeaders = []
self.rowIdx = {}
self.rowWidth = []
self.Rows = []
self.hRows = {}
self.colHeaders = []
self.colIdx = {}
self.colWidth = []
self.Cols = []
self.hCols = {}
self.wcols = ['Activity','Lower_bound','Upper bound','Marginal']
self.readFile(filename)
# split columns with weird line break
def smartSplit(self,line,type,job):
ret = []
line = line.rstrip()
if type == 'ROWS':
cols = len(self.rowHeaders)
idx = self.rowWidth
else:
cols = len(self.colHeaders)
idx = self.colWidth
if job == 'full':
start = 0
for i in range(cols):
stop = start+idx[i]+1
ret.append(line[start:stop].strip())
start = stop
elif job == 'part1':
entries = line.split()
ret = entries[0:2]
elif job == 'part2':
start = 0
for i in range(cols):
stop = start+idx[i]+1
ret.append(line[start:stop].strip())
start = stop
ret = ret[2:]
# print()
# print("SMART:",job,line.strip())
# print(" TO:",ret)
return ret
def readFile(self,filename):
fp = open(filename,"r")
lines = fp.readlines()
fp.close
i = 0
pos = "HEAD"
while pos == 'HEAD' and i<len(lines):
entries = lines[i].split()
if len(entries)>0:
if entries[0] == 'Rows:':
self.nRows = int(entries[1])
elif entries[0] == 'Columns:':
self.nCols = int(entries[1])
elif entries[0] == 'Non-zeros:':
self.nNonZeros = int(entries[1])
elif entries[0] == 'Status:':
self.Status = entries[1]
elif entries[0] == 'Objective:':
self.Objective = float(entries[3]) #' '.join(entries[1:])
elif re.search('Row name',lines[i]):
lines[i] = lines[i].replace('Row name','Row_name')
lines[i] = lines[i].replace('Lower bound','Lower_bound')
lines[i] = lines[i].replace('Upper bound','Upper_bound')
entries = lines[i].split()
pos = 'ROWS'
self.rowHeaders = entries
else:
pass
i+= 1
# formatting of row width
self.rowWidth = lines[i].split()
for k in range(len(self.rowWidth)): self.rowWidth[k] = len(self.rowWidth[k])
# print("Row Widths:",self.rowWidth)
i+= 1
READY = False
FOUND = False
while pos == 'ROWS' and i<len(lines):
if re.match('^\s*[0-9]+',lines[i]): # new line
if len(lines[i].split())>2: # no linebrak
entries = self.smartSplit(lines[i],pos,'full')
READY = True
else: # line break
entries = self.smartSplit(lines[i],pos,'part1')
READY = False
FOUND = True
else:
if FOUND and not READY: # second part of line
entries += self.smartSplit(lines[i],pos,'part2')
READY = True
FOUND = False
if READY:
READY = False
FOUND = False
# print("ROW:",entries)
if re.match('[0-9]+',entries[0]): # valid line with solution data
self.Rows.append(entries)
self.hRows[entries[1]] = len(self.Rows)-1
else:
print("wrong line format ...")
print(entries)
sys.exit()
elif re.search('Column name',lines[i]):
lines[i] = lines[i].replace('Column name','Column_name')
lines[i] = lines[i].replace('Lower bound','Lower_bound')
lines[i] = lines[i].replace('Upper bound','Upper_bound')
entries = lines[i].split()
pos = 'COLS'
self.colHeaders = entries
else:
pass #print("NOTHING: ",lines[i])
i+= 1
# formatting of row width
self.colWidth = lines[i].split()
for k in range(len(self.colWidth)): self.colWidth[k] = len(self.colWidth[k])
# print("Col Widths:",self.colWidth)
i+= 1
READY = False
FOUND = False
while pos == 'COLS' and i<len(lines):
if re.match('^\s*[0-9]+',lines[i]): # new line
if len(lines[i].split())>2: # no linebreak
entries = self.smartSplit(lines[i],pos,'full')
READY = True
else: # linebreak
entries = self.smartSplit(lines[i],pos,'part1')
READY = False
FOUND = True
else:
if FOUND and not READY: # second part of line
entries += self.smartSplit(lines[i],pos,'part2')
READY = True
FOUND = False
if READY:
READY = False
FOUND = False
# print("COL:",entries)
if re.match('[0-9]+',entries[0]): # valid line with solution data
self.Cols.append(entries)
self.hCols[entries[1]] = len(self.Cols)-1
else:
print("wrong line format ...")
print(entries)
sys.exit()
elif re.search('Karush-Kuhn-Tucker',lines[i]):
pos = 'TAIL'
else:
pass #print("NOTHING: ",lines[i])
i+= 1
for i,e in enumerate(self.rowHeaders): self.rowIdx[e] = i
for i,e in enumerate(self.colHeaders): self.colIdx[e] = i
def getRow(self,name,attr):
if name in self.hRows:
if attr in self.rowIdx:
try:
val = float(self.Rows[self.hRows[name]][self.rowIdx[attr]])
except:
val = self.Rows[self.hRows[name]][self.rowIdx[attr]]
return val
else:
return -1
def getCol(self,name,attr):
if name in self.hCols:
if attr in self.colIdx:
try:
val = float(self.Cols[self.hCols[name]][self.colIdx[attr]])
except:
val = self.Cols[self.hCols[name]][self.colIdx[attr]]
return val
else:
print("key error:",name,"not known ...")
return -1
def __str__(self):
retString = '\n'+"="*80+'\nSOLUTION\n'
retString += "nRows: "+str(self.nRows)+'/'+str(len(self.Rows))+'\n'
retString += "nCols: "+str(self.nCols)+'/'+str(len(self.Cols))+'\n'
retString += "nNonZeros: "+str(self.nNonZeros)+'\n'
retString += "Status: "+str(self.Status)+'\n'
retString += "Objective: "+str(self.Objective)+'\n\n'
retString += ' '.join(self.rowHeaders)+'\n'
for r in self.Rows: retString += ' # '.join(r)+' #\n'
retString += '\n'
retString += ' '.join(self.colHeaders)+'\n'
for c in self.Cols: retString += ' # '.join(r)+' #\n'
return retString

VLSM program that ask input of the network address, number of network, and host per network

it shows this error-- forH = math.log(h,[2]) a float is required
the error said that the variable forH which is assigned for the log function, said that "a float is required"
networkAddress = raw_input('Enter network address: ')
networks = input('Enter number of networks: ')
octet = networkAddress.split('.')
host = 0
itHost = 0
for i in range(1,networks):
h = input('Enter number of hosts: ')
forH = math.log(h,[2])
if forH%1 < 0:
forH = forH + 1
host = 2**forH
else:
host = 2**forH
if host > 255:
thirdOctet = host/256
rem = host%256
fourthOctet = int(rem*256)
octet[2] = thirdOctet
octet[3] = fourthOctet
if host > 65535:
secondOctet = host/65536
rem = host%65536
thirdOctet = int(rem*256)
fourthOctet = 0
octet[1] = secondOctet
octet[2] = thirdOctet
octet[3] = fourthOctet
print 'network', octet
host +=host
elif host < 256:
if itHost > 255:
thirdOctet = octet[2] + 1
fourthOctet = 0
else:
fourthOctet = itHost
octet[3] = fourthOctet
print 'network: ', octet
elif itHost == 0:
print 'network: ', networkAddress
itHost += host

change label values when an entry value is changed

My problem at the moment is I am trying to change a label(label 16) to the first value of entry_values[0] which isn't working I have tried passing it in as a variable and many other things, after about an hour of research I couldn't find a solution.I think the main problem is that it sets the label before the code with the entry is run so that it wont change. when I set it to a textvariable it produces an empty string (I think) but when I use just text it puts in a 0 where I expect my number.
def sub_menu(root):
global subpage
subpage = Frame(root)
button5 = Button(subpage, text="Save Generation Data",
command = lambda: save_entries())
button5.grid(row = 1, column = 6, sticky = E)
button6 = Button(subpage, text="Return To Main Page",
command = lambda: switch_page("main"))
button6.grid(row = 0, column = 6, sticky = W)
juveniles_label0 = Label(subpage,text="Juveniles")
adults_label1 = Label(subpage,text="Adults")
seniles_label2 = Label(subpage,text="Seniles")
population_label3 = Label(subpage,text="Population (Thousands)")
survival_rate_label4 = Label(subpage,text="Survival Rate (Between 0 and 1)")
birth_rate_label5 = Label(subpage,text="Birth Rate")
number_of_gens_label6 = Label(subpage,text="Number of Generations")
disease_trigger_label7 = Label(subpage,text="Disease Trigger Point")
global entry0
entry0 = Entry(subpage)
global entry1
entry1 = Entry(subpage)
global entry2
entry2 = Entry(subpage)
global entry3
entry3 = Entry(subpage)
global entry4
entry4 = Entry(subpage)
global entry5
entry5 = Entry(subpage)
global entry6
entry6 = Entry(subpage)
global entry7
entry7 = Entry(subpage)
global entry8
entry8 = Entry(subpage)
juveniles_label0.grid(row = 0, column = 1)
adults_label1.grid(row = 0, column = 2)
seniles_label2.grid(row = 0, column = 3)
population_label3.grid(row = 1, column = 0)
survival_rate_label4.grid(row = 2, column = 0)
birth_rate_label5.grid(row = 3, column = 0)
number_of_gens_label6.grid(row = 3, column = 2)
disease_trigger_label7.grid(row = 4, column = 0)
entry0.grid(row = 1, column = 1)
entry1.grid(row = 1, column = 2)
entry2.grid(row = 1, column = 3)
entry3.grid(row = 2, column = 1)
entry4.grid(row = 2, column = 2)
entry5.grid(row = 2, column = 3)
entry6.grid(row = 3, column = 1)
entry7.grid(row = 3, column = 3)
entry8.grid(row = 4, column = 1)
return subpage
def save_entries(): #entry recieve point
save_page = Frame(root)
""" if e0 < 0:
make a check to check if value is < 0 dont accept and if a value is inputed or not using if type(string_name) == str """
e0 = entry0.get()
if e0 >= 0:
entry_values[0] = (e0)
e1 = entry1.get()
if e0 >= 0:
entry_values[1] = (e1)
e2 = entry2.get()
if e0 >= 0:
entry_values[2] = (e2)
e3 = entry3.get()
if e0 >= 0:
entry_values[3] = (e3)
e4 = entry4.get()
if e0 >= 0:
entry_values[4] = (e4)
e5 = entry5.get()
if e0 >= 0:
entry_values[5] = (e5)
e6 = entry6.get()
if e0 >= 0:
entry_values[6] = (e6)
e7 = entry7.get()
if e0 >= 0:
entry_values[7] = (e7)
e8 = entry8.get()
if e0 >= 0:
entry_values[8] = (e8)
print entry_values
return save_page
def display_values(root):
sub2 = Frame(root)
global entry_values
label8 = Label(sub2, text = "Juveniles")
label9 = Label(sub2, text = "Adults")
label10 = Label(sub2, text = "Seniles")
label11 = Label(sub2, text = "Population(Thousands)")
label12 = Label(sub2, text = "Survival Rate(Between 1 and 0)")
label13 = Label(sub2, text = "Birth Rate")
label14 = Label(sub2, text = "Number of Generations")
label15 = Label(sub2, text = "Disase Trigger Point")
label16 = Label(sub2, text = entry_values[0])
label17 = Label(sub2, textvariable = entry_values[1])
label18 = Label(sub2, textvariable = "")
label19 = Label(sub2, textvariable = "")
label20 = Label(sub2, textvariable = "")
label21 = Label(sub2, textvariable = "")
label22 = Label(sub2, textvariable = "")
label23 = Label(sub2, textvariable = "")
label24 = Label(sub2, textvariable = "")
button7 = Button(sub2, text="Return To Main Page",
command = lambda: switch_page("main"))
label8.grid(row = 0, column = 1)
label9.grid(row = 0, column = 2)
label10.grid(row = 0, column = 3)
label11.grid(row = 1, column = 0)
label12.grid(row = 2, column = 0)
label13.grid(row = 3, column = 0)
label14.grid(row = 3, column = 3)
label15.grid(row = 4, column = 0)
label16.grid(row = 1, column = 1)
label17.grid(row = 1, column = 2)
label18.grid(row = 1, column = 3)
label19.grid(row = 2, column = 1)
label20.grid(row = 2, column = 2)
label21.grid(row = 2, column = 3)
label22.grid(row = 3, column = 1)
label23.grid(row = 3, column = 3)
label24.grid(row = 4, column = 1)
button7.grid(row = 0, column = 0)
return sub2
In order to change the text of a label you can do:
label["text"] = textVar
or
label.config(text=textVar)
So in your above code, when the entry changes, reconfigure the label using one of the above options.

Finding whether a number has P^Q form or not?

I have recently appeared online coding Test. I was struck one question i.e
A number N is given finding the above number is P^Q(P power Q) form or not. I did the question using Brute force method (satisfying for individual number) but that result in time out. SO I need Efficient algorithm.
Input: 9
out put : yes
Input: 125
out put : yes
Input: 27
out put : yes
Constraints: 2<N<100000
if we assume non trivial cases then the constraints would be something like this:
N = <2,100000)
P>1
Q>1
This can be solved by sieves that mark all powers bigger then 1 up to N of the result. Now the question is do you need to optimize single query or many of them ? If you need just single query then you do not need the sieve table in memory, you just iterate until hit the N and then stop (so in worst case when N is not in form P^Q this would compute the whole sieve). Otherwise init such table once and then just use it. As N is small I go for the full table.
const int n=100000;
int sieve[n]={255}; // for simplicity 1 int/number but it is waste of space can use 1 bit per number instead
int powers(int x)
{
// init sieve table if not already inited
if (sieve[0]==255)
{
int i,p;
for (i=0;i<n;i++) sieve[i]=0; // clear sieve
for (p=sqrt(n);p>1;p--) // process all non trivial P
for (i=p*p;i<n;i*=p) // go through whole table
sieve[i]=p; // store P so it can be easily found later (if use 1bit/number then just set the bit instead)
}
return sieve[x];
}
first call took 0.548 ms on mine setup the others are non measurable small times
it returns the P so if P!=0 the number is in form P^Q so you can use it as bool directly, and also you can easily get Q by dividing or you can create another sieve with Q to be even more fast if you need also the P,Q
Here all found non trivial powers N<100000
4 = 2^q
8 = 2^q
9 = 3^q
16 = 2^q
25 = 5^q
27 = 3^q
32 = 2^q
36 = 6^q
49 = 7^q
64 = 2^q
81 = 3^q
100 = 10^q
121 = 11^q
125 = 5^q
128 = 2^q
144 = 12^q
169 = 13^q
196 = 14^q
216 = 6^q
225 = 15^q
243 = 3^q
256 = 2^q
289 = 17^q
324 = 18^q
343 = 7^q
361 = 19^q
400 = 20^q
441 = 21^q
484 = 22^q
512 = 2^q
529 = 23^q
576 = 24^q
625 = 5^q
676 = 26^q
729 = 3^q
784 = 28^q
841 = 29^q
900 = 30^q
961 = 31^q
1000 = 10^q
1024 = 2^q
1089 = 33^q
1156 = 34^q
1225 = 35^q
1296 = 6^q
1331 = 11^q
1369 = 37^q
1444 = 38^q
1521 = 39^q
1600 = 40^q
1681 = 41^q
1728 = 12^q
1764 = 42^q
1849 = 43^q
1936 = 44^q
2025 = 45^q
2048 = 2^q
2116 = 46^q
2187 = 3^q
2197 = 13^q
2209 = 47^q
2304 = 48^q
2401 = 7^q
2500 = 50^q
2601 = 51^q
2704 = 52^q
2744 = 14^q
2809 = 53^q
2916 = 54^q
3025 = 55^q
3125 = 5^q
3136 = 56^q
3249 = 57^q
3364 = 58^q
3375 = 15^q
3481 = 59^q
3600 = 60^q
3721 = 61^q
3844 = 62^q
3969 = 63^q
4096 = 2^q
4225 = 65^q
4356 = 66^q
4489 = 67^q
4624 = 68^q
4761 = 69^q
4900 = 70^q
4913 = 17^q
5041 = 71^q
5184 = 72^q
5329 = 73^q
5476 = 74^q
5625 = 75^q
5776 = 76^q
5832 = 18^q
5929 = 77^q
6084 = 78^q
6241 = 79^q
6400 = 80^q
6561 = 3^q
6724 = 82^q
6859 = 19^q
6889 = 83^q
7056 = 84^q
7225 = 85^q
7396 = 86^q
7569 = 87^q
7744 = 88^q
7776 = 6^q
7921 = 89^q
8000 = 20^q
8100 = 90^q
8192 = 2^q
8281 = 91^q
8464 = 92^q
8649 = 93^q
8836 = 94^q
9025 = 95^q
9216 = 96^q
9261 = 21^q
9409 = 97^q
9604 = 98^q
9801 = 99^q
10000 = 10^q
10201 = 101^q
10404 = 102^q
10609 = 103^q
10648 = 22^q
10816 = 104^q
11025 = 105^q
11236 = 106^q
11449 = 107^q
11664 = 108^q
11881 = 109^q
12100 = 110^q
12167 = 23^q
12321 = 111^q
12544 = 112^q
12769 = 113^q
12996 = 114^q
13225 = 115^q
13456 = 116^q
13689 = 117^q
13824 = 24^q
13924 = 118^q
14161 = 119^q
14400 = 120^q
14641 = 11^q
14884 = 122^q
15129 = 123^q
15376 = 124^q
15625 = 5^q
15876 = 126^q
16129 = 127^q
16384 = 2^q
16641 = 129^q
16807 = 7^q
16900 = 130^q
17161 = 131^q
17424 = 132^q
17576 = 26^q
17689 = 133^q
17956 = 134^q
18225 = 135^q
18496 = 136^q
18769 = 137^q
19044 = 138^q
19321 = 139^q
19600 = 140^q
19683 = 3^q
19881 = 141^q
20164 = 142^q
20449 = 143^q
20736 = 12^q
21025 = 145^q
21316 = 146^q
21609 = 147^q
21904 = 148^q
21952 = 28^q
22201 = 149^q
22500 = 150^q
22801 = 151^q
23104 = 152^q
23409 = 153^q
23716 = 154^q
24025 = 155^q
24336 = 156^q
24389 = 29^q
24649 = 157^q
24964 = 158^q
25281 = 159^q
25600 = 160^q
25921 = 161^q
26244 = 162^q
26569 = 163^q
26896 = 164^q
27000 = 30^q
27225 = 165^q
27556 = 166^q
27889 = 167^q
28224 = 168^q
28561 = 13^q
28900 = 170^q
29241 = 171^q
29584 = 172^q
29791 = 31^q
29929 = 173^q
30276 = 174^q
30625 = 175^q
30976 = 176^q
31329 = 177^q
31684 = 178^q
32041 = 179^q
32400 = 180^q
32761 = 181^q
32768 = 2^q
33124 = 182^q
33489 = 183^q
33856 = 184^q
34225 = 185^q
34596 = 186^q
34969 = 187^q
35344 = 188^q
35721 = 189^q
35937 = 33^q
36100 = 190^q
36481 = 191^q
36864 = 192^q
37249 = 193^q
37636 = 194^q
38025 = 195^q
38416 = 14^q
38809 = 197^q
39204 = 198^q
39304 = 34^q
39601 = 199^q
40000 = 200^q
40401 = 201^q
40804 = 202^q
41209 = 203^q
41616 = 204^q
42025 = 205^q
42436 = 206^q
42849 = 207^q
42875 = 35^q
43264 = 208^q
43681 = 209^q
44100 = 210^q
44521 = 211^q
44944 = 212^q
45369 = 213^q
45796 = 214^q
46225 = 215^q
46656 = 6^q
47089 = 217^q
47524 = 218^q
47961 = 219^q
48400 = 220^q
48841 = 221^q
49284 = 222^q
49729 = 223^q
50176 = 224^q
50625 = 15^q
50653 = 37^q
51076 = 226^q
51529 = 227^q
51984 = 228^q
52441 = 229^q
52900 = 230^q
53361 = 231^q
53824 = 232^q
54289 = 233^q
54756 = 234^q
54872 = 38^q
55225 = 235^q
55696 = 236^q
56169 = 237^q
56644 = 238^q
57121 = 239^q
57600 = 240^q
58081 = 241^q
58564 = 242^q
59049 = 3^q
59319 = 39^q
59536 = 244^q
60025 = 245^q
60516 = 246^q
61009 = 247^q
61504 = 248^q
62001 = 249^q
62500 = 250^q
63001 = 251^q
63504 = 252^q
64000 = 40^q
64009 = 253^q
64516 = 254^q
65025 = 255^q
65536 = 2^q
66049 = 257^q
66564 = 258^q
67081 = 259^q
67600 = 260^q
68121 = 261^q
68644 = 262^q
68921 = 41^q
69169 = 263^q
69696 = 264^q
70225 = 265^q
70756 = 266^q
71289 = 267^q
71824 = 268^q
72361 = 269^q
72900 = 270^q
73441 = 271^q
73984 = 272^q
74088 = 42^q
74529 = 273^q
75076 = 274^q
75625 = 275^q
76176 = 276^q
76729 = 277^q
77284 = 278^q
77841 = 279^q
78125 = 5^q
78400 = 280^q
78961 = 281^q
79507 = 43^q
79524 = 282^q
80089 = 283^q
80656 = 284^q
81225 = 285^q
81796 = 286^q
82369 = 287^q
82944 = 288^q
83521 = 17^q
84100 = 290^q
84681 = 291^q
85184 = 44^q
85264 = 292^q
85849 = 293^q
86436 = 294^q
87025 = 295^q
87616 = 296^q
88209 = 297^q
88804 = 298^q
89401 = 299^q
90000 = 300^q
90601 = 301^q
91125 = 45^q
91204 = 302^q
91809 = 303^q
92416 = 304^q
93025 = 305^q
93636 = 306^q
94249 = 307^q
94864 = 308^q
95481 = 309^q
96100 = 310^q
96721 = 311^q
97336 = 46^q
97344 = 312^q
97969 = 313^q
98596 = 314^q
99225 = 315^q
99856 = 316^q
it took 62.6 ms including first init call (and string output to memo which is much slower then the computation itself) without the string it took just 1.25 ms