Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I am trying to make a game that has a cookie in the middle and if you click that cookie, your points increase
My problem is that once i display the points and increase it, the numbers overlap
import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((1000,500))
pygame.display.set_caption("Cookie Clicker")
clock = pygame.time.Clock()
screen.fill("White")
font1 = pygame.font.Font("c:/Users/oreni/OneDrive/Masaüstü/sprites/Minecraft. ttf", 25)
font2 = pygame.font.Font("c:/Users/oreni/OneDrive/Masaüstü/sprites/Minecraft.ttf", 30)
font3 = pygame.font.Font("c:/Users/oreni/OneDrive/Masaüstü/sprites/Minecraft.ttf", 35)
font4 = pygame.font.Font("c:/Users/oreni/OneDrive/Masaüstü/sprites/Minecraft. ttf", 40)
font5 = pygame.font.Font("c:/Users/oreni/OneDrive/Masaüstü/sprites/Minecraft.ttf", 45)
font6 = pygame.font.Font("c:/Users/oreni/OneDrive/Masaüstü/sprites/Minecraft.ttf", 50)
noc = 0
# Texts
nuofco = font4.render(str(noc), False, "Black")
nuofco_r = nuofco.get_rect(center = (237,80))
# Drawn Rects
cookie = pygame.draw.ellipse(screen, "Brown", (110,150,250,250))
pygame.draw.rect(screen, "Black", pygame.Rect(475,0,25,500))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if cookie.collidepoint(event.pos):
noc += 1
screen.blit(nuofco,nuofco_r)
pygame.display.update()
clock.tick(60)
After calculating the new number I think you need to redraw everything on the screen including the background. Because everything you draw on the screen is actually drawn on top of the previous one. And everything overlaps when the background is not drawn.
And also in the main loop, the usually recommended order is to take input, update variables, draw everything. It would be better for you if you first calculate everything that needs to be calculated and then draw what needs to be drawn.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 10 months ago.
Improve this question
MAIN CODE
i dont really know why i keep on getting tuple errors the code looks fine
its just the loop part of my game for now, this is it
import pygame
# important window variables
WIDTH, HEIGHT = 900, 500
WIN = WIDTH, HEIGHT
SCREEN = pygame.display.set_mode((WIN))
pygame.display.set_caption('SPACE GAME')
WHITE = (0,0,0)
# display function (what shows up on the screen)
def display():
WIN.fill(WHITE)
pygame.display.update()
# main function/loop function
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
display()
pygame.quit()
if __name__ == '__main__':
main()
I'm confident this is the issue (though without the real error traceback, I could be wrong.)
The basic issue is that you set the value of WIN as a tuple
i.e.
WIN = BASE, HEIGHT
Then in the display() function, you do the following:
WIN.fill(WHITE)
Which is what I think the error is. WIN being a tuple,
has no fill method. What I think you wanted to use is
SCREEN.fill(WHITE)
I took a gander at the documentation (as I don't know pygame),
and it confirms that: pygame.display.set_mode((WIN))
returns a Surface object which does have a fill()
method.
So, in conclusion:
# important window variables
WIDTH, HEIGHT = 900, 500
WIN = WIDTH, HEIGHT
SCREEN = pygame.display.set_mode((WIN))
pygame.display.set_caption('SPACE GAME')
WHITE = (0,0,0)
# display function (what shows up on the screen)
def display():
SCREEN.fill(WHITE)
pygame.display.update()
# main function/loop function
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
display()
pygame.quit()
if __name__ == '__main__':
main()
This question already has answers here:
Why is nothing drawn in PyGame at all?
(2 answers)
Closed 1 year ago.
I'm fairly new to pymunk and I wanted to make physics engine for my future games, there's just a small problem, My code won't draw the circle that pygame is trying to visualize. Here's my code.
import pygame
import pymunk
import sys
def create_item(space):
body = pymunk.Body(1, 100, body_type = pymunk.Body.DYNAMIC)
body.position = (450, 50)
shape = pymunk.Circle(body, 80)
space.add(body, shape)
return shape
def draw_items(items):
for item in items:
pygame.draw.circle(screen, item_color, item.body.position, 80)
def quit():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
def display_update():
screen.fill(bg_color)
clock.tick(FPS)
space.step(1/60)
pygame.display.flip()
# Constructor
pygame.init()
# Constants and Variables
WIDTH = 900
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
FPS = 60
clock = pygame.time.Clock()
# Colors
bg_color = 30, 30, 40
item_color = 200, 200, 200
# Pymunk Variables
space = pymunk.Space()
space.gravity = (0, 500)
items = []
items.append(create_item(space))
# Loops
def main():
running = True
while running:
quit()
display_update()
draw_items(items)
main()
I don't really know what the problem is here, it doesn't give me an error or something like that and I only get a clean blank canvas with my bg color.(also sorry for the bad comments)
You have to draw the objects before updating the display
def main():
running = True
while running:
quit()
screen.fill(bg_color)
draw_items(items)
pygame.display.flip()
clock.tick(FPS)
space.step(1/60)
You are actually drawing on a Surface object. If you draw on the Surface associated to the PyGame display, this is not immediately visible in the display. The changes become visibel, when the display is updated with either pygame.display.update() or pygame.display.flip().
The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
limit frames per second to limit CPU usage
This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
How do I detect collision in pygame?
(5 answers)
Closed 2 years ago.
code responsible for creating the buttons.
def __init__(self, str, x, y):
font = pygame.font.Font(None, 60)
text = font.render(str, 0, (0, 0, 0))
textpos = text.get_rect()
self.surface = pygame.Surface((300, textpos.height + 10))
self.surface.fill((0, 255, 0))
#self.surface.set_colorkey((0, 255, 0))
self.surfacepos = self.surface.get_rect()
textpos.centerx = self.surfacepos.centerx
textpos.centery = self.surfacepos.centery
self.surface.blit(text, textpos)
self.surfacepos.centerx = x
self.surfacepos.top = y
code that checks where the mouse was pressed
if event.type == MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
if credito.surfacepos.collidepoint(pos):
there are multiple buttons and they all work fine, except for the last one that's placed close to the bottom of the screen. More specifically, only a small area below the actual text seems to work.
picture showing the area that's actually working:
i already moved this button to other positions and it worked, but i wonder what's causing this
Edit: i also found out that, if i simply remove the ` from the string, the collision seems to stop working completely, plus if i create another button and move this new one to the same position, it works fine. i think it might be related to the strings given somehow.
code of the generation of the button objects.
play = Button("JOGAR", new_screen.get_rect().centerx, new_screen.get_rect().centery)
new_screen.blit(play.surface, play.surfacepos)
help = Button("INSTRUÇÕES", new_screen.get_rect().centerx, new_screen.get_rect().centery+100)
new_screen.blit(help.surface, help.surfacepos)
credito = Button("CRÉDITOS", new_screen.get_rect().centerx, new_screen.get_rect().centery+200)
new_screen.blit(credito.surface, credito.surfacepos)
back = Button("VOLTAR", -300, -300)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
So, I just made this weird program due to boredom called the "flex machine" (which is still being worked on), that shows some simple animation, games & projects I made one by one. In the first bit, it will ask you whether you want to see it but when you say yes, it will show syntax error on elif. Can someone help me solve this and explain what's the problem that caused it?
Code:
import pygame
import random
import time
# Begin the Flex
print("Yo! What's Up?")
time.sleep(2)
print("So uh since you have opened this, I will tell you what it's about")
time.sleep(2)
print("My creator got hella bored one day and found himself just scrolling through his phone too much. The only option he had was to create me")
time.sleep(2)
answer = input("So, here I am. Shall we continue? Yes or No ")
if answer == "Yes":
print("Let's watch this cool animation that my owner gave me!")
# Snowflake.py
# Initialize the game engine
pygame.init()
BLACK = [0, 0, 0]
WHITE = [255, 255, 255]
BLUE = [0, 0, 255]
# Set the height and width of the screen
SIZE = [400, 400]
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Snow Animation")
# Create an empty array
snow_list = []
# Loop 50 times and add a snow flake in a random x,y position
for i in range(50):
x = random.randrange(0, 400)
y = random.randrange(0, 400)
snow_list.append([x, y])
clock = pygame.time.Clock()
# Loop until the user clicks the close button.
done = False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# Set the screen background
screen.fill(BLACK)
# Process each snow flake in the list
for i in range(len(snow_list)):
# Draw the snow flake
pygame.draw.circle(screen, WHITE, snow_list[i], 2)
# Move the snow flake down one pixel
snow_list[i][1] += 9
# If the snow flake has moved off the bottom of the screen
if snow_list[i][1] > 400:
# Reset it just above the top
y = random.randrange(-50, -10)
snow_list[i][1] = y
# Give it a new x position
x = random.randrange(0, 400)
snow_list[i][0] = x
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
clock.tick(20)
pygame.quit()
elif answer == "No":
print("Well, that's fine")
time.sleep(2)
print("Cya next time, have a good day")
else:
print("Please enter yes or no.")
In your code, you have an if statement, an elif statement, and an else statement. You've indented the code within the elif and else statements properly, but seem to have forgotten to indent the code within if statement. Indents are required in python, so you must indent the code in the if statement.
I've indented the code within the statement, so it should work fine now:
import pygame
import random
import time
# Begin the Flex
print("Yo! What's Up?")
time.sleep(2)
print("So uh since you have opened this, I will tell you what it's about")
time.sleep(2)
print("My creator got hella bored one day and found himself just scrolling through his phone too much. The only option he had was to create me")
time.sleep(2)
answer = input("So, here I am. Shall we continue? Yes or No ")
if answer == "Yes":
print("Let's watch this cool animation that my owner gave me!")
# Snowflake.py
# Initialize the game engine
pygame.init()
BLACK = [0, 0, 0]
WHITE = [255, 255, 255]
BLUE = [0, 0, 255]
# Set the height and width of the screen
SIZE = [400, 400]
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Snow Animation")
# Create an empty array
snow_list = []
# Loop 50 times and add a snow flake in a random x,y position
for i in range(50):
x = random.randrange(0, 400)
y = random.randrange(0, 400)
snow_list.append([x, y])
clock = pygame.time.Clock()
# Loop until the user clicks the close button.
done = False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# Set the screen background
screen.fill(BLACK)
# Process each snow flake in the list
for i in range(len(snow_list)):
# Draw the snow flake
pygame.draw.circle(screen, WHITE, snow_list[i], 2)
# Move the snow flake down one pixel
snow_list[i][1] += 9
# If the snow flake has moved off the bottom of the screen
if snow_list[i][1] > 400:
# Reset it just above the top
y = random.randrange(-50, -10)
snow_list[i][1] = y
# Give it a new x position
x = random.randrange(0, 400)
snow_list[i][0] = x
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
clock.tick(20)
pygame.quit()
elif answer == "No":
print("Well, that's fine")
time.sleep(2)
print("Cya next time, have a good day")
else:
print("Please enter yes or no.")
you have to use elif only when if condition is above !
For instance .
if (a == 1):
//do something
elif (a == 1):
//do something
you can't do this :
elif (a == 1):
//do something
to fix your problem remove your first elif by if!
if answer == "No":
print("Well, that's fine")
time.sleep(2)
print("Cya next time, have a good day")
else:
print("Please enter yes or no.")
Check your indentation between the first pygame.init() to the elif.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
No idea why the syntax is invalid, anyone have an idea? It says the two bottom lines of code in particular have invalid syntax. This is probably embarassingly simple to fix, so please have mercy on my soul.
I haven't tried anything because it's an extremely basic problem and I'm probably just bad at coding
import pygame
import sys
import time
pygame.init()
(width, height) = (1920, 1080)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('fat')
background_colour = pygame.Color('white')
color = pygame.Color('dodgerblue2')
font = pygame.font.Font(None, 100)
clock = pygame.time.Clock()
running = True
text = ''
while running:
# handle events and user-input
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if (event.key >= pygame.K_SPACE and event.key <= pygame.K_z):
# Append key-stroke's character
text += event.unicode
elif (event.key == pygame.K_BACKSPACE):
text = text[:-1]
elif (event.key == pygame.K_RETURN):
#print("interpret(text) - NOT IMPLEMENTED")
text = ""
if len(text) > 20:
text = text[:-1]
# repaint the screen
screen.fill(background_colour)
txt_surface = font.render(text, True, color)
screen.blit(txt_surface, (50, 100))
response = font.render(Room.defaultprompt, True, color)
screen.blit((response,(80, 150))
clock.tick_busy_loop(60) # limit FPS
display.flip()
The code did, but no longer, takes what the user types and presents it onto the screen. It stopped working after I tried to make pygame draw another line of text. (btw I know that Room.defaultprompt is undefined but that's because the rest of the code just isn't in the post)
Looking closely to it, so an error on this line:
screen.blit((response,(80, 150))
When it should be:
screen.blit(response,(80, 150))
#ErikXIII's answer is little different