How do I change class value Python 3? - c++

I'm trying to use OOP to make tic tac toe, but whenever I win/draw a game is just keeps running and won't cancel out the game?
The error seems to be something to do with my while loop not wanted to break out.
Maybe this is a really stupid and obvious error in my code, but I've only been learning Python for 3 months so unfortunately I'm not the best right now.
# The

In the p_v_p() function it checks while both players have won, could this be causing the problem?

The problem isn't that the class variable isn't changed, it's that you're not checking it frequently enough. FYI, you called it a class variable in your question, but has_won is actually an instance variable. There are two problems that need to be corrected.
Your diagonal win conditions are incorrect:
diagnol_win = [[1,4,9],[3,4,7]]
This should be diagnol_win = [[1,5,9],[3,5,7]]
As #rob-py mentioned, you need to check has_won after each move. The following should fix the issue.
def p_v_p():
print("\nWelcome to Player vs Player Game Mode\
Player 1 you are 'X' , Player 2 you are 'O'!")
while True:
print("\nPlayer Ones Turn!")
player1.move()
if player1.has_won:
return
print("\nPlayer Twos Turn!")
player2.move()
if player2.has_won:
return
Since you're new to python, I thought I could offer some suggestions. I think you're off to a good start, but I would suggest defining three main classes: Player, Board, and Game. Here's a (at least mostly) working example. Keep in mind that this was a quick edit, so there's still plenty of room for more improvement.
class Board():
class PositionError(RuntimeError):
pass
class UpdateError(RuntimeError):
pass
def __init__(self):
self.markers = [' '] * 9
def print(self):
print()
print(self.markers[:3])
print(self.markers[3:6])
print(self.markers[6:])
def update(self, position, marker):
if position < 1 or position > 9:
raise self.PositionError()
if self.markers[position - 1] != ' ':
raise self.UpdateError()
self.markers[position - 1] = marker
def __getitem__(self, index):
return self.markers[index]
def __setitem__(self, index, value):
self.update(index + 1, value)
class Player:
def __init__(self, counter):
self.has_won = False
self.counter = counter
def move(self, board):
while True:
try:
player_input = int(input("Where you you like to place your counter? (1-9): "))
board.update(player_input, self.counter)
return
except ValueError:
print("\nInvalid Input not an number,Try Again.")
continue
except Board.PositionError:
print("\nPlease enter a position between 1-9")
continue
except Board.UpdateError:
print("\nPosition {} is already taken".format(player_input))
continue
class Computer(Player):
def move(self):
raise NotImplementedError()
class Game:
DRAW = 'D'
INCOMPLETE = 'I'
HORIZONTAL_WIN = [[1,2,3],[4,5,6],[7,8,9]]
VERTICAL_WIN = [[1,4,7],[2,5,8],[3,6,9]]
DIAGONAL_WIN = [[1,5,9],[3,5,7]]
def __init__(self, player_1, player_2):
self.player_1 = player_1
self.player_2 = player_2
self.board = Board()
def reset(self):
self.board = Board()
def play(self):
index = 0
players = [self.player_1, self.player_2]
while True:
players[index].move(self.board)
self.board.print()
state = self.check_state()
if state == players[index].counter:
print("\nPlayer with counter {} has won!".format(players[index].counter))
break
if state == self.DRAW:
print("\nTHIS GAME IS A DRAW! NOBODY WINS!")
break
index = (index + 1) % len(players)
self.reset()
return
def check_state(self):
if len([c for c in self.board.markers if c in ['O', 'X']]) >= 9:
return self.DRAW
for x, y, z in self.HORIZONTAL_WIN:
if self.board[x-1] == self.board[y-1] == self.board[z-1] != " ":
return self.board[x-1]
for x, y, z in self.VERTICAL_WIN:
if self.board[x-1] == self.board[y-1] == self.board[z-1] != " ":
return self.board[x-1]
for x, y, z in self.DIAGONAL_WIN:
if self.board[x-1] == self.board[y-1] == self.board[z-1] != " ":
return self.board[x-1]
return self.INCOMPLETE
def p_v_p():
print("\nWelcome to Player vs Player Game Mode")
print("Player 1 you are 'X' , Player 2 you are 'O'!")
return Game(Player('X'), Player('O'))
def p_v_c():
print("\nWelcome to Player vs Computer")
print("Human player you are Player 1 and counter 'X'. "
"The Computer is player 2 and counter 'O'")
return Game(Player('X'), Computer('0'))
def game_selection():
while True:
game_mode = input("""\nEnter what game mode you want to play:
- Player Vs Player (PvP)
- Player vs Computer (PvC)
Type your desired game mode here: """)
if game_mode.lower() == 'pvp':
return p_v_p() # Calls function for Player vs Player
if __name__ == '__main__':
while True:
game_selection().play()
if not input('Play again? [y/N]: ').lower().startswith('y'):
break

Related

How to make servo Dynamixel motor to move from 0 --> 90 --> 180 --> 220--->0 degrees

Hello software developers.
I am new in programming and ROS. I am working now with servo motors and want to make the controlling node to rotate motor into some degrees like from 0 --> 90--> 180-->0 degrees.
there is a main code and I would like to add def function into the main node:
#!/usr/bin/env python
import os
import rospy
from std_msgs.msg import String
from controller_motor.msg import Motor
from controller_motor.srv import Motor2
if os.name == 'nt':
import msvcrt
def getch():
return msvcrt.getch().decode()
else:
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
def getch():
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
from dynamixel_sdk import * # Uses Dynamixel SDK library
class DynamixelController(object):
def __init__(self):
#print("1")
self.motor_sub = rospy.Subscriber("/motor_topic", Motor, self.motor_callback)
self.test_motor_client(1) #here we can put request order as 1 for the using id=14 and position= 1500; or as 2 is id same and position is 2500. The cases could be found in the server.py node
def motor_callback(self, data):
_id = data.id
_position = data.position
print("_id : {0}, _position : {1}".format(_id, _position))
self.read_write(_id, _position)
def test_motor_client(self, request):
print("2")
rospy.wait_for_service('test_motor_service')
try:
proxy = rospy.ServiceProxy('test_motor_service', Motor2)
response = proxy(request)
print("response is id : {} position : {}".format(response.id, response.position))
self.read_write(response.id, response.position)
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def new_rotation(self, response):
print("3")
rospy.wait_for_service('test_mototr_rotation')
try:
proxy = rospy.ServiceProxy('test_motor_rotation', Motor2)
response = proxy(request)
self.read_write(response.id, response.position(arg[0]))
sleep(2)
self.read_write(response.id, response._position(arg[1]))
sleep(2)
self.read_write(response.id, response._position(arg[2]))
sleep(2)
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def read_write(self, _id, _position):
print("Start the node")
# Control table address
ADDR_PRO_TORQUE_ENABLE = 64 # Control table address is different in Dynamixel model
ADDR_PRO_GOAL_POSITION = 116
ADDR_PRO_PRESENT_POSITION = 132
# Protocol version
PROTOCOL_VERSION = 2.0 # See which protocol version is used in the Dynamixel
# Default setting
DXL_ID = _id # Dynamixel ID : 14
BAUDRATE = 1000000 # Dynamixel default baudrate : 1000000
DEVICENAME = '/dev/ttyUSB0' # Check which port is being used on your controller
# ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
TORQUE_ENABLE = 1 # Value for enabling the torque
TORQUE_DISABLE = 0 # Value for disabling the torque
DXL_MINIMUM_POSITION_VALUE = 10 # Dynamixel will rotate between this value
DXL_MAXIMUM_POSITION_VALUE = _position # The position here is already in the degree measurement; and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
DXL_MOVING_STATUS_THRESHOLD = 20 # Dynamixel moving status threshold
index = 0
dxl_goal_position = [DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE] # Goal position
# Initialize PortHandler instance
# Set the port path
# Get methods and members of PortHandlerLinux or PortHandlerWindows
portHandler = PortHandler(DEVICENAME)
# Initialize PacketHandler instance
# Set the protocol version
# Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler
packetHandler = PacketHandler(PROTOCOL_VERSION)
# Open port
if portHandler.openPort():
print("Succeeded to open the port")
else:
print("Failed to open the port")
print("Press any key to terminate...")
getch()
quit()
# Set port baudrate
if portHandler.setBaudRate(BAUDRATE):
print("Succeeded to change the baudrate")
else:
print("Failed to change the baudrate")
print("Press any key to terminate...")
getch()
quit()
# Enable Dynamixel Torque
dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
else:
print("Dynamixel has been successfully connected")
while 1:
print("Press any key to continue! (or press ESC to quit!)")
if getch() == chr(0x1b):
break
# Write goal position
dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_GOAL_POSITION, dxl_goal_position[index])
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
while 1:
# Read present position
dxl_present_position, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_PRESENT_POSITION)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
print("[ID:%03d] GoalPos:%03d PresPos:%03d" % (DXL_ID, dxl_goal_position[index], dxl_present_position))
if not abs(dxl_goal_position[index] - dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD:
break
# Change goal position
if index == 0:
index = 1
else:
index = 0
# Disable Dynamixel Torque
dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
# Close port
portHandler.closePort()
if __name__ == '__main__':
rospy.init_node('read_write', anonymous=True)
controller = DynamixelController()
and here is the server node:
#!/usr/bin/env python
import rospy
from controller_motor.srv import Motor2, Motor2Response
def motor_info(req):
print("receive the request : {}".format(req.order))
if req.order == 1:
_id = 14
#_position = 1500
_positiondegree = 180 # change it degree value
_position = (11.4 * (_positiondegree)) # here is using there 11.4 the number which helps rotate the motor in the correct degree; We get the number encoder number/degree we want to rotate the motor.
elif req.order == 2:
_id = 14
#_position = 2047.5
_positiondegree = 180
_position = (11.4 * (_positiondegree))
print("Response to this request id : {} and postiion : {}".format(_id, _position))
return Motor2Response(_id, _position)
def motor_info_server():
rospy.init_node('test_motor_service')
s = rospy.Service('test_motor_service', Motor2, motor_info)
print("Ready to response some id and position")
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
motor_info_server()
Now when running the motor it rotates to the degree I would like it to rotate. And now I would like to know how could I give some degrees to make motor rotates from 0 to some other degrees and go back to the 0 degree position again.
I guess there might be applied the list and args for some degrees. But I am not well-known how I could do this :)
I would like to get some advice from professionals like you ,guys :)
I know my question could be obvious for professionals. I would like to get experience in the programming and ROS as much as I can :)
I will be so thankful for any help and advise how I could do this :)
Thank to everyone who will share his/her idea:)
I wish you have a good day :)
You have to add a new function to your code in the client file:
def rotate_bot(self,degree):
rospy.wait_for_service('rotate_motor')
try:
proxy = rospy.ServiceProxy('test_motor_rotation', Motor2)
response = proxy(degree)
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
This function basically calls a Service and gives him the amount of degrees the robot has to turn. Also add this function to call the roate function:
def test_rotate(self):
rotate_bot(90)
rotate_bot(90)
rotate_bot(-180)
Now the robot turns from 0 --> 90 --> 180 --> 0
In your server file you have to add the service in the motor_info_server() method:
s = rospy.Service('test_motor_rotation', Motor2, rotate_motor)
and also add the method:
def rotate_motor(req):
print("received the request : {}".format(req.order))
degree = req.order
_id = 14
_positiondegree = degree
_position = (11.4 * (_positiondegree))
return Motor2Response(_id, _position)
If you want to pass doubles as degrees you have to change your message datatype from Motor2 to something else...

Attempting to use OOP Inner Objects, comming up with really werid error

Alright, I'm attempting to create a fairly simple blackjack game and Im fairly new to Python. While attempting to run the program after organizing most of it(program not finished) I keep geting this error and I'm not too sure how to fix it. It states that, "blackjack is not defined at unkown" however blackjack is clearly defined. Here's my code,
import random
import time
import os
def clear():
os.system( 'cls' )
# Globals
global pointcount
pointcount = []
global balance
balance = 100
global cardsuits
cardsuits = ['Diamonds','Spades','Hearts','Clubs'],
global cardsuitsym
cardsuitsym = ['♦','♠','♥','♣'],
global level
level = ["2",'3','4','5','6','7','8','9','10'],
randomsuit = random.choice(cardsuitsym)
randomlevel = random.choice(level)
class blackjack(object):
cardvalues = {
'2':2,
'3':3,
'4':4,
'5':5,
'6':6,
'7':7,
'8':8,
'9':9,
'10':10,
'J':10,
'Q':10,
'K':10,
'A':11
}
class dealer(): #Handles all functions related to the dealer and its operations
pass
class player(): #All Player Functions
def game_card_deal():#Draws the cards for the player and the dealer
upcardsuit = random.choice(cardsuitsym)
upcardlevel = random.choice(level)
random_cardsuit = random.choice(upcardsuit)
random_cardlevel = random.choice(upcardlevel)
print("┌────┐")
print("│ {} │").format(random_cardlevel)
print("│ {} │").format(random_cardsuit)
print("│ │")
print("└────┘")
pointcount.append(random_cardlevel)
class system(): #Handles all things system related, not dealing with the dealer or player
def game_begin(): #First thing ran, starts the game
print("Welcome to Blackjack, the rules are simple,")
print("")
print("Blackjack is played with one or more standard 52-card decks,\nwith each denomination assigned a point value.\n The cards 2 through 10 are worth their face value. Kings, queens, and jacks are each worth 10, and aces may be used as either 1 or 11.\n The object for the player is to draw cards totaling closer to 21, without going over, than the dealer's cards.")
print("██████████████████████████████████████████████████")
play_prompt = input("\nWould you like to play?")
if play_prompt == "yes" or "Yes" or "YES" or "y" or "YeS" or "YEs":
clear()
loadsym = "⌛"
for x in range(0, 5):
newloadsym = loadsym + "⌛"
print(newloadsym)
loadsym = newloadsym
time.sleep(1)
clear()
blackjack.game_card_deal()
blackjack.game_card_deal()
def game_point_finder(pointcount): #Finds the amount of points the player has
level = ["2",'3','4','5','6','7','8','9','10']
int(level[0])
int(level[1])
int(level[2])
int(level[3])
int(level[4])
int(level[5])
int(level[6])
int(level[7])
int(level[8])
amt_of_points = len(pointcount)
amt_of_points = amt_of_points - 1
int_points = pointcount[amt_of_points]
for x in range(0, amt_of_points):
int(int_points)
totalpoints = sum(pointcount)
print("Value:")
print(totalpoints)
blackjack.game_hit_or_stand()
def game_hit_or_stand(): #Third Prompt
hit_stand = input("Would you like to hit, or stand?")
if hit_stand == "hit" or "Hit" or "HIT" or "h":
blackjack.game_card_deal()
elif hit_stand == "stand" or "Stand" or "STAND" or "s":
blackjack.game_cards_show()
def game_card_show(): #End Game
blackjack.system.game_begin()
here is the corrected code and it runs fine
import random
import time
import os
def clear():
os.system( 'cls' )
Globals
global pointcount
pointcount = []
global balance
balance = 100
global cardsuits
cardsuits = ['Diamonds','Spades','Hearts','Clubs'],
global cardsuitsym
cardsuitsym = ['♦','♠','♥','♣'],
global level
level = ["2",'3','4','5','6','7','8','9','10'],
randomsuit = random.choice(cardsuitsym)
randomlevel = random.choice(level)
class blackjack(object):
cardvalues = {
'2':2,
'3':3,
'4':4,
'5':5,
'6':6,
'7':7,
'8':8,
'9':9,
'10':10,
'J':10,
'Q':10,
'K':10,
'A':11
}
class dealer(): #Handles all functions related to the dealer and its operations
pass
class player(): #All Player Functions
def game_card_deal():#Draws the cards for the player and the dealer
upcardsuit = random.choice(cardsuitsym)
upcardlevel = random.choice(level)
random_cardsuit = random.choice(upcardsuit)
random_cardlevel = random.choice(upcardlevel)
print("┌────┐")
print("│ {} │".format(random_cardlevel))
print("│ {} │".format(random_cardsuit))
print("│ │")
print("└────┘")
pointcount.append(random_cardlevel)
class system(): #Handles all things system related, not dealing with the dealer or player
def game_begin(): #First thing ran, starts the game
print("Welcome to Blackjack, the rules are simple,")
print("")
print("Blackjack is played with one or more standard 52-card decks,\nwith each denomination assigned a point value.\n The cards 2 through 10 are worth their face value. Kings, queens, and jacks are each worth 10, and aces may be used as either 1 or 11.\n The object for the player is to draw cards totaling closer to 21, without going over, than the dealer's cards.")
print("██████████████████████████████████████████████████")
play_prompt = input("\nWould you like to play?")
if play_prompt == "yes" or "Yes" or "YES" or "y" or "YeS" or "YEs":
clear()
loadsym = "⌛"
for x in range(0, 5):
newloadsym = loadsym + "⌛"
print(newloadsym)
loadsym = newloadsym
time.sleep(1)
clear()
blackjack.player.game_card_deal()
blackjack.player.game_card_deal()
def game_point_finder(pointcount): #Finds the amount of points the player has
level = ["2",'3','4','5','6','7','8','9','10']
int(level[0])
int(level[1])
int(level[2])
int(level[3])
int(level[4])
int(level[5])
int(level[6])
int(level[7])
int(level[8])
amt_of_points = len(pointcount)
amt_of_points = amt_of_points - 1
int_points = pointcount[amt_of_points]
for x in range(0, amt_of_points):
int(int_points)
totalpoints = sum(pointcount)
print("Value:")
print(totalpoints)
blackjack.game_hit_or_stand()
def game_hit_or_stand(): #Third Prompt
hit_stand = input("Would you like to hit, or stand?")
if hit_stand == "hit" or "Hit" or "HIT" or "h":
blackjack.player.game_card_deal()
elif hit_stand == "stand" or "Stand" or "STAND" or "s":
blackjack.game_cards_show()
def game_card_show():
pass#End Game
blackjack.system.game_begin()

Tkinter button doesn't respond (has no mouse over effect)

I'm writing a game that has info that is communicated from client to server and from server to client. One specific (non-playing) client is the monitor, which only displays the game board and players. This works fine, the only thing that doesn't work is the quit button on the GUI. A minor thing, but I would like it to work. :) Plus I think that there might be something pretty wrong with the code, even though it works.
I tried all kind of different commands (sys.exit, quit...) and nothing fixed it.
There's no error message, nothing happens with the button at all. No mouse over effect, nothing if I click it. Relevant code (I removed matrix and server logic because I think it's irrelevant - if it isn't I'll post it):
class Main():
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
# Has to be counted up by server class
rounds = 0
# Has to be communicated by server class. If numberwin == numberrobots,
# game is won
numberwin = 0
numberrobots = 2
def draw(self):
if hasattr(self, 'info'):
self.info.destroy()
if hasattr(self, 'quit'):
self.quit.destroy()
print "Main should draw this matrix %s" % self.matrix
[...] lots of matrix stuff [...]
# Pop-Up if game was won
# TODO: Make GUI quittable
if self.numberwin == self.numberrobots:
self.top = Toplevel()
self.msg = Message(self.top, text="This game was won!")
self.msg.pack(side=LEFT)
self.quittop = Button(
self.top, text="Yay", command=self.frame.destroy)
self.quittop.pack(side=BOTTOM)
# TODO: Quit GUI
self.quit = Button(self.frame, text="Quit", command=self.frame.destroy)
self.quit.pack(side=BOTTOM)
# Information on the game
self.info = Label(
self.frame, text="Rounds played: {}, Numbers of robots in win condition: {}".format(self.rounds, self.numberwin))
self.info.pack(side=TOP)
def canvasCreator(self, numberrows, numbercolumns):
# Game board
self.canvas = Canvas(
self.frame, width=numbercolumns * 100 + 10, height=numberrows * 100 + 10)
self.canvas.pack()
class Agent(Protocol, basic.LineReceiver):
master = Tk()
main = Main(master)
# So first matrix is treated differently from later matrixes
flagFirstMatrix = 1
def connectionMade(self):
msg = dumps({"type": "monitor"})
self.sendLine(msg)
print "Sent message:", msg
def dataReceived(self, data):
# Decode the json dump
print "Data received: %s" % data
data = loads(data)
self.main.matrix = np.matrix(data["positions"])
self.main.goals = np.matrix(data["goals"])
self.main.next_move_by_agent = data["next_move"]
self.main.rounds = data["rounds"]
self.main.numberwin = data["win_states"]
if self.flagFirstMatrix == 1:
self.main.numberrows, self.main.numbercolumns = self.main.matrix.shape
self.main.canvasCreator(
self.main.numberrows, self.main.numbercolumns)
self.main.canvas.pack()
self.flagFirstMatrix = 0
self.main.canvas.delete(ALL)
self.main.draw()
self.master.update_idletasks()
self.master.update()
First there is no indentation for class Agent, second for the quit button's "call back" self.frame.destroy is never defined so it doesn't do anything. If you meant tkinter destroy method try self.frame.destroy() or try explicitly defining it. You can also try calling either fram.pack_forget() or fram.grid_forget()
Add master.mainloop() to your last line in terms of the entire lines of code

Tkinter forgetting to finish the function

I am again asking a question on this progressbar project; although this should just be a clarification question.
My code causes for a progressbar to be created to track the creation of a file. The user selects the type of file they want to create and then hits "go" which causes for the file to begin changing and for the progressbar to appear. Progressbar works great. File writing/manipulation works great.
Problem: When the user selects several files to manipulate, despite the progressbars being created correctly, they do NOT update correctly. At first I thought that clicking on a button multiple times causes for tkinter to forget the root.after() function it was doing previously but after playing with a (much simpler) sample code I realized that this is not the case.
Question: How do I make sure tkinter doesn't stop implementing the first function even when the same function is restarted with different parameters?
Below are parts of my code to describe what I am doing.
progbarlock = False # start with the prograssbar marked as not occupied
class guibuild:
def __init__(self):
self.root = root
guibuild.progbarlock = False
global theframe
theframe = Frame(root)
job_name = e.get()
label = Label(theframe,text = job_name).pack(side=LEFT,padx =2)
self.progbar = Meter(theframe) #makes the progressbar object
self.progbar.set(0.0) #sets the initial value to 0
self.progbar.pack(side=LEFT)
self.counter = 0
self.i = float(0) #i is the value set to the progressbar
def stop_progbar(self):
self.progbar.stop()
def begin(self):
self.interval()
self.Status_bar()
theframe.pack(anchor="s")
def interval(self):
if guibuild.progbarlock == False:
guibuild.progbarlock = True
def update(self):
the_file = open('running_file.json')
data = json.load(the_file)
curr = data["current_line"]
total = data["total_lines"]
if self.i == 1.0:
self.stop_progbar
rint "100% - process is done"
self.root.after_cancel(self.interval)
elif curr == self.counter:
self.root.after(5000, self.interval)
elif curr == self.counter+1:
self.i += 1.0/total
self.progbar.set(self.i) #apply the new value of i to the progressbar
self.counter += 1
self.stop_progbar
self.root.after(5000, self.interval)
elif curr > self.counter+1:
self.i += 1.0/total*(curr-self.counter)
self.progbar.set(self.i) #apply the new value of i to the progressbar
self.counter = curr
self.stop_progbar
self.root.after(5000, self.interval)
else:
print "something is wrong - running.json is not available"
self.root.after(5000, self.interval)
guibuild.progbarlock = False
def start_process():
makeRequest() #this is defined much earlier in the code and includes all the file creation and manipulation
guibuild().begin()
button4 = Button(root,text="GO", command = start_process).pack()
NOTE:makeRequest() depends entirely on user input and the user input changes each time "go" is pressed.

Pygame midi prevents other input

I wish to have real-time midi input, in order to control some wx.Sliders. I have been able to achieve this, however it prevents interaction with the sliders via the mouse or keyboard and causes the application to crash.
This is the code I have at the moment.
import wx, pygame, pygame.midi
class windowClass(wx.Frame):
def __init__(self, *args, **kwargs):
super(windowClass, self).__init__(*args, **kwargs)
self.basicGUI()
def basicGUI(self):
panel = wx.Panel(self)
self.slider = wx.Slider(panel, -1, 2, 0, 128, pos=(10,25), size=(250,-1), style=wx.SL_AUTOTICKS | wx.SL_LABELS)
sliderText = wx.StaticText(panel, -1, 'Slider 1 ', (8,8))
self.slider2 = wx.Slider(panel, -1, 2, 0, 128, pos=(10,110), size=(250,-1), style=wx.SL_AUTOTICKS | wx.SL_LABELS)
sliderText = wx.StaticText(panel, -1, 'Slider 2', (8,88))
self.Bind(wx.EVT_SLIDER, self.sliderUpdate)
self.SetTitle('Sliders Window!')
self.Show(True)
pygame.init()
pygame.midi.init()
inp = pygame.midi.Input(1)
running = True
while running:
if inp.poll():
dataset = inp.read(1)
control = dataset[0][0][1]
if control > 8:
continue
if control == 1:
value = dataset[0][0][2]
self.slider.SetValue(value)
if control == 2:
value = dataset[0][0][2]
self.slider2.SetValue(value)
pygame.time.wait(10)
def sliderUpdate(self, event):
value1 = self.slider1.GetValue()
value2 = self.slider2.GetValue()
print value1, value2
def main():
app = wx.App()
windowClass(None)
app.MainLoop()
main()
What is causing pygame.midi to take all resources? I have a feeling it is regarding while running = True, however my attempts at trying to close the instance don't seem to work.
How can I have the sliders being controlled by the midi and the mouse calling sliderUpdate? Thanks for any help.
You have a loop that never exits, so your program never reaches the parts that deal with anything except the midi input
I would move the code that is currently in that loop into a function, remove the loop, and add a timer to the panel, e.g.
def basicGUI(self):
... panel stuff
pygame.init()
pygame.midi.init()
timer = wx.Timer(self, -1)
self.Bind(wx.EVT_TIMER, self.OnTimer)
timer.Start(10, False)
def OnTimer(self, event):
inp = pygame.midi.Input(1)
if inp.poll():
dataset = inp.read(1)
control = dataset[0][0][1]
if control > 8:
continue
if control == 1:
value = dataset[0][0][2]
self.slider.SetValue(value)
if control == 2:
value = dataset[0][0][2]
self.slider2.SetValue(value)