How to create a border in Pygame -


i know how create border in pygame stop user controlled object exiting screen. right now, have python prints text when user controlled object has come near 1 of 4 sides.

here code far.

import pygame pygame.locals import * pygame.init()  #display stuff  screenx = 1000 screeny = 900 screen = pygame.display.set_mode((screenx,screeny)) pygame.display.set_caption('block runner') clock = pygame.time.clock() image = pygame.image.load('square.png')     #color stuff red = (255,0,0) green = (0,255,0) blue = (0,0,255) white = (255,255,255) black = (0,0,0)   #variables x_blocky = 50 y_blocky = 750 blocky_y_move = 0 blocky_x_move = 0    #animations def blocky(x_blocky, y_blocky, image): screen.blit(image,(x_blocky,y_blocky))  #game loop  game_over = false while not game_over:     event in pygame.event.get():         if event.type == pygame.quit:             pygame.quit()             quit()          if event.type == pygame.keydown:             if event.key == pygame.k_up:                 blocky_y_move = -3         if event.type == pygame.keyup:             if event.key == pygame.k_up:                 blocky_y_move = 0          if event.type == pygame.keydown:             if event.key == pygame.k_down:                 blocky_y_move = 3         if event.type == pygame.keyup:             if event.key == pygame.k_down:                 blocky_y_move = 0          if event.type == pygame.keydown:             if event.key == pygame.k_right:                 blocky_x_move = 3         if event.type == pygame.keyup:             if event.key == pygame.k_right:                 blocky_x_move = 0          if event.type == pygame.keydown:             if event.key == pygame.k_left:                 blocky_x_move = -3         if event.type == pygame.keyup:             if event.key == pygame.k_left:                 blocky_x_move = 0          if x_blocky > 870 or x_blocky < 0:             print(' x border')           if y_blocky > 750 or y_blocky < 2:             print(' y border')        y_blocky += blocky_y_move     x_blocky += blocky_x_move       screen.fill(white)     blocky(x_blocky, y_blocky, image)     pygame.display.update() clock.tick(60) 

don't use integers store position. use rect.

so instead of

x_blocky = 50 y_blocky = 750 

use

blocky_pos = pygame.rect.rect(50, 750) 

now can use

blocky_pos.move_ip(blocky_x_move, blocky_y_move) 

to move object.

after moving, can call clamp/clamp_ip ensure blocky_pos rect inside screen.

blocky_pos.clamp_ip(screen.get_rect()) 

also, don't need define basic colors yourself, use pygame.color.color('red') example.

i suggest use pygame.key.get_pressed() pressed keys see how move object instead of creating 1000 lines of event handling code.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -