Python always print just one value [duplicate] - python

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How do I detect collision in pygame?
(5 answers)
Closed 12 months ago.
I run the codes below. The computer always print "win" if (500 < mouse_x < 700) and (100 < mouse_y < 211) (player = 2) and "lose" if (100 < mouse_x < 300) and (100 < mouse_y < 221) (player = 1). I had checked the "player" and it works fine, but the "computer" always print value "2". If I change "if computer <= 10" to "else": "computer" always print value "1"
This is my codes:
import pygame
from random import randint
def draw_floor():
screen.blit(floor, (floorrunning, 453))
screen.blit(floor, (floorrunning + 800, 453))
pygame.init()
bg = pygame.image.load("background.png")
screen = pygame.display.set_mode((800,500))
GREY = (120, 120, 120)
WHITE = (255, 255, 255)
BLANK = (0, 0, 0)
floor = pygame.image.load("quangcaobanthan.png")
floorrunning = 0
xucxac1 = pygame.image.load("nan1.png")
xucxac2 = pygame.image.load("nan1_2.png")
xucxac3 = pygame.image.load("nan1_3.png")
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
youlose = pygame.image.load("youlose.png")
youlose_rect = youlose.get_rect(center = (400, 250))
youwin = pygame.image.load("youwin.png")
youwin_rect = youwin.get_rect(center = (400, 250))
running = True
replay = True
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
game_font = pygame.font.SysFont("04B_19.ttf", 40)
player = 0
def ketqua():
ketqua1_infor = game_font.render(str(ketqua1), True, (0,0,0))
ketqua1_rect = (190, 334)
screen.blit(ketqua1_infor, ketqua1_rect)
ketqua2_infor = game_font.render(str(ketqua2), True, (0,0,0))
ketqua2_rect = (390, 334)
screen.blit(ketqua2_infor, ketqua2_rect)
ketqua3_infor = game_font.render(str(ketqua3), True, (0,0,0))
ketqua3_rect = (590, 334)
screen.blit(ketqua3_infor, ketqua3_rect)
while running:
screen.blit(bg,(0,0))
mouse_x, mouse_y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and replay == False:
replay = True
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (100 < mouse_x < 300) and (100 < mouse_y < 221):
player = 1
if (500 < mouse_x < 700) and (100 < mouse_y < 211):
player = 2
if 10 < computer <= 18:
computer = 1
if computer <= 10:
computer = 2
if xucxac1_rect == (41, 300) and xucxac2_rect == (241, 300) and xucxac3_rect == (441, 300):
if computer == player:
print("win")
else:
print("lose")
pygame.draw.rect(screen, WHITE, (100, 100, 200, 121))
pygame.draw.rect(screen, WHITE, (500, 100, 200, 111))
pygame.draw.rect(screen, WHITE, (277, 0, 240, 100))
screen.blit(pygame.image.load("tai.png"), (100,100))
screen.blit(pygame.image.load("xiu.png"), (500,100))
screen.blit(pygame.image.load("start.png"), (275, -60))
draw_floor()
floorrunning -= 0.5
if floorrunning <= -800:
floorrunning = 0
if replay == False:
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
if replay:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (141 < mouse_x < 241) and (300 < mouse_y < 400):
xucxac1_rect = (41, 300)
if (341 < mouse_x < 441) and (300 < mouse_y < 400):
xucxac2_rect = (241, 300)
if (541 < mouse_x < 641) and (300 < mouse_y < 400):
xucxac3_rect = (441, 300)
if (277 < mouse_x < 527) and (0 < mouse_y < 79):
replay = False
pygame.draw.rect(screen, GREY, (50, 290, 700, 120))
pygame.draw.circle(screen, GREY, (195, 350), 48)
pygame.draw.circle(screen, GREY, (395, 350), 48)
pygame.draw.circle(screen , GREY,(595, 350), 48)
screen.blit(xucxac1, xucxac1_rect)
screen.blit(xucxac2, xucxac2_rect)
screen.blit(xucxac3, xucxac3_rect)
else:
pygame.draw.rect(screen, BLANK, (50, 290, 700, 120))
ketqua()
pygame.display.flip()
pygame.quit()

Related

Python always print one value when i run anyways

it always prints "2", please help me
this is my codes:
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
if 10 < computer <= 18:
computer = 1
elif computer <= 10:
computer = 2
this is all my code:
import pygame
from random import randint
def draw_floor():
screen.blit(floor, (floorrunning, 453))
screen.blit(floor, (floorrunning + 800, 453))
pygame.init()
bg = pygame.image.load("background.png")
screen = pygame.display.set_mode((800,500))
GREY = (120, 120, 120)
WHITE = (255, 255, 255)
floor = pygame.image.load("quangcaobanthan.png")
floorrunning = 0
xucxac1 = pygame.image.load("nan1.png")
xucxac2 = pygame.image.load("nan1_2.png")
xucxac3 = pygame.image.load("nan1_3.png")
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
youlose = pygame.image.load("youlose.png")
youlose_rect = youlose.get_rect(center = (400, 250))
youwin = pygame.image.load("youwin.png")
youwin_rect = youwin.get_rect(center = (400, 250))
running = True
replay = True
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
if 10 < computer <= 18:
computer = 1
elif computer <= 10:
computer = 2
game_font = pygame.font.SysFont("04B_19.ttf", 40)
player = 0
def ketqua():
ketqua1_infor = game_font.render(str(ketqua1), True, (0,0,0))
ketqua1_rect = (190, 334)
screen.blit(ketqua1_infor, ketqua1_rect)
ketqua2_infor = game_font.render(str(ketqua2), True, (0,0,0))
ketqua2_rect = (390, 334)
screen.blit(ketqua2_infor, ketqua2_rect)
ketqua3_infor = game_font.render(str(ketqua3), True, (0,0,0))
ketqua3_rect = (590, 334)
screen.blit(ketqua3_infor, ketqua3_rect)
while running:
screen.blit(bg,(0,0))
mouse_x, mouse_y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and replay == False:
replay = True
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (100 < mouse_x < 300) and (100 < mouse_y < 221):
player = 1
if (500 < mouse_x < 700) and (100 < mouse_y < 211):
player = 2
if xucxac1_rect == (41, 300) and xucxac2_rect == (241, 300) and xucxac3_rect == (441, 300):
screen.blit(youwin, youwin_rect)
screen.blit(youlose, youlose_rect)
pygame.draw.rect(screen, WHITE, (100, 100, 200, 121))
pygame.draw.rect(screen, WHITE, (500, 100, 200, 111))
pygame.draw.rect(screen, WHITE, (277, 0, 240, 100))
screen.blit(pygame.image.load("tai.png"), (100,100))
screen.blit(pygame.image.load("xiu.png"), (500,100))
screen.blit(pygame.image.load("start.png"), (275, -60))
print(computer)
draw_floor()
floorrunning -= 0.5
if floorrunning <= -800:
floorrunning = 0
if replay == False:
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
if replay:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (141 < mouse_x < 241) and (300 < mouse_y < 400):
xucxac1_rect = (41, 300)
if (341 < mouse_x < 441) and (300 < mouse_y < 400):
xucxac2_rect = (241, 300)
if (541 < mouse_x < 641) and (300 < mouse_y < 400):
xucxac3_rect = (441, 300)
if (277 < mouse_x < 527) and (0 < mouse_y < 79):
replay = False
pygame.draw.rect(screen, GREY, (50, 290, 700, 120))
pygame.draw.circle(screen, GREY, (195, 350), 48)
pygame.draw.circle(screen, GREY, (395, 350), 48)
pygame.draw.circle(screen , GREY,(595, 350), 48)
screen.blit(xucxac1, xucxac1_rect)
screen.blit(xucxac2, xucxac2_rect)
screen.blit(xucxac3, xucxac3_rect)
ketqua()
pygame.display.flip()
pygame.quit()
Your code runs randomly.
That means there is a change that you get 1 day, one week, one month the same answer.
Assuming that you have from random import randint
Then you could thy this:
def execute():
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
if 10 < computer <= 18:
computer = 1
elif computer <= 10:
computer = 2
return computer
histogram = [0,0,0]
for _ in range(100):
c = execute()
histogram[c] += 1
print("Times we got computer==1: {}".format(histogram[1]))
print("Times we got computer==2: {}".format(histogram[2]))
You should have something like this:
Times we got computer==1: 49
Times we got computer==2: 51
So randint is being used well...

Start screen won't work how to fix problem?

The issue that I am having is every time I run my game the start screen won't work right, for example, all click on the GO button and it won't let me start my game yet everything seems correct and in place, if anyone can please help it would very much be appreciated
import pygame, random
from time import sleep
pygame.init()
# music/sounds
CarSound = pygame.mixer.Sound("image/CAR+Peels+Out.wav")
CarSound_two = pygame.mixer.Sound("image/racing01.wav")
CarSound_three = pygame.mixer.Sound("image/RACECAR.wav")
CarSound_four = pygame.mixer.Sound("image/formula+1.wav")
Crowds = pygame.mixer.Sound("image/cheer_8k.wav")
Crowds_two = pygame.mixer.Sound("image/applause7.wav")
Crowds_three = pygame.mixer.Sound("image/crowdapplause1.wav")
music = pygame.mixer.music.load("image/Led Zeppelin - Rock And Roll (Alternate Mix) (Official Music Video).mp3")
pygame.mixer.music.play(-1)
bg = pygame.image.load('image/Crowds.png')
clock = pygame.time.Clock()
# Setting up our colors that we are going to use
GREEN = (20, 255, 140)
GREY = (210, 210, 210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACKWHITE = (96, 96, 96)
BLACK = (105, 105, 105)
RGREEN = (0, 66, 37)
LIGHT_RED = (200, 0, 0)
BRIGHT_GREEN = (0, 255, 0)
DARK_BLUE = (0, 0, 139)
BLUE = (0, 0, 255)
NAVY = (0, 0 , 128)
DARK_OLIVE_GREEN = (85, 107, 47)
YELLOW_AND_GREEN = (154, 205, 50)
SCREENWIDTH = 400
SCREENHEIGHT = 500
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
Icon = pygame.image.load("image/redca_iconr.png")
pygame.display.set_icon((Icon))
# This will be a list that will contain all the sprites we intend to use in our game.
# all_sprites_list = pygame.sprite.Group()
# player
playerIMG = pygame.image.load("image/red_racecar.png")
playerX = 280
playerY = 450
playerCar_position = 0
# player2
playerIMG_two = pygame.image.load("image/greencar.png")
playerX_two = 150
playerY_two = 450
playerCar_position_two = 0
# player3
playerIMG_three = pygame.image.load("image/Orangecar.png")
playerX_three = 60
playerY_three = 450
playerCar_position_three = 0
# player4
playerIMG_four = pygame.image.load("image/yellowcar2.png")
playerX_four = 210
playerY_four = 450
playerCar_position_four = 0
# Putting cars to the screen
def player(x, y):
screen.blit(playerIMG, (x, y))
def player_two(x, y):
screen.blit(playerIMG_two, (x, y))
def player_three(x, y):
screen.blit(playerIMG_three, (x, y))
def player_four(x, y):
screen.blit(playerIMG_four, (x, y))
finish_text = ""
font2 = pygame.font.SysFont("Papyrus", 65)
players_finished = 0
placings = ["1st", "2nd", "3rd", "4th"]
smallfont = pygame.font.SysFont("Papyrus", 15)
normalfont = pygame.font.SysFont("arial", 25)
differntfont = pygame.font.SysFont("futura", 25)
def score(score):
text = smallfont.render("Race cars passing: " + str(score), True, RGREEN)
screen.blit(text, [145, 490])
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def message_display(text):
largText = pygame.font.Font("Mulish-Regular.ttf", 15)
TextSurf, TextRect = text_objects(text, largText)
TextRect.center = ((SCREENWIDTH / 1), (SCREENHEIGHT / 1))
screen.blit(TextSurf, TextRect)
text_two = normalfont.render("Start new game?", 5, (0, 66, 37))
time_to_blit = None
screen.blit(bg, (0, 0))
pygame.display.flip()
Here is my button the Quit button works fine its just the GO button that when pressed won't let me start my game my only guess could be unless I placed something in the wrong place?
def button(msg, x, y, w, h, iC, aC, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(click)
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen, iC, (x , y, w, h))
if click[0] == 1 and action != None:
if action == "Play":
game_loop()
elif action == "Quit":
pygame.quit()
quit()
else:
pygame.draw.rect(screen, aC, (x , y, w, h))
if 260 + 100 > mouse[0] > 260 and 40 + 50 > mouse[1] > 40:
pygame.draw.rect(screen, BLUE, (260, 40, 100, 50))
else:
pygame.draw.rect(screen, DARK_BLUE, (260, 40, 100, 50))
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects(msg, newtext)
textReact.center = ((x + (100 / 2))), (y + (h / 2))
screen.blit(textSurf, textReact)
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects("QUIT!", newtext)
textReact.center = ((260 + (100 / 2))), (40 + (50 / 2))
screen.blit(textSurf, textReact)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(YELLOW_AND_GREEN)
text = normalfont.render("Super Racer!", 8, (0, 66, 37))
screen.blit(text, (165 - (text.get_width() / 5), 100))
button("GO!", 60, 40, 100, 50, RED, LIGHT_RED, "Play")
button("QUIT!", 260, 40, 100, 50, BLUE, DARK_BLUE, "Quit")
pygame.display.update()
clock.tick(15)
# Main game loop
def game_loop():
run = True
while run:
# Drawing on Screen
screen.fill(BLACK)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
# Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 20)
text = font.render("Finish line!", 2, (150, 50, 25))
screen.blit(text, (185 - (text.get_width() / 2), 45))
screen.blit(bg, (-236, -34))
screen.blit(bg, (-236, -5))
screen.blit(bg, (-235, 140))
screen.blit(bg, (-235, 240))
screen.blit(bg, (-235, 340))
screen.blit(bg, (340, -60))
screen.blit(bg, (340, -60))
screen.blit(bg, (335, 5))
screen.blit(bg, (335, 130))
screen.blit(bg, (335, 230))
screen.blit(bg, (335, 330))
screen.blit(bg, (333, 330))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
CarSound.play()
playerCar_position = -0.5
if keys[pygame.K_q]:
playerCar_position = 0.5
if keys[pygame.K_2]:
CarSound_two.play()
playerCar_position_two = -0.5
if keys[pygame.K_w]:
playerCar_position_two = 0.5
if keys[pygame.K_3]:
CarSound_three.play()
playerCar_position_three = -0.5
if keys[pygame.K_e]:
playerCar_position_three = 0.5
if keys[pygame.K_4]:
CarSound_four.play()
playerCar_position_four = -0.5
if keys[pygame.K_r]:
playerCar_position_four = 0.5
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
finish_line_rect = pygame.Rect(50, 70, 235, 32)
game_intro()
score(players_finished)
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
inish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
Crowds.play()
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
Crowds_three.play()
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
Crowds_two.play()
if (players_finished and finish_text):
font = pygame.font.SysFont("Impact", 15)
text = font.render(finish_text, 5, (0, 66, 37))
screen.blit(text, (90 - (text.get_width() / 2), -2))
if (finish_text):
font = pygame.font.SysFont("Impact", 20)
text = font.render('Game Over!!!', 5, (0, 66, 37))
screen.blit(text, (250 - (text.get_width() / 5), -2))
if players_finished == 4:
time_to_blit = pygame.time.get_ticks() + 5000
if time_to_blit:
print(screen.blit(text_two, (130, 460)))
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = None
pygame.quit()
In the game loop, you're not calling the screen update. You also need to render the cars in the loop.
# Main game loop
def game_loop():
print(".......GAME LOOP........")
global playerCar_position,playerCar_position_two,playerCar_position_three,playerCar_position_four
global playerY,playerY_two,playerY_three,playerY_four,playerX,playerX_two,playerX_three,playerX_four
finish_line_rect = pygame.Rect(50, 70, 235, 32)
finish_text = ""
players_finished = 0
time_to_blit = 0
run = True
while run:
# Drawing on Screen
screen.fill(BLACK)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
# Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 20)
text = font.render("Finish line!", 2, (150, 50, 25))
screen.blit(text, (185 - (text.get_width() / 2), 45))
#.............
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
# CarSound.play()
playerCar_position = -0.5
if keys[pygame.K_q]:
playerCar_position = 0.5
if keys[pygame.K_2]:
# CarSound_two.play()
playerCar_position_two = -0.5
if keys[pygame.K_w]:
playerCar_position_two = 0.5
if keys[pygame.K_3]:
# CarSound_three.play()
playerCar_position_three = -0.5
if keys[pygame.K_e]:
playerCar_position_three = 0.5
if keys[pygame.K_4]:
# CarSound_four.play()
playerCar_position_four = -0.5
if keys[pygame.K_r]:
playerCar_position_four = 0.5
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
finish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
# Crowds.play()
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
# Crowds_three.play()
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
# Crowds_two.play()
if (players_finished and finish_text):
print("ft:", finish_text)
font = pygame.font.SysFont("Impact", 15)
textrect = font.render(finish_text, False, (0, 66, 37))
print('x', (SCREENWIDTH - text.get_width()) / 2)
screen.blit(textrect, (0,0))
screen.blit(textrect, ((SCREENWIDTH - textrect.get_width()) // 2, -5))
if (finish_text):
font = pygame.font.SysFont("Impact", 20)
text = font.render('Game Over!!!', 5, (0, 66, 37))
screen.blit(text, (250 - (text.get_width() / 5), -2))
if players_finished == 4:
time_to_blit = pygame.time.get_ticks() + 5000
if time_to_blit:
screen.blit(text_two, (130, 460))
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = 0
pygame.display.update()
clock.tick(60)
game_intro()
score(players_finished)
pygame.quit()
Try:
if action == "Play":
game_loop()
return
I think there is something wrong with your indentation of the code. You have pygame.quit() at the global level. So, you run pygame.init(), then define some functions, then pygame.quit()
Comment out the pygame.quit() line and see what happens.

Starting a game when countdown is over pygame

So I have this code that's my main game:
def game():
running = True
import pygame, sys
import random
import math as m
mainClock = pygame.time.Clock()
pygame.init()
pygame.font.init
pygame.display.set_caption('Ping Pong')
SCREEN = width, height = 900,600
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0,0,0)
speed = [4,4]
font = pygame.font.Font('freesansbold.ttf', 32)
score = 0
score = str(score)
font.size(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen = pygame.display.set_mode(SCREEN, 0,32)
height1 = height/4
score = int(score)
ball = pygame.Rect(width/2, height/2, 50,50)
player = pygame.Rect(0,(height/2),25,height1)
player_1 = pygame.Rect(width - 25,(height/2),25,height1)
font1 = pygame.font.Font('freesansbold.ttf', 32)
score1 = 0
score1 = str(score)
font1.size(score1)
font1.set_bold(True)
text1 = font1.render(score1, True, white)
score1 = int(score1)
textRect1 = text1.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
up = False
down = False
up_1 = False
down_1 = False
RED = (255,0,0)
particles = []
while running:
color = (192,192,192)
# clear display #
screen.fill((0,0,0))
screen.blit(text, textRect)
screen.blit(text1, textRect1)
bx = ball.centerx
by = ball.centery
particles.append([[bx, by],[random.randint(0,20) / 10 - 1, -1], random.randint(4,6)])
for particle in particles:
particle[0][0] += particle[1][0]
particle[0][1] += particle[1][1]
particle[2] -= 0.1
particle[1][1] += 0.1
pygame.draw.circle(screen, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
if particle[2] <= 0:
particles.remove(particle)
if up == True:
player.y -= 5
if down == True:
player.y += 5
if up_1 == True:
player_1.y -= 5
if down_1 == True:
player_1.y += 5
if player.top < 0 :
player.y = 0
if player.bottom > height:
player.bottom = height
if player_1.top < 0 :
player_1.y = 0
if player_1.bottom > height :
player_1.bottom = height
for i in range(-90,(height + 130), 120):
rectangle = pygame.Rect((width/2), i, 13, 60)
pygame.draw.rect(screen, (255,255,255), rectangle)
pygame.draw.rect(screen,(191, 224, 255),player)
pygame.draw.rect(screen,(191, 224, 255),player_1)
color = (192,192,192)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
pygame.draw.rect(screen,color,ball, 3)
import time
ball.x += speed[0]
ball.y += speed[1]
if ball.top < 0 or ball.bottom > height:
speed[1] = -speed[1]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
pygame.draw.circle(screen, (r,b,g), [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
dab = random.randint(0,1)
if ball.left < 0 :
font = pygame.font.Font('freesansbold.ttf', 32)
score1 = int(score1)
score1 += 1
score1 = str(score1)
font.set_bold(True)
text1 = font.render(score1, True, white)
textRect1 = text.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
screen.blit(text1, textRect1)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
if ball.right > width:
font = pygame.font.Font('freesansbold.ttf', 32)
score = int(score)
score += 1
score = str(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen.blit(text, textRect)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
# event handling #
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_s:
down = True
if event.key == K_w:
up = True
if event.key == K_UP:
up_1 =True
if event.key == K_ESCAPE:
running = False
if event.key == K_DOWN:
down_1 = True
if event.type == KEYUP:
if event.key == K_s:
down = False
if event.key == K_w:
up = False
if event.key == K_UP:
up_1 = False
if event.key == K_DOWN:
down_1 = False
if ball.colliderect(player_1):
dab = random.randint(0,1)
if dab == 1:
speed[1] = -speed[1]
speed[0] = -speed[0]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
if ball.colliderect(player):
speed[0] = -speed[0]
speed[0] = random.randint(4,6)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
# update display #
pygame.display.update()
mainClock.tick(60)
and I have a menu screen that displays some options. Only button_1 works.:
def main_menu():
while True:
white = (255,255,255)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
screen.fill((0,0,0))
button_1 = pygame.Rect(width/2, (height/2), width/2, 50)
button_1.centerx = width/2
button_2 = pygame.Rect(width/2, height/1.5, width/2, 50)
button_2.centerx = width/2
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
#draw_text('Start!', font, (255, 255, 255), screen, button_1.centerx, button_1.centery)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
text1 = font.render('Start!', True, white)
textRect1 = text1.get_rect()
textRect1.center = (button_1.centerx, button_1.centery)
screen.blit(text1, textRect1)
mx, my = pygame.mouse.get_pos()
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
options()
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
clock.tick(60)
How do I make it so that after button_1 is pressed, there's a 3,2,1 countdown on the screen, and then the game starts?
In order to do the countdown, you import the time module:
import time
...then you need a for loop, with a step -1, counting down from 3 to 1. Inside the for loop, print the numbers and sleep one second, using the time module:
for a in range(3,0,-1):
print(a)
time.sleep(1)
After this for loop, you put the rest of your code.

How would I create another incoming rectangle?

I have made a little game with your player being a car and a car coming at you. I want there to be two cars coming at you but i'm not sure how to start this. I know I need another surface and Rect value for it as it needs to be able to check collision. Also, is there anyway I could get two cars coming at once from one side or is this not possible?
import time, pygame, random
import math
pygame.init()
#First Variables
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (100, 255, 100)
ORANGE = (255, 140, 0)
YELLOW = (155, 135, 12)
white = (255, 255, 255)
GOLD = (255, 215, 0)
screenwidth = 500
screenheight = 500
Lines = True
Space = True
color = random.sample(range(250), 3)
doris = []
i = []
x = 247
y = - 20
y1 = 40
y2 = 100
y3 = 160
y4 = 220
y5 = 280
y6 = 340
y7 = 400
y8 = 460
#Display and caption
win = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption('Lil cary')
clock = pygame.time.Clock()
#Load in images
bkg = pygame.image.load('BG.jpg')
#Actual player class
class player():
def __init__(self):
self.color = (12, 124, 134)
self.vel = 5
self.grassdamage = 0
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(center = (200, 390))
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
self.damage5 = False
self.damage6 = False
self.damage7 = False
self.damage8 = False
self.dead = False
def draw (self, win):
#pygame.draw.rect(win, (self.color), (self.x, self.y, self.width, self.height))
win.blit(self.image, self.rect.topleft)
def moveback(self):
if self.rect.y < 390 and self.rect.y >= 0:
self.rect.y += 10
def grass(self):
if self.rect.x > -10 and self.rect.x < 150:
self.grassdamage += 1
self.vel = 3
elif self.rect.x > 300 and self.rect.x < 500:
self.vel =3
self.grassdamage += 1
else:
self.vel = 5
def grasshealth(self):
if self.grassdamage == 100:
self.damage1 = True
elif self.grassdamage == 200:
self.damage2 = True
elif self.grassdamage == 300:
self.damage3 = True
elif self.grassdamage == 400:
self.damage4 = True
elif self.grassdamage == 500:
self.damage5 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 700:
self.damage7 = True
elif self.grassdamage == 800:
self.damage8 = True
self.dead = True
def death(self):
if self.dead == True:
exit()
#Text Setup
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
#Drawing damage bar
def drawbar ():
if player.damage1 == True and car.damage1 == False or car.damage1 == True:
pygame.draw.rect(win, (GOLD), (50, 50, 25, 25))
if player.damage2 == True and car.damage1 == False or car.damage1 == True:
pygame.draw.rect(win, (GOLD), (50, 75, 25, 25))
if car.damage1 == True and player.grassdamage <= 200:
player.grassdamage = 201
if player.damage3 == True and car.damage2 == False or car.damage2 == True:
pygame.draw.rect(win, (GOLD), (50, 100, 25, 25))
if player.damage4 == True and car.damage2 == False or car.damage2 == True:
pygame.draw.rect(win, (GOLD), (50, 125, 25, 25))
if car.damage2 == True and player.grassdamage <= 400:
player.grassdamage = 401
if player.damage5 == True and car.damage3 == False or car.damage3 == True:
pygame.draw.rect(win, (GOLD), (50, 150, 25, 25))
if player.damage6 == True and car.damage3 == False or car.damage3 == True:
pygame.draw.rect(win, (GOLD), (50, 175, 25, 25))
if car.damage3 == True and player.grassdamage <= 600:
player.grassdamage = 601
if player.damage7 == True and car.damage4 == False or car.damage4 == True:
pygame.draw.rect(win, (GOLD), (50, 200, 25, 25))
if player.damage8 == True and car.damage4 == False or car.damage4 == True:
pygame.draw.rect(win, (GOLD), (50, 225, 25, 25))
raise SystemExit ('YOU LOST')
if car.damage4 == True and player.grassdamage <= 800:
player.grassdamage = 800
pygame.draw.rect(win, (0,0,0), (50, 50, 25, 200), 3)
Text = pygame.font.Font('freesansbold.ttf', 20)
TextSurf, TextRect = text_objects("Damage", Text)
TextRect.center = ((65), (30))
win.blit(TextSurf, TextRect)
class car():
def __init__(self):
self.color = random.sample(range(250), 3)
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(topleft = (175, -100))
self.carvel = random.randrange(5, 10)
self.damage = 0
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
def draw(self, win):
#pygame.draw.rect(win,(self.color),self.rect)
win.blit(self.image, self.rect.topleft)
def move(self):
if self.rect.y < 530:
self.rect.y += self.carvel
else:
self.rect.y = -100
self.color = random.sample(range(250), 3)
self.carvel = random.randrange(8, 10)
def collision_check(self, another_object):
if self.rect.colliderect(another_object):
print('collison')
self.rect.y = -100
self.damage += 1
def cardamage(self):
if self.damage == 1:
self.damage1 = True
player.damage1 = True
player.damage2 = True
if self.damage == 2:
self.damage2 = True
player.damage3 = True
player.damage4 = True
if self.damage == 3:
self.damage3 = True
player.damage5 = True
player.damage6 = True
if self.damage == 4:
self.damage4 = True
player.damage7 = True
player.damage8 = True
#Putting variables to the classes
player = player()
car = car()
#Main drawing function
def redrawgamewindow():
win.blit(bkg, (0, 0))
pygame.draw.rect(win, (0, 0, 0), (150, 0, 200, 500))
pygame.draw.rect(win, (255, 255, 255), (x, (y), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y1), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y2), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y3), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y4), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y5), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y6), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y7), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y8), 10, 30))
player.draw(win)
car.draw(win)
player.grasshealth()
car.cardamage()
player.grass()
player.death()
car.collision_check(player.rect)
car.move()
drawbar()
pygame.display.update()
#MAINLOOP
run = True
while run:
#Making background and FPS
clock.tick(80)
#Quiting Funciton
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
#Scrolling the lines
if Lines:
y += player.vel
y1 += player.vel
y2 += player.vel
y3 += player.vel
y4 += player.vel
y5 += player.vel
y6 += player.vel
y7 += player.vel
y8 += player.vel
if Lines:
if y >= 500:
y = -40
if y1 >= 500:
y1 = -40
if y2 >= 500:
y2 = -40
if y3 >= 500:
y3 = -40
if y4 >= 500:
y4 = -40
if y5 >= 500:
y5 = -40
if y6 >= 500:
y6 = -40
if y7 >= 500:
y7 = -40
if y8 >= 500:
y8 = -40
#User input
keys = pygame.key.get_pressed()
#Boost controller
if keys[pygame.K_SPACE]:
start_time = time.time()
if player.rect.y > 200:
player.rect.y -= 9
Space = True
else:
player.moveback()
end_time = time.time()
#Left movement
if keys[pygame.K_LEFT] and player.rect.x > 150:
player.rect.x -= 5
if keys [pygame.K_LEFT] and player.rect.x <= 150:
if player.rect.x > 0:
player.rect.x -=5
#Right movement
if keys[pygame.K_RIGHT] and player.rect.x < 300:
player.rect.x += 5
if keys[pygame.K_RIGHT]and player.rect.x >= 300:
if player.rect.x < 500 - player.rect.width:
player.rect.x += 5
#Grass and grass damage
#MAIN DRAW RECALL
redrawgamewindow()
Your code is pretty-much there already. Instead of just creating one Car, make a list of Cars. Where the car is draw, collided, etc., now do that for every car in the list. After some event, say 3 seconds pass, add another car to the list.
For example:
car = Car()
car_list = [ car ] # start with one car
car_add_time = 0
Now it's easy to add more cars:
while run:
#Making background and FPS
clock.tick(80)
### Add another car after 3 seconds
time_now = pygame.time.get_ticks()
if ( time_now - car_add_time > 3000 ):
new_car = Car()
car_list.append( new_car )
car_add_time = time_now
Re-drawing the car list:
def redrawgamewindow():
# ...
for car in car_list:
car.draw(win)
player.grasshealth()
for car in car_list:
car.cardamage()
player.grass()
player.death()
for car in car_list:
car.collision_check(player.rect)
car.move()
One other thing you need to do, is change the Car class to start the car in a random x-position (but still within the road (... or not)). Since the code just recycles the car back to -100 when it collides or moves off-screen, it also needs to be re-positioned here too.
For example:
class Car():
ROAD_LEFT = 150 # this is a rough guess on the correct spot
ROAD_RIGHT = 300
def __init__(self):
# ...
x_pos = random.randrange( Car.ROAD_LEFT, Car.ROAD_RIGHT )
self.rect = self.image.get_rect(topleft = ( x_pos, -100) )

How can I have different 'menus' in pygame with python 3.6 without a bunch of if statements? [duplicate]

This question already has answers here:
tips on Adding/creating a drop down selection box in pygame
(1 answer)
trying creating dropdown menu pygame, but got stuck
(1 answer)
Closed 1 year ago.
I am creating a pygame project called 'bitcoin clicker', a simple game where you click and, in turn, receive bitcoin. You can then go to an exchange 'tab' to exchange bitcoin for money, then you can buy upgrades to mine bitcoin idle.
I am not having issues with getting it to work, however, I have programmed enough to know that continual 'stairs' of if statements are not very efficient. Here is my code:
import decimal
import math
import pygame
pygame.init()
width = 900
height = 600
frame_rate = 60
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
scene = 0
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bitcoin Clicker")
clock = pygame.time.Clock()
background = pygame.image.load('trump.png')
trumpImg = pygame.image.load('170907-wilson-trump-tease_h1fks0.png')
bitcoinImg = pygame.image.load('Bitcoin image.png')
dollarBillImg = pygame.image.load('100DollarBill.jpg')
pentiumImg = pygame.image.load('KL Intel Pentium A80501.jpg')
cents = 0
exchange_rate = 18901.83
click_value = 0.000001
pentium_price = .00001 * exchange_rate
passive_value = 0.0
bitcoin = 0.0
coin_x = (width / 2 - 100)
coin_y = (height / 2 - 100)
def coin(x, y):
gameDisplay.blit(bitcoinImg, (x, y))
def text_objects(string, font):
textSurface = font.render(string, True, white)
return textSurface, textSurface.get_rect()
def text(string, x, y, size):
largeText = pygame.font.Font('freesansbold.ttf', size)
TextSurf, TextRect = text_objects(string, largeText)
TextRect.center = (x, y)
gameDisplay.blit(TextSurf, TextRect)
def clicker():
global scene
global bitcoin
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
x_squared = (mouse_x - coin_x - 100) ** 2
y_squared = (mouse_y - coin_y - 100) ** 2
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if math.sqrt(x_squared + y_squared) < 100:
bitcoin += click_value
if mouse_x < 60 and mouse_y < 35:
scene = 1
if 65 < mouse_x < 155 and mouse_y < 30:
scene = 2
text("Store", 30, 15, 20)
text("Exchange", 115, 16, 17)
coin(coin_x, coin_y)
def store():
global cents
global scene
global pentium_price
global passive_value
pentium_markup = 1.1
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if mouse_x < 60 and mouse_y < 35:
scene = 0
if 65 < mouse_x < 155 and mouse_y < 30:
scene = 2
if 75 < mouse_x < 300 and 150 < mouse_y < 375:
if cents >= pentium_price:
passive_value += .000001
cents -= pentium_price
pentium_price *= pentium_markup
gameDisplay.blit(pentiumImg, (75, 150))
b = decimal.Decimal(str(pentium_price))
text(str(round(b, 2)), 125, 400, 25)
text("Shop", width / 2, 25, 25)
text("Clicker", 35, 15, 18)
text("Exchange", 115, 16, 17)
def exchange():
global scene
global bitcoin
global cents
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if mouse_x < 60 and mouse_y < 35:
scene = 1
if 65 < mouse_x < 155 and mouse_y < 200:
scene = 0
if 200 < mouse_x < 700 and 200 < mouse_y < 409:
cents += bitcoin * exchange_rate
bitcoin = 0
gameDisplay.blit(dollarBillImg, (width / 2 - 250, 200))
text("Clicker", 100, 15, 18)
text("Store", 30, 15, 20)
def game_loop():
global bitcoin
global scene
global passive_value
global pentium_price
global cents
running = True
while running:
bitcoin += passive_value/frame_rate
gameDisplay.blit(background, (0,0))
# clicker scene
if scene == 0:
clicker()
# store scene
if scene == 1:
store()
# exchange scene
if scene == 2:
exchange()
a = decimal.Decimal(str(bitcoin))
c = decimal.Decimal(str(cents))
text("B " + str(round(a, 6)), width / 2, 100, 25)
text("$ " + str(round(c, 2)), width / 2, 125, 25)
pygame.display.update()
clock.tick(frame_rate)
game_loop()
pygame.quit()
quit()
Is there any way I can simplify the following code? Specifically the many if statements. I deleted some code from the functions to make it easier to see. (each function is a separate 'tab' that renders a different screen based on user input)
def clicker():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if math.sqrt(x_squared + y_squared) < 100:
bitcoin += click_value
if mouse_x < 60 and mouse_y < 35:
scene = 1
if 65 < mouse_x < 155 and mouse_y < 30:
scene = 2
def store():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if mouse_x < 60 and mouse_y < 35:
scene = 0
if 65 < mouse_x < 155 and mouse_y < 30:
scene = 2
if 75 < mouse_x < 300 and 150 < mouse_y < 375:
if cents >= pentium_price:
passive_value += .000001
cents -= pentium_price
pentium_price *= pentium_markup
def exchange():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if mouse_x < 60 and mouse_y < 35:
scene = 1
if 65 < mouse_x < 155 and mouse_y < 200:
scene = 0
if 200 < mouse_x < 700 and 200 < mouse_y < 409:
cents += bitcoin * exchange_rate
bitcoin = 0

Categories