logo
down
shadow

How to get an input from user in Pygame and save it as a variable?


How to get an input from user in Pygame and save it as a variable?

By : GURJEET SINGH KHALSA
Date : November 22 2020, 10:38 AM
it should still fix some issue Here is a possible solution, it may be really useful for future visitors that are also suffering with this problem like me. Which is;
code :
def text1(word,x,y):
    font = pygame.font.SysFont(None, 25)
    text = font.render("{}".format(word), True, RED)
    return screen.blit(text,(x,y))
def inpt():
    word=""
    text1("Please enter your name: ",300,400) #example asking name
    pygame.display.flip()
    done = True
    while done:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    word+=str(chr(event.key))
                if event.key == pygame.K_b:
                    word+=chr(event.key)
                if event.key == pygame.K_c:
                    word+=chr(event.key)
                if event.key == pygame.K_d:
                    word+=chr(event.key)
                if event.key == pygame.K_RETURN:
                    done=False
                #events...
    return text1(word,700,30)
def game_intro():
intro=True

while intro:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            quit()
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_RETURN:
                intro=False
    inpt() #Here we are calling our function
    screen.fill(white)

    pygame.display.update()
    clock.tick(15)


Share : facebook icon twitter icon
Save variable value in a file by user input

Save variable value in a file by user input


By : Augusto Neves
Date : March 29 2020, 07:55 AM
I hope this helps . Basically, manually overwriting config file sounds like a trivial task using pure Lua.
Something like this (initial write, do whatever changes to default or current config):
code :
local function flush_config_to_file(configTable, configFile)
    local tmpFileHandle
    local configFileLines = {}

    --start file with array declaration
    table.insert(configFileLines, "local config = {")

    --iterate default configs and put string analogical lines into table:
    for key, value in pairs(defaultConfig) do
        table.insert(configFileLines, "\t[\"key\"] = " .. tostring(value) .. ",")
    end

    --closing array:
    table.insert(configFileLines, "}")

    --returning table of config values:
    table.insert("return config")

    tmpFileHandle = io.open(configFile, "w")

    --concat lines with \n separator and write those to file:
    tmpFileHandle:write(table.concat(configFileLines, "\n"))
    tmpFileHandle:close()
end

local function create_initial_config_file(configFile)
    local defaultConfig = 
    {
        "first_run" = true,
        "maxMP" = nil,
        "maxHP" = nil

        -- etc etc etc
    }

    flush_config_to_file(defaultConfig, configFile)
end

local function get_config_from_module(configModule)
    local tmpConfigTable

    package.loaded[configModule] = nil
    tmpConfigTable = require(configModule)

    return tmpConfigTable
end
local configModule = "config_file"
local configFile = configModule .. ".lua"
local tmpConfig = nil

create_initial_config_file(configFile)

-- Wall of text and logics I do not care about

-- Then user requires some configuration from file (module):
tmpConfig = getConfigFromModule(configModule)

-- User interaction or whatever which updates config:
tmpConfig.maxHP = io.read()
tmpConfig.first_run = false
-- etc etc 

-- Rewrite config file with updated values:
flush_config_to_file(tmpConfig, configFile)
local config = {
    ["first_run"] = true,
    ["maxMP"] = nil,
    ["maxHP"] = nil,
}

return config
`pygame`: on Ubuntu, using `pygame.image.save` to save PNG causes `pygame.error: SavePNG: could not create png write str

`pygame`: on Ubuntu, using `pygame.image.save` to save PNG causes `pygame.error: SavePNG: could not create png write str


By : Yamini Gera
Date : March 29 2020, 07:55 AM
around this issue This problem was caused because I installed my Python stack using Anaconda, but then installed pygame using the build+install instructions for Ubuntu on pygame's documentation page.
This caused there to be conflicting libraries of libpng, I think, somewhere, somehow.
code :
======================================================================
FAIL: BaseModuleTest.test_get_error
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/brian/anaconda2/lib/python2.7/site-packages/pygame/tests/base_test.py", line 569, in test_get_error
    e)
AssertionError: Failed to access the SoundFont /usr/share/sounds/sf2/FluidR3_GM.sf2

======================================================================
FAIL: BaseModuleTest.test_set_error
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/brian/anaconda2/lib/python2.7/site-packages/pygame/tests/base_test.py", line 586, in test_set_error
    e)
AssertionError: Failed to access the SoundFont /usr/share/sounds/sf2/FluidR3_GM.sf2
How to save user's input in variable using delegate?

How to save user's input in variable using delegate?


By : Huy Dang Khang
Date : March 29 2020, 07:55 AM
this will help I think the way to go is to use the UITableViewDelegate method didSelectRowAtindexPath in the WordTableViewController (if that's the class with your table view).
A gestureRecognizer does not seem like something you want in your tableViewController as it has nice build in delegate methods to register user presses. Therefore, replace your viewDictionary(_:) function with the following:
code :
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "viewDictionary", sender: indexPath)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // I just made this identifier up, but create one yourself in the storyboard
    if segue.identifier == "viewDictionary" {
       // Define your vc
       let libController = segue.destination as! UIReferenceLibraryViewController

       // Define indexPath
       let indexPath = sender as! IndexPath

       // Set value in destination vc
       libController.engWord = yourArrayOfEngWords[indexPath.row]       
    }
}
class UIReferenceLibraryViewController(){
     var engWord: String = ""

     // Rest your class properties and functions here...
}
Saving user input as a variable in pygame

Saving user input as a variable in pygame


By : user3599363
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I am working on a game in which the user inputs an amount of money they want to bet and then if they win/lose, the purse is updated. After they input the amount they want to take, Pygame is not recognizing it as a variable and will not continue. Message I get is
code :
amount = raw_input('Please enter a number: ')
amount = raw_input('...')
stake = 0
try:
  stake = int(amount)
except Exception:  # this is raised if the input is invalid i.e. not numeric
  pass  # does nothing
Python/Pygame: How to save text box input as variable

Python/Pygame: How to save text box input as variable


By : Buddymf Swailes
Date : March 29 2020, 07:55 AM
it helps some times I am currently using this bit of code I found: , After creating a text_box, the text is stored in text_box.text
Related Posts Related Posts :
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • Creating a custom admin view
  • How do you get the user role of the currently logged in user in Ckan?
  • Speed up Numpy Meshgrid Command
  • Python error - name lengths
  • appending text to a global variable
  • Python Mistake - Number of letters in name
  • Searching for a sequence in a text
  • Testing logging output with pytest
  • How do I change my default working directory for Python (Anaconda) on VSCode?
  • .lower() for x in list, not working, but works in another scenario
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org