Showing posts with label pygame. Show all posts
Showing posts with label pygame. Show all posts

Sunday, July 22, 2018

Pygame Surface updates non-sequentially

Leave a Comment

I am attempting to implement a simple Pygame script that is supposed to:

  1. First, check for when the user presses the Space key;
  2. On Space keypress, display some text; then
  3. Pauses for 2 seconds and then update the screen to its original state.

Note that all of the above events must occur sequentially, and cannot be out of order.

I am encountering problems where the program first pauses, then displays the text only appears for a split second (or not at all) before the screen updates to its original state.

The program seems to have skipped over step 2 and proceeded with the pause in step 3 before displaying text. My code is as follows:

import pygame import sys from pygame.locals import *  WHITE = (255, 255, 255) BLACK = (0, 0, 0)  pygame.init() wS = pygame.display.set_mode((500, 500), 0, 32)   # Method works as intended by itself def create_text(x, y, phrase, color):     """     Create and displays text onto the globally-defined `wS` Surface     (params in docstring omitted)     """     # Assume that the font file exists and is successfully found     font_obj = pygame.font.Font("./roboto_mono.ttf", 32)     text_surface_obj = font_obj.render(phrase, True, color)     text_rect_obj = text_surface_obj.get_rect()     text_rect_obj.center = (x, y)     wS.blit(text_surface_obj, text_rect_obj)   while True:     wS.fill(BLACK)     for event in pygame.event.get():         if event.type == KEYDOWN and event.key == K_SPACE:              # Snippet containing unexpected behavior             create_text(250, 250, "Hello world!", WHITE)             pygame.display.update()             pygame.time.delay(2000)             # Snippet end          if event.type == QUIT:             pygame.quit()             sys.exit(0)     pygame.display.update() 

Thanks in advance!

2 Answers

Answers 1

For some reason the program worked for me with the only thing I changed was the font. This is the same as what @Omega0x013 is doing, but you have an unlimited framerate. It works because FPS.tick() returns the amount of time since it was last called, if you don't specify a frame rate, it does not hold the program.

import pygame import sys from pygame.locals import * displayText = False WHITE = (255, 255, 255) BLACK = (0, 0, 0)  pygame.init() wS = pygame.display.set_mode((500, 500), 0, 32)   # Method works as intended by itself def create_text(x, y, phrase, color):     """     Create and displays text onto the globally-defined `wS` Surface     (params in docstring omitted)     """     # Assume that the font file exists and is successfully found      font_obj = pygame.font.Font(None,30)     text_surface_obj = font_obj.render(phrase, True, color)     text_rect_obj = text_surface_obj.get_rect()     text_rect_obj.center = (x, y)     wS.blit(text_surface_obj, text_rect_obj)  FPS = pygame.time.Clock() while True:     wS.fill(BLACK)     for event in pygame.event.get():         if event.type == KEYDOWN and event.key == K_SPACE:             totalTime = 0             FPS.tick()             displayText = True          if event.type == QUIT:             pygame.quit()             sys.exit(0)     if displayText:         totalTime += FPS.tick()         create_text(250, 250, "Hello world!", WHITE)         if totalTime >= 2000:             displayText = False     pygame.display.update() 

Answers 2

you should try this:

import pygame import sys from pygame.locals import *  WHITE = (255, 255, 255) BLACK = (0, 0, 0)  pygame.init() wS = pygame.display.set_mode((500, 500), 0, 32) clock = pygame.time.Clock()  showing = False timer = 0 # Method works as intended by itself def create_text(x, y, phrase, color):     """     Create and displays text onto the globally-defined `wS` Surface     (params in docstring omitted)     """     # Assume that the font file exists and is successfully found     font_obj = pygame.font.Font("./roboto_mono.ttf", 32)     text_surface_obj = font_obj.render(phrase, True, color)     text_rect_obj = text_surface_obj.get_rect()     text_rect_obj.center = (x, y)     wS.blit(text_surface_obj, text_rect_obj)   while True:     wS.fill(BLACK)     for event in pygame.event.get():         if event.type == KEYDOWN and event.key == K_SPACE:             showing = True             timer = 0          if event.type == QUIT:             pygame.quit()             sys.exit(0)      if showing:         timer += 1         create_text(250, 250, "Hello world!", WHITE)      if timer == 20:         timer = 0         showing = False      pygame.display.update()     clock.tick(100) 

what this does is every time you press space it shows the text for 2s by showing it, counting 2000ms and then not showing it.

Read More

Saturday, May 19, 2018

Matplotlib equivalent of pygame flip

Leave a Comment

I have a program with rapid animations which works perfectly under pygame, and for technical reasons, I need to do the same using only matplotlib or an other widespread module.

The program structure is roughly:

pygame.init()         SURF = pygame.display.set_mode((500, 500)) arr = pygame.surfarray.pixels2d(SURF) # a view for numpy, as a 2D array while ok:     # modify some pixels of arr     pygame.display.flip() pygame.quit() 

I have no low level matplotlib experience, but I think it is possible to do equivalent things with matplotlib. In other words :

How to share the bitmap of a figure, modify some pixels and refresh the screen ?

Here is a minimal working exemple, which flips 250 frames per second (more than the screen ...) on my computer :

import pygame,numpy,time pygame.init() size=(400,400)         SURF = pygame.display.set_mode(size) arr = pygame.surfarray.pixels2d(SURF) # buffer pour numpy    t0=time.clock()  for counter in range(1000):         arr[:]=numpy.random.randint(0,0xfffff,size)         pygame.display.flip()       pygame.quit()  print(counter/(time.clock()-t0)) 

EDIT

What I try with indications in answers :

import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation  fig = plt.figure()   def f(x, y):     return np.sin(x) + np.cos(y)  x = np.linspace(0, 2 * np.pi, 400) y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)  im = plt.imshow(f(x, y), animated=True)  count=0 t0=time.clock()+1 def updatefig(*args):     global x, y,count,t0     x += np.pi / 15.     y += np.pi / 20.     im.set_array(f(x, y))     if time.clock()<t0:         count+=1     else:         print (count)         count=0         t0=time.clock()+1          return im,  ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True) plt.show() 

But this only provides 20 fps....

4 Answers

Answers 1

If you want to animate a plot, then you can take a look at the animation functionality in matplotlib under matplotlib.animation.Animation. Here's a great tutorial - https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial.

If you just want to periodically update an adhoc bitmap, I am not sure matplotlib is meant for what you are trying to achieve. From matplotlib docs:

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

If you would like to periodically update an adhoc image on the screen, you may want to look into GUI libraries for python. Here is a short summary of available options - https://docs.python.org/3/faq/gui.html. Tkinter is a pretty standard one and is shipped with python. You can use the ImageTk module in pillow to create/modify images for displaying via Tkinter - http://pillow.readthedocs.io/en/4.2.x/reference/ImageTk.html.

Answers 2

It should be noted that the human brain is capable of "seeing" up to a framerate of ~25 fps. Faster updates are not actually resolved.

Matplotlib

With matplotlib and its animation module the example from the question runs with 84 fps on my computer.

import time import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation  fig, ax = plt.subplots()   def f(x, y):     return np.sin(x) + np.cos(y)  x = np.linspace(0, 2 * np.pi, 400) y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)  im = ax.imshow(f(x, y), animated=True) text = ax.text(200,200, "")  class FPS():     def __init__(self, avg=10):         self.fps = np.empty(avg)         self.t0 = time.clock()     def tick(self):         t = time.clock()         self.fps[1:] = self.fps[:-1]         self.fps[0] = 1./(t-self.t0)         self.t0 = t         return self.fps.mean()  fps = FPS(100)  def updatefig(i):     global x, y     x += np.pi / 15.     y += np.pi / 20.     im.set_array(f(x, y))     tx = 'Mean Frame Rate:\n {fps:.3f}FPS'.format(fps= fps.tick() )      text.set_text(tx)          return im, text,  ani = animation.FuncAnimation(fig, updatefig, interval=1, blit=True) plt.show() 

PyQtGraph

In pyqtgraph a higher framerate is obtained, it would run with 295 fps on my computer.

import sys import time from pyqtgraph.Qt import QtCore, QtGui import numpy as np import pyqtgraph as pg  class FPS():     def __init__(self, avg=10):         self.fps = np.empty(avg)         self.t0 = time.clock()     def tick(self):         t = time.clock()         self.fps[1:] = self.fps[:-1]         self.fps[0] = 1./(t-self.t0)         self.t0 = t         return self.fps.mean()  fps = FPS(100)  class App(QtGui.QMainWindow):     def __init__(self, parent=None):         super(App, self).__init__(parent)          #### Create Gui Elements ###########         self.mainbox = QtGui.QWidget()         self.setCentralWidget(self.mainbox)         self.mainbox.setLayout(QtGui.QVBoxLayout())          self.canvas = pg.GraphicsLayoutWidget()         self.mainbox.layout().addWidget(self.canvas)          self.label = QtGui.QLabel()         self.mainbox.layout().addWidget(self.label)          self.view = self.canvas.addViewBox()         self.view.setAspectLocked(True)         self.view.setRange(QtCore.QRectF(0,0, 100, 100))          #  image plot         self.img = pg.ImageItem(border='w')         self.view.addItem(self.img)          #### Set Data  #####################         self.x = np.linspace(0, 2 * np.pi, 400)         self.y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)          #### Start  #####################         self._update()      def f(self, x, y):             return np.sin(x) + np.cos(y)      def _update(self):          self.x += np.pi / 15.         self.y += np.pi / 20.         self.img.setImage(self.f(self.x, self.y))          tx = 'Mean Frame Rate:\n {fps:.3f}FPS'.format(fps= fps.tick() )          self.label.setText(tx)         QtCore.QTimer.singleShot(1, self._update)   if __name__ == '__main__':      app = QtGui.QApplication(sys.argv)     thisapp = App()     thisapp.show()     sys.exit(app.exec_()) 

Answers 3

If you just need to animate a matplotlib canvas the animation framework is the answer. There's a simple example here that does basically what you ask.

If this is going to be part of a more complex application you probably want finer control over a specific backend.

Here's a quick attempt using Qt loosely based on this matplotlib example.

It's using a QTimer for the updates, probably there's also some idle callback in Qt you could attach to.

import sys  import numpy as np import matplotlib as mpl mpl.use('qt5agg') from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from PyQt5 import QtWidgets, QtCore  size = (400, 400)  class GameCanvas(FigureCanvas):     def __init__(self, parent=None, width=5, height=4, dpi=100):         fig = Figure(figsize=(width, height), dpi=dpi)          self.axes = fig.gca()         self.init_figure()          FigureCanvas.__init__(self, fig)         self.setParent(parent)          timer = QtCore.QTimer(self)         timer.timeout.connect(self.update_figure)         timer.start(10)      def gen_frame(self):         return np.random.randint(0,0xfffff,size)      def init_figure(self):         self.img = self.axes.imshow(self.gen_frame())      def update_figure(self):         self.img.set_data(self.gen_frame())         self.draw()  class ApplicationWindow(QtWidgets.QMainWindow):     def __init__(self):         QtWidgets.QMainWindow.__init__(self)         self.main_widget = QtWidgets.QWidget(self)          dc = GameCanvas(self.main_widget, width=5, height=4, dpi=100)         self.setCentralWidget(dc)      def fileQuit(self):         self.close()      def closeEvent(self, ce):         self.fileQuit()  app = QtWidgets.QApplication(sys.argv) appw = ApplicationWindow() appw.show() sys.exit(app.exec_()) 

One thing you should be careful with is that imshow computes the image normalization on the first frame. In the subsequent frames it's calling set_data so the normalization stays the same. If you want to update it you can call imshow instead (probably slower). Or you could just fix it manually with vmin and vmax in the first imshow call and provide properly normalized frames.

Answers 4

Given you talked about using widespread modules, here's a proof of concept using OpenCV. It runs pretty fast here, up to 250-300 generated frames per second. It's nothing too fancy, just to show that maybe if you're not using any plotting feature matplotlib shouldn't really be your first choice.

import sys                                                                                  import time                                                                                 import numpy as np                                                                          import cv2                                                                                   if sys.version_info >= (3, 3):                                                                  timer = time.perf_counter                                                               else:                                                                                           timer = time.time                                                                        def f(x, y):                                                                                    return np.sin(x) + np.cos(y)                                                             # ESC, q or Q to quit                                                                       quitkeys = 27, 81, 113                                                                      # delay between frames                                                                      delay = 1                                                                                   # framerate debug init                                                                      counter = 0                                                                                 overflow = 1                                                                                start = timer()                                                                              x = np.linspace(0, 2 * np.pi, 400)                                                          y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)                                            while True:                                                                                     x += np.pi / 15.                                                                            y += np.pi / 20.                                                                             cv2.imshow("animation", f(x, y))                                                             if cv2.waitKey(delay) & 0xFF in quitkeys:                                                       cv2.destroyAllWindows()                                                                     break                                                                                    counter += 1                                                                                elapsed = timer() - start                                                                   if elapsed > overflow:                                                                          print("FPS: {:.01f}".format(counter / elapsed))                                             counter = 0                                                                                 start = timer()                                                                                                 
Read More

Thursday, April 21, 2016

py2exe suddenly no longer working. No module named _view

Leave a Comment

Running an exe compiled in py2exe is now giving me this error:

C:\Users\digiholic\git\universalSmashSystem\main.exe\zipextimporter.py:82: RuntimeWarning: import display: No module named _view (ImportError: No module named _view) C:\Users\digiholic\git\universalSmashSystem\main.exe\zipextimporter.py:82: RuntimeWarning: import draw: No module named _view (ImportError: No module named _view) C:\Users\digiholic\git\universalSmashSystem\main.exe\zipextimporter.py:82: RuntimeWarning: import image: No module named _view (ImportError: No module named _view) C:\Users\digiholic\git\universalSmashSystem\main.exe\zipextimporter.py:82: RuntimeWarning: import pixelcopy: No module named _view (ImportError: No module named _view) C:\Users\digiholic\git\universalSmashSystem\main.exe\zipextimporter.py:82: RuntimeWarning: import transform: No module named _view (ImportError: No module named _view) 

I did not modify my py2exe file since the last working build, nor have I made any significant changes to my Python installation. I have modified code, which must be causing this issue, but the error message is giving me no information on how to fix it. What could cause this issue?

I have put import pygame._view at the top of my main.py script and it is not helping. I do not reference any system fonts, all fonts used in my code are .ttf files in my package.

EDIT: Searched more. import re is not working either.

2 Answers

Answers 1

The solution is to add import pygame._view to the top of your main source file. Any of the packagers should work after that.

Try to do so. Some similar question was already asked in the past.

Please check also Pygame to exe display module error [duplicate] and Opening an EXE of my Pygame program gives me import errors

IF you look at the second answer the problem was in the "font" usage. Maybe you did something similar :-) Try it out and let us know.

Unfortunately I am not personally using pygame module :-( but I guess for the defined _view you have to use the import as you did correctly :-)

Hope this solve your query :-) Have a nice day.

Answers 2

This is looking like a PYTHONPATH issue. You need to verify that all of the locations where these modules are located are either in the development directory itself or in your search path for Python.

You can do a:

print sys.path 

to see what is in your search path and validate those modules are in it. It is possible something changed it. Once you verify that, you can add the missing paths using PYTHONPATH.

Read More