python - Printing small rectangles to the screen in a for loop. (pygame) -


i'm trying code print small rectangles on screen in pygame of loops, having trouble. have solved parts of code looks ugly , preforms bad:

x = 0 y = 0  y_row in range(60):     y = y + 10     pygame.draw.rect(screen, green, [x, y, 5, 5], 0)     x_row in range(70):         pygame.draw.rect(screen, green, [x, y, 5, 5], 0)         x = x + 10     x = 0 

to start of, not believe have assign value x , y if can figure out how implement value of y_row , x_row @ x , y's places instead, increases 1, should increase 10, can implement instead.

another problem code leaves blank row @ top, because had add y = y + 10 above pygame draw, otherwise printed 1 rectangle there witch made more visible.

the template i'm using code working can find here.

drawing 4,200 rectangles screen every 60th of second significant task cpu. suspect pygame.draw.rect() function high-level , calls not batched pygame making sub-optimal, there hint in documentation (https://www.pygame.org/docs/ref/draw.html#pygame.draw.rect) surface.fill(color, rect=none, special_flags=0) can hardware accelerated , may faster option if you're filling rectangles.

note: code examples below pseudo ... means need fill in gaps.

you need 1 call pygame.draw.rect per iteration of loop not 2 have now, e.g.

for row in rows:     y = ...     col in cols:         x = ...         ... draw rect ... 

one easy win performance not draw that's off-screen, test x, y coordinates before rendering, e.g:

screen_width = 800 screen_height = 600  ...     y = y += 10     if y > screen_height:         break      ...         x += 10         if x > screen_width:             break          ... draw block ... 

the same approach used (with continue) implement offset (e.g starting offset_x, offset_y value) rectangles negative x, y values not rendered (the test not x < 0 however, x < -block_size).

there's nothing wrong calculating x , y values loop index doing, it's useful have index (for example index [row][col] might give location of data tile in 2d matrix representing game tiles). calculate x, y values myself indexes using multiplier (this solves blank first row issue):

block_size = 10  row in ...     y = row * block_size     if y > screen_height:         break      col in ...         x = col * block_size          if x > screen_width:             break          ... draw block ... 

if you're using python2 might consider using xrange predefine loop ranges improve performance (though imagine small amount , optimization testing performance difference key). example:

rows = xrange(60) cols = xrange(70)  row in rows:     ...     cols in cols:         ... draw block ... 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -