Last active
May 12, 2021 07:43
-
-
Save X-88/61716c04518e4d83894d9ceca9d0f48b to your computer and use it in GitHub Desktop.
Create Simple Button using Rect in pygame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame as pg | |
import sys, os, random | |
pg.init() | |
w = 600 | |
h = 800 | |
res = (w, h) | |
fontname = "/storage/emulated/0/fonts/clacon.ttf" | |
sndpath = "/storage/emulated/0/sfx/test.mp3" | |
efn = os.path.basename(sndpath[:-4]) | |
screen = pg.display.set_mode(res) | |
white = (255, 255, 255) | |
black = (0, 0, 0) | |
gray = (211, 211, 211) | |
silver = (192, 192, 192) | |
lime = (0, 255, 0) | |
blue = (0, 0, 255) | |
red = (255, 0, 0) | |
def loop(): | |
status = 'Ready' | |
i = w | |
running = True | |
clock = pg.time.Clock() | |
button1 = pg.Rect(4, 100, 150, 50) | |
button2 = pg.Rect(9, 105, 150, 50) | |
button3 = pg.Rect(4, 160, 150, 50) | |
button4 = pg.Rect(9, 165, 150, 50) | |
while running: | |
for event in pg.event.get(): | |
if event.type == pg.QUIT: | |
running = False | |
elif event.type == pg.MOUSEBUTTONDOWN and event.button == 1: | |
if button2.collidepoint(event.pos): | |
pg.mixer.music.load(sndpath) | |
pg.mixer.music.play(0) | |
status = 'Playing - ' + efn | |
if button4.collidepoint(event.pos): | |
pg.mixer.music.pause() | |
status = 'Stoped' | |
screen.fill(white) | |
pg.draw.rect(screen, gray, button1) | |
pg.draw.rect(screen, black, button2) | |
pg.draw.rect(screen, gray, button3) | |
pg.draw.rect(screen, black, button4) | |
font = pg.font.Font(fontname, 40) | |
bcaption = font.render('Play', True, lime, black) | |
bcaption2 = font.render('Stop', True, red, black) | |
text2 = font.render('Status: ' + status, True, blue) | |
font = pg.font.Font(fontname, 60) | |
screen.blit(bcaption, (55, 110)) | |
screen.blit(bcaption2, (55, 172)) | |
screen.blit(text2, (10, 40)) | |
tani = "Zephio - 2021, Belajar Pygame" | |
ani = font.render(tani, True, (0, random.randint(0, 255), random.randint(0, 255))) | |
i -= 1 | |
screen.blit(ani, (i, 220)) | |
pg.display.update() | |
clock.tick(20) | |
loop() | |
pg.quit() | |
sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment