import tkinter as tk
import pygame
pygame.init()
ss = width, height = 1024, 600
screen = pygame.display.set_mode(ss)
tkinput_1 = True
while True:
event = pygame.event.poll()
keys = pygame.key.get_pressed()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((0,0,0))
if tkinput_1 == True:
tkinput_root1 = tk.Tk()
tkinput_root1.geometry("200x200")
tkinput_root1.title("How many teams?")
tkinput_input1 = tk.Entry(tkinput_root1)
tkinput_1 = False
pygame.display.update()
tkinput_root1.mainloop()
This was just me giving the tkinter text input box a shot in pygame. I was fairly sure it wouldn't work out properly but decided I'd try it anyway cause I had nothing to lose.
The tkinter screen does not show up till you've exited pygame.
So, I'm not asking if anyone knows how to fix the code, but instead if anyone knows the simplest way to create a text box in pygame. I know there is a textinput class module that can be imported. If you believe that is the easiest way to do it then can you walk me through it. If not could you please let me know what you think the easiest way is. It's a small program so I want to avoid a lot of heavy lines of code for a simple text box. Let me know what you guys think.
Thanks a lot in advance.
I've tryed using Tk but the thing about using is it stops the whole pygame program when the Tk window pops up and its just not good
this is what i use Pygame InputBox its not the prettiest but it works great just download it and its really easy to use
just import inputbox
then do something like this:
inp = int(inputbox.ask(screen, 'Message')) #inp will equal whatever the input is
this is pretty much like raw_input but for pygame
its not the most aesthetically pleasing but im sure if you search around you can find maybe a nicer one
You can use a small library i'm making, just download it and use it.
To make a simple Text box try:
from GUI import *
input_bow = InLineTextBox((0, 0), 200)
You must give it at least a postion and the size
Then in your input loop, update it :
for e in pygame.event.get():
input_box.update(e)
and at the end, render it :
input_box.render(screen)
You can get the text with input_box.text at any moment
I recommend using EzText. It's a great way to add text inputs into your pygame programs. I have personally used it my self and it is nice and easy and works with python 3.3.2.
http://www.pygame.org/project-EzText-920-.html
Regarding what you said about the error with InputBox, all you have to do find and replace everywhere it says (without the quotation marks) string.join(current_string,"") with "".join(current_string), since I think this is new in python 3.4, anyway, hope that helps.
Related
I was wondering if someone could give me a detailed explanation on how to run a game/app developed using Pygame on an Android phone. I recently finished programming PacMan and it works perfectly on my computer, but I think it would be awesome if I could get it running on my phone. I tried following the instructions at http://pygame.renpy.org/android-packaging.html, but every time i run "import android" on the IDLE I get an error saying it did not find the module. Could someone clearly explain how to set up the android module?
Also, in my program I used code such as if (event.key == K_UP or event.key == K_w): direction = UP. However there are no arrow keys on a phone. What code would I need to use to see if the user swiped the screen with their fingers from up -> down or left -> right, etc.
Any help would be great. Thanks <3
There is a pyGame subset for android. However this requires special reworking and changing the program. Hopefully it will not be to hard.
http://pygame.renpy.org/writing.html
http://pygame.renpy.org/index.html
However about your second question i am unable to awnser because I am Not yet experienced enough.
i think the pygame subset for android would be good but i dont trust its functionality, i use kivy as its cross platform
and if you ever decide to use the pygame subset for android your touch of flips on screen of an android device would be your mouse movement on the desktop so i ma saying treat the touch as the mouse good luck
There are some pretty good answers for your first part already so I won't answer that. (I came here looking into what to use for it too!)
However the second part of your question should be a lot easier.
Have a mouse object that on a mouse down event will save the coordinates of the touch to an MX and MY variable
Then when the mouse up event is triggered takes the new coordinates and calculates a vector using the MX and MY and this new point ie. The distance and angle of the swipe. Use trigonometry or the math module for the angle (research arctan2).
You can then use this in an if, elif, else to determine what quadrant the angle was and the distance to determine whether the swipe was valid if it's greater than a certain value.
I'm on mobile so unfortunately I can't give an example, however I'm certain you're apt to work out the solution with this guidance.
For your second question, there is an answer in another website.
https://amp.reddit.com/r/Python/comments/2ak14j/made_my_first_android_app_in_under_5_hours_using/
it says You can try code like this
if android:
android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
I hope it will help you.
I've runned pygame for android!!!!
Firstly, I'm debugged app using saving error to file.
I got error that on android it can be runned only under fullscreen.
I've created small app and it working:
import sys, os
andr = None
try:
import android
andr = True
except ImportError:
andr = False
try:
import pygame
import sys
import pygame
import random
import time
from pygame.locals import *
pygame.init()
fps = 1 / 3
width, height = 640, 480
screen = pygame.display.set_mode((width, height), FULLSCREEN if andr else 0)
width, height = pygame.display.get_surface().get_size()
while True:
screen.fill((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
time.sleep(fps)
except Exception as e:
open('error.txt', 'w').write(str(e))
Screenshot: https://i.stack.imgur.com/4qXPe.png
requirements in spec file:
requirements = python3,pygame
APK File size is only 12 MB!
pygame.event has multiple touch-screen events. Here are some useful ones:
FINGERMOTION: touch_id, finger_id, x, y, dx, dy
FINGERDOWN: touch_id, finger_id, x, y, dx, dy
FINGERUP: touch_id, finger_id, x, y, dx, dy
MULTIGESTURE: touch_id, x, y, pinched, rotated, num_fingers
import pygame
import sys
from pygame.locals import *
DISPLAY_SURF = pygame.display.set_mode((640,480))
#Sets the resolution to 640 pixels by 720 pixels
class Game:
def __init__(self):
pygame.init()
self.FPS = 60
self.fps_clock = pygame.time.Clock()
self.surface = pygame.display.set_mode((640, 480))
pygame.display.set_caption("The Hunt")
img = pygame.image.load("Graphics/background.png")
self.surface.blit(img)
#This class sets the basic attributes for the window.
#The clock is set to 60 and the name of the window
#is set to The Hunt which is a working title for my project
def run(self):
while True:
pygame.display.update()
self.fps_clock.tick(self.FPS)
self.process_game()
#This updates the window display to refresh every clock tick
def process_game(self):
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
game = Game()
#This creates an instance of the class Game which gives all the attributes
# and behaviours to this instance
game.run()
#Calling this function generates a window with the attributes defined.
I need some help. I have already checked if it is in the same folder, the file is definitely a png and I spelt all the folder names and the destination correctly. I'm open to any suggestions
I'm going to answer this question despite that it is not really a good one for Stack Overflow. On this site, you'll have to be more specific and detailed, because no one intends to read through a huge lot of code for you. I did however pickup some things that I think can be fixed ( some of these are opinion based, something that your question should never force an answer to have), but... here it is anyway:
For starters, when you construct a class, you use parenthesis after the class name, even if it's not going to inherit anything form another class. So change the line where you construct the Game class to this:
class Game():
Second thing about this code is that if your going to create the pygame window surface inside the Game() class, I don't understand why you're creating another window at the beginning of your code. If there is a reason for this please explain it in a comment in your code.
The last thing is more opinion-based . I don't know how many people create Pygame GUI applications like this, but it would be simpler to not use classes so you could understand the code better. When I create a Pygame GUI, I define the window, then the sprites, then I run the main game loop in a While Loop. Here is how I would normally structure your program:
#import pygame
import pygame, sys
from pygame.locals import *
#Initialize pygame and define colours
pygame.init()
white = 255,255,255
#Sets the resolution to 640 pixels by 720 pixels and caption for pygame window
DISPLAY_SURF = pygame.display.set_mode((640,480))
pygame.display.set_caption("The Hunt!")
#Create a clock object
clock = pygame.time.Clock()
FPS = 60
#Define a variable to refer to image
image = pygame.image.load("download.jpg")
#Start main loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
DISPLAY_SURF.fill(white)
DISPLAY_SURF.blit(image,(0,0))
pygame.display.update()
I do use classes when creating a sprite, so I can create several instances of it, as well as keep functions I want to perform on the sprite all in one place. Doing this for the WHOLE program does work, and I suppose it's more "pythonic" (since python is object-oriented) but is still unnecessary for something like this. Here is a reference that teaches pygame in a similar way to how I code it, which I personally find to be an excellent tutorial.
Many people also put this code in a main() function and then run it, which is also a wildly used and accepted practice.
This question already has answers here:
How can I create a text input box with Pygame?
(5 answers)
Closed 2 years ago.
I'm making a program and I'd like to run it using pygame. The key thing is that I need an space for the user to input numbers and at the screen I need to print an array, which may vary in size (always 3 columns, but the user controls the number of lines), but I want it to always been fully shown in the screen. How can I make both things?
You can't expect people to write down code from scratch to accomplish what you want. If it is just advice you need, I can give some.
Pygame has no formal input field or input box introduced. If you want to implement such thing in pygame specifically, you have to keep record of the input keys(keyboard input). And insert the inputs in a string or list, then display them yourself. But you have to implement the methodology of the inputbox you designed, like you should have a condition for backspace where it deletes the last element of the list. Pygame does not do this formally, but you can write something like this.
However, what you need seems like a gui. Which gives a better way of taking inputs, making input fields, giving properties to the program window and the input boxes, making buttons etc.. In this case, if you change your mind, I would suggest Wxpython.
If you want to create a very simple text input box on your own, you could try to define an area with a pygame.Rect, then check if the mouse collides with the rect to select it and use the .unicode attribute of the keyboard events to attach the characters to a list or string which you can display on the screen.
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
your_input_string += event.unicode
There are also some GUI libraries for Pygame like SGC which is pretty easy to use. Alternatives (on pygame.org) are Albow, PGU and OcempGUI (the latter works only with Python 2.7).
This can be done using pygame_gui. Text input is available through a UITextEntryLine instance, while printing an array could be done using a UITextBox. You'll first need to set up the environment as in the quick start guide.
Create a UITextEntryLine instance:
from pygame.rect import Rect
from pygame_gui.elements.ui_text_entry_line import UITextEntryLine
text_input = UITextEntryLine(relative_rect=Rect(0, 0, 100, 100), manager=manager)
Input can be restricted to only numbers using set_allowed_characters:
text_input.set_allowed_characters('numbers')
Adding a check to the event queue allows for getting text input when enter is pressed:
for event in pygame.event.get():
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_TEXT_ENTRY_FINISHED:
if event.ui_element == text_input:
entered_text = text
A UITextBox can be set to a custom height by setting the height to -1:
from pygame_gui.elements.ui_text_box import UITextBox
text_box = UITextBox(relative_rect=Rect(0, 0, 100, -1), manager=manager, text='foobar')
I am Python 3 noob creating a checkers game, I have a bunch of functions... and my game's loop is as follows:
while EndGame==0:
PrintBoard()
PrintBoardGui()
print("################","\n","Player 1","\n","################","\n")
Player=1
PlayerSelectPiece()
MovePiece()
PrintBoard()
PrintBoardGui()
print("################","\n","Player 2","\n","################","\n")
Player=2
if NbrPlayer==2:
PlayerSelectPiece()
else:
AiSelectPiece()
MovePiece()
PrintBoardGui() that I run at the beggining of each turn and creates a Tkinter window and draws the board on a new Canvas in a Tkinter Frame.
After that, I have to close the window in order for the program to continue.
I know this is a sub-optimal solution.
I have looked around trying to understand Tkinter's loops and read a bit about the after() function but i really don't know how I could implement it in my code.
Ultimatly I would like my Tkinter window to stay open (mabye disabled or something) while I input stuff in the console to move the pieces. Can you help me?
At first, how do you want to interact with your game ?
With text in the console ?
With buttons ?
With keyboard/mouse event ?
The "after" method is used to refresh your screen after an amount of time.
It will call the method that you pass through the parameters.
You shouldn't have to put an infinite loop in it. But you will have to check with a simple condition the game ending, to display another screen.
If you have to use the console entry, it can be a bit hard for a beginner to manage the GUI update and the console.
I am not sure what ur question was but, If you would want to run the code forever (until you stop it). you would have to use the while loop like this:
while "thing" == True:
PrintBoard()
PrintBoardGui()
print("################","\n","Player 1","\n","################","\n")
Player=1
PlayerSelectPiece()
MovePiece()
PrintBoard()
PrintBoardGui()
print("################","\n","Player 2","\n","################","\n")
Player=2
if NbrPlayer==2:
PlayerSelectPiece()
else:
AiSelectPiece()
MovePiece()
thing = False
at the end you change thing to False otherwise it would be infinite and it would bug.
OKay, so i wrote a code to develop a game using pygame. this is the aim of the game :
there is a player (Mario) which can move only vertically. from the right side of the window, flames appear which the mario has to dodge. the game is very similar to dodger.py !
now, when i run the game, it gets stuck at "Press any key to Enter"
PLEASE HELP !
You are not doing anything in the waitforkey() function.
if event.type == KEYDOWN:
# if key exit blah blah
else:
runGame()
You could put your game in a function called runGame and that would probabaly be the easiest way of doing this. Just remember that the variables will then be local to the scope of that function and any changes won't affect the rest of the program.
Having checked the code on a PC, I have found 3 errors. Two of which are typing errors. First one is on Line 77:
playerrect.topleft = (50,window_hight/2)
Needs to be:
playerrect.topleft = (50,window_height/2)
and the second is on line 126:
WindowSurface.fill(bgcolour)
You haven't defined bgcolour (as far as I could see) so by adding the following to the variables at the top of the file:
bgcolour(255,255,255) #change to what colour you want
The third error I found was in your waitForKey() function. I don't know whether this is important to the running of the program, but you have your if event.type == "QUIT" in speech marks. Like I said, this may not matter but I thought I'd point it out. You have also done this for the other conditions in this function.
By making these changes, you get running code. However, flames do not appear and I don't have time to figure this one out. By fiddling though, I'm sure you'll figure it out!