最终效果:
完整视频:
pygame简单实现菜单
Code:
settings.py
RES=WIDTH,HEIGHT=800,600
FPS=60
main.py
import pygame as pg
from settings import *
import sys
class Game:
def __init__(self):
pg.init()
self.screen=pg.display.set_mode(RES)
self.clock=pg.time.Clock()
self.DOWN_KEY,self.UP_KEY=False,False
self.x,self.y=260,200
def update(self):
pg.display.flip()
self.clock.tick(FPS)
pg.display.set_caption(f'{self.clock.get_fps():.1f}')
def draw(self):
self.screen.fill('black')
self.cursor()
self.text("aaaaa", (255,255,255), (300,200))
self.text("bbbb", (255,255,255), (300,300))
self.text("cccc", (255,255,255), (300,400))
def text(self,text,color,pos):
font=pg.font.Font('8-BIT WONDER.TTF', 35)
img=font.render(text,True,color)
self.screen.blit(img, pos)
def cursor(self):
if self.DOWN_KEY and 200<=self.y<400:
self.y+=100
self.DOWN_KEY=False
if self.UP_KEY and 400>=self.y>200:
self.y-=100
self.UP_KEY=False
self.text("x", "red", (self.x,self.y))
def events(self):
for event in pg.event.get():
if event.type==pg.QUIT:
pg.quit()
sys.exit()
if event.type==pg.KEYDOWN:
if event.key==pg.K_DOWN:
self.DOWN_KEY=True
if event.key==pg.K_UP:
self.UP_KEY=True
def run(self):
while True:
self.events()
self.update()
self.draw()
if __name__ == "__main__":
game=Game()