pygame.draw.line invalid syntax? - python

So, I'm following a tutorial which currently has me building the following for a quick look at drawing using pygame functions.
import pygame, sys
from pygame.locals import *
pygame.init() #has to be called before any other pygame functions
#setup the window
DISPLAYSURF = pygame.display.set_mode((500,400), 0, 32)
pygame.display.set_caption('Drawing')
#colors
black = (0, 0, 0, 0)
white = (255, 255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
BLUE = (0, 0, 255)
#draw on the surface object
DISPLAYSURF.fill(white)
pygame.draw.polygon(DISPLAYSURF, green, ((146,0), (291,106), (236,277),
(56,277), (0,106))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(DISPLAYSURF, BLUE,(120,60), (60,120))
pygame.draw.line(DISPLAYSURF, BLUE,(60,120), (120,120), 4)
pygame.draw.circle(DISPLAYSURF, BLUE, (300,500), 20, 0)
pygame.draw.ellipse(DISPLAYSURF, red, (300, 250, 40, 80), 1)
pygame.draw.rect(DISPLAYSURF, red, (200,150,100,50))
pixObj = pygame.pixelarray(DISPLAYSURF)
pixObj[480][380] = black
pixObj[482][382] = black
pixObj[484][384] = black
pixObj[486][386] = black
pixObj[488][388] = black
del pixObj
#run game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
My problem is that in attempting to run this code, I get an invalid syntax error pointing to the first pygame.draw.line. If this is somehow a typo, I'll be kinda surprised, I retyped those lines several times to make sure they were correct, even double checked the docs to make sure that was still the valid syntax. Any ideas?

Focusing on that line:
pygame.draw.polygon(DISPLAYSURF, green, ((146,0), (291,106), (236,277),
(56,277), (0,106))
Let's make some changes to it, that take valid syntax to valid syntax.
pygame.draw.polygon(DISPLAYSURF, green, ((), (), (), (), ())
pygame.draw.polygon(DISPLAYSURF, green, ()
pygame.draw.polygon(
There are more open parentheses than closing.
If the following lines are correct, you should remove an open paren after "green".

Related

My pygame code is running horribly slow, how can I fix it?

So I'm trying to make tetris in pygame, and it was running really slow. I isolated the function that draws everything and even that is running really slow, how can I fix this? (And by running I mean I get a black screen and the desired images just load slowly from the bottom over the course of several minutes.)
P.S. There are some unused variables because I was too lazy to comment them out, but I don't imagine a couple variables make a big difference
import random
import time
import pygame
pygame.init()
win=pygame.display.set_mode((420, 840))
clock= pygame.time.Clock()
score= 0
level= 0
lines= 0
field= [[1]*10 for _ in range(22)]
run= True
play= True
setState= False
t= 48
frameCounter= 0
font= pygame.font.SysFont('arial', 30)
def drawWin():
tempY= 40
for y in range(2 ,22):
tempX= 10
for x in field[y]:
if(x==1):
win.fill((255, 255, 255), (tempX, tempY, 40, 40))
pygame.draw.rect(win, (0, 0, 255), (tempX, tempY, 40, 40), 5)
tempX+=40
tempY+=40
pygame.draw.rect(win, (255, 255, 255), (10, 40, 400, 800), 2)
text= font.render('Score: '+ str(score)+ '\nLevel: '+ str(level), 1, (255, 255, 255))
while True:
drawWin()
for event in pygame.event.get():
if event.type== pygame.QUIT:
break
time.sleep(1)
clock.tick(t)
pygame.quit()
Try adding pygame.display.update() to the end of your while loop
I've had a similar issue running Pygame before :))
Simple fix, forgot the update display command for pygame.

How to make an empty shape in pygame?

i wanted to draw a circle in pygame that is empty, i mean you should see behind surface through it.
i wrote a code that find all the colored pixels in a surface and empty their coordinates in the other surface.
def draw_empty(surf1, surf2, pos):
"""makes surf2 pixels empty on surf1"""
pixobj2 = pygame.PixelArray(surf2)
empty = []
for x in range(len(pixobj2)):
for y in range(len(pixobj2[x])):
if pixobj2[x][y]!=0:
empty.append((x,y))
del pixobj2
pixobj1 = pygame.PixelArray(surf1)
for pix in empty:
pixobj1[pix[0]+pos[0]][pix[1]+pos[1]] = 0
del pixobj1
window = pygame.display.set_mode((600, 600))
white_surf = pygame.surface.Surface((600, 600))
white_surf.fill((255, 255, 255))
circle_surf = pygame.surface.Surface((50, 50))
pygame.draw.circle(circle_surf, (1, 1, 1), circle_surf.get_rect().center, 25)
pic = pygame.image.load('pic.png')
pic = pygame.transform.scale(pic, (600, 600))
done = False
while not done:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
draw_empty(white_surf, circle_surf, (200, 200))
window.blit(pic, (0, 0))
window.blit(white_surf, (0, 0))
pygame.display.update()
pygame.time.Clock().tick(60)
i expected to see background picture through that circle but the circle i just black, is this even possible to do that? can somebody help me with this?
P.S.
by empty, i mean like a hole in my front surface
Just use the draw() function:
pygame.draw.circle(Surface, color, pos, radius, width=0)
width represents the size of the circumference curve. When it is 0, the circle is solid. If you set it to 1, the edge will be only one pixel wide (an empty circle).
edit: to draw a circle with a sprite, you can use this code†:
import pygame
import pygame.gfxdraw
IMG = pygame.Surface((30, 30), pygame.SRCALPHA)
pygame.gfxdraw.aacircle(IMG, 15, 15, 14, (0, 255, 0))
pygame.gfxdraw.filled_circle(IMG, 15, 15, 14, (0, 255, 0))
class img(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = IMG
self.rect = self.image.get_rect(center=(150, 200))
†Credit for code goes to dunker_wanderer
You can draw the shape the same way you would if it had a color or surface image, and then just set the fill to a transparent color using:
empty = (255,255,255,0)
surface.fill(empty)
You will have to figure out how to add this to your code without breaking it, or rewrite it but, first you will need to make a set with three numbers
white = (255, 255, 255)
next use the function
pygame.draw.rect(canvas_name, set_name, (100, 100, 100, 100))
last use
pygame.display.flip()
#Initializes pygame import pygame, random, sys, time, math pygame.init()
#Creates screen screen = pygame.display.set_mode((400, 350)) pygame.display.set_caption("Game")
#Initializes screen running = True while running: pass
#Colors screen white = (255, 255, 255) screen.fill(white)
#Draws rectangle num1 = random.randrange(0, 255) num2 = random.randrange(0, 255) num3 = random.randrange(0, 255)
color = (num1, num2, num3) pygame.draw.rect(screen, color, pygame.Rect(100, 100, 60, 60), )
pygame.display.flip()
#Made by and only by the kid genius Nathan

How to let pygame text input detect the key in Pygame? [duplicate]

This question already has answers here:
How can I create a text input box with Pygame?
(5 answers)
Closed 5 years ago.
I'm doing a project that using Python and Pygame. I want to ask some question about the key in Pygame.
Thank you Shubhitgarg. I use his/her suggestions(use pygame_textinput), it succeed. Now I want to change the text input position with pressed an enter, but it can't detect the enter. How can I fix it? My real code:
# installing package
import pygame
from pygame import *
import pygame_textinput
pygame.init()
# colour settings
red = (255, 0, 0)
green = (0, 255, 0)
grass_green = (112, 173, 71)
blue = (0, 0, 255)
yellow = (255, 255, 0)
white = (255, 255, 255)
black = (0, 0, 0)
# screen settings
window = pygame.display.set_mode((680, 600))
window.fill(grass_green)
pygame.display.flip()
# font settings
default_font = pygame.font.get_default_font()
big_font = pygame.font.Font(default_font, 96)
font_a = pygame.font.Font(default_font, 50)
font_b = pygame.font.Font(default_font, 30)
font_c = pygame.font.Font(default_font, 18)
# text input settings
textinput = pygame_textinput.TextInput("freeansbold.ttf", 96, True, black, white, 400, 35)
# timer
start = pygame.time.get_ticks()
# text
please_guess_a_number = font_a.render("Please guess a number. ", 1, white)
text_range = font_c.render("from to", 1, white)
wrong_bigger = font_b.render("Sorry, You haven’t guess it rightly. Please try again.(The answer must be bigger.)", 1, white)
wrong_smaller = font_b.render("Sorry, You haven’t guess it rightly. Please try again.(The answer must be smaller.)", 1, white)
correct = font_b.render("Congratulations! You guess it correctly!!", 1, white)
# game
ask_you_to_set_range_1 = True
ask_you_to_set_range_2 = False
while True:
if ask_you_to_set_range_1:
window.blit(please_guess_a_number, (60, 80))
pygame.draw.rect(window, yellow, [60, 200, 230, 300])
pygame.draw.rect(window, yellow, [390, 200, 230, 300])
window.blit(text_range, (10, 550))
pygame.display.flip()
while True:
events = pygame.event.get()
textinput.update(events)
window.blit(textinput.get_surface(), (110, 300))
pygame.display.flip()
if ask_you_to_set_range_2:
while True:
events = pygame.event.get()
textinput.update(events)
window.blit(textinput.get_surface(), (440, 300))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if ask_you_to_set_range_1 and event.key == pygame.K_KP_ENTER:
ask_you_to_set_range_1 = False
ask_you_to_set_range_2 = True
if textinput.update(event):
num1 = textinput.get_text()
text1 = big_font.render(num1, 1, black)
window.blit(text1, (110, 300))
Can anyone teach me to solve it?
You see this https://github.com/ShubhitGarg/pygame-text-input .
You can import this and use the text_input class and blit it on the same or next page
Use this
textinput = pygame_textinput.TextInput()
while True:
screen.fill((225, 225, 225))
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
# Feed it with events every frame
textinput.update(events)
# Blit its surface onto the screen
screen.blit(textinput.get_surface(), (10, 10))
pygame.display.update()

Pygame transparency issue

I have a rather confusing problem. I currently have a countdown and I would ideally have the text from the countdown to be somewhat transparent (say 50% or so)
pygame.init()
surface = pygame.display.set_mode((0,0))
fontObj = pygame.font.Font('freesansbold.ttf', 600)
textSurfaceObj = fontObj.render("3", True, (255, 255, 255))
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (surface.get_width() / 2, surface.get_height() / 2)
pygame.mouse.set_visible(False)
while True:
surface.fill(255, 255, 255)
pygame.display.update()
time = str(datetime.datetime.now())
filename = 'photos/' + time.replace(' ', '_') + '.jpg'
for i in xrange(3, 0, -1):
surface.fill(WHITE)
textSurfaceObj = fontObj.render(str(i), True, (255, 0, 0)
surface.blit(textSurfaceObj, textRectObj)
pygame.display.update()
pygame.time.wait(1000)
pygame.display.update()
pygame.time.wait(100);
surface.fill(WHITE)
pygame.display.update()
I've tried putting in surface.set_alpha(50) but that doesnt seem to do anything. Any suggestions are very welcome!
In pygame you must set a background color for antialiased text if you want it to use a color key (which allows you to render transparent text). To get the result you want you just need to match the background color to the surface color, in this case white. The below code (starting right after the for i in ...) worked for me:
surface.fill(WHITE)
textSurfaceObj = fontObj.render(str(i), True, (255, 0, 0),WHITE)
textSurfaceObj.set_alpha(50)
surface.blit(textSurfaceObj,(0,0))
pygame.display.update()
pygame.time.wait(500)
Edit: I did a little digging as to what's going on here, and this mailing list post details the backend properties that cause this for anyone interested.

Segmentation fault 11 when running pygame in Sublime Text 3

I am using Python 3.4.0 and I have Mac OSX 10.9.2. I have the following code saved as sublimePygame in Sublime Text.
import pygame, sys
from pygame.locals import *
pygame.init()
#set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Drawing')
# set up the colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
# Draw on surface object
DISPLAYSURF.fill(WHITE)
pygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4)
pygame.draw.line(DISPLAYSURF, BLUE, (120, 60), (60, 120))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120, 120), 4)
pygame.draw.circle(DISPLAYSURF, BLUE, (300, 50), 20, 0)
pygame.draw.ellipse(DISPLAYSURF, RED, (300, 250, 40, 80), 1)
pygame.draw.rect(DISPLAYSURF, RED, (200, 150, 100, 50))
pixObj = pygame.PixelArray(DISPLAYSURF)
pixObj[480, 380] = BLACK
pixObj[482, 382] = BLACK
pixObj[48, 384] = BLACK
pixObj[486, 386] = BLACK
pixObj[488, 388] = BLACK
del pixObj
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
pygame.display.update()
I ran the code in my terminal and the python window opened for a second and then closed.
I got this error in the terminal.
Traceback (most recent call last):
File "sublimePygame", line 29, in <module>
pixObj[480, 380] = BLACK
IndexError: invalid index
Segmentation fault: 11
I checked the pygame documentation and my code seemed ok. I googled the error and Segmentation Error 11 seems to be a bug in python but I read that it was fixed in Python 3.4.0.
Does Anyone know what went wrong?
Thanks in advance!
Edit: Marius found the bug in my program, however when I run it it opens a blank Python window and not what it was supposed top open. Does anyone know why this happened?
I can see a definite bug in your code, but I'm not sure if that's causing a segmentation fault, which is a more serious error.
The bug in your code is that you create a 400x300 window:
DISPLAYSURF = pygame.display.set_mode((400, 300))
And then try to set colour values for pixels that are outside the bounds of that window
pixObj[480, 380] = BLACK
Again, this might not be causing the segmentation fault.
Your blank python window problem is here:
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
pygame.display.update()
pygame.display.update() will only be executed if QUIT is activated. You need to remove some of the indents so that it is outside the for loop, but within the while loop.

Categories

Resources