当前位置:网站首页>[pygame Games] ce jeu "eat Everything" est fantastique? Tu manges tout? (avec code source gratuit)
[pygame Games] ce jeu "eat Everything" est fantastique? Tu manges tout? (avec code source gratuit)
2022-06-27 15:53:00 【- Salut! Chestnut!】
Préface
- Salut.!Je suis l'élève de Chestnut..Je ne l'ai pas vu depuis longtemps.!Je suis de retour.~

Qu'est - ce que j'écris pour vous aujourd'hui??!Hé! Hé!,Je n'ai pas écrit de code depuis si longtemps.,Les mains ne savent même pas taper.,Le Code ne frappe même pas.
C'est,Laisse - moi prendre mon temps.!Un peu de simplicité.(En fait, je n'ai aucune idée.,La dernière fois que j'ai écrit le dernier jeu de sniper invincible
C'est une petite adaptation du Code.,Paresseux,Parce que je ne sais pas quoi écrire.,Ne me frappe pas.jpg)
Quand je serai inspiré, je vous écrirai.,On s'entraîne.!Source d'amour,Peut - être la prochaine fois.!
Aujourd'hui, je vais vous apprendre à écrire un petit jeu simple.:《Mange tout.》Commençons tout de suite.
Tous les articles+ Le code source est à la fin de l'article public haoPrends - le.!

Texte
Cet article est basé surpygameÉcrivez un petit jeu avec une interface simple.!
Un.、Environnement opérationnel
1)Installation environnementale Python3、 Pycharm 、tkinter、PygameLa partie module n'est pas affichée avec le module lui - même..
(Installer le paquet si nécessaire、Code d'activation, etc. direct Je peux installer des réponses à vos questions en privé. ~)
Installation de bibliothèques tierces:pip install pygame Ou Avec source miroir pip install -i
https://pypi.douban.com/simple/ +Nom du module2)Matériel(Photos: La nourriture et les gens qui mangent )

J'ai l'impression que la nourriture ne correspond pas à la beauté d'une fille. ,Ha ha ha, Juste une seconde. , Vous pouvez changer les photos. !
2.、Procédure principale
import pygame,os,random
from pygame.locals import *
from pygame.sprite import *
def load_image(name):
fullname=os.path.join(os.path.join(os.path.split(os.path.abspath(__file__))[0],"filedata"),name)
image=pygame.image.load(fullname)
return image
def load_sound(name):
fullname=os.path.join(os.path.join(os.path.split(os.path.abspath(__file__))[0],"filedata"),name)
sound=pygame.mixer.Sound(fullname)
return sound
class Tip(Sprite):
def __init__(self,screen,fontrender,waitticks,pos):
super(Tip,self).__init__()
self.screen=screen
self.image=fontrender
self.rect=self.image.get_rect()
self.rates=0
self.waitticks=waitticks
self.rect.center=pos
def update(self):
self.rates+=1
if self.rates>=self.waitticks:
self.kill()
class Surface:
def __init__(self,screen):
self.screen=screen
self.image=load_image("eatingface.png")
self.rect=self.image.get_rect()
self.rect.center=self.screen.get_rect().center
self.speed=3.7
self.caneat=20
self.eat=self.caneat
self.moveUp=False
self.moveDown=False
self.moveLeft=False
self.moveRight=False
self.faceatleft=False
self.punch=0
def update(self):
if self.punch==0:
if self.moveUp and self.rect.top>0:
self.rect.centery-=self.speed
if self.moveDown and self.rect.bottom<HEIGHT:
self.rect.centery+=self.speed
if self.moveLeft and self.rect.left>0:
if not self.faceatleft:
self.faceatleft=True
self.image=pygame.transform.flip(self.image,True,False)
self.rect.centerx-=self.speed
if self.moveRight and self.rect.right<WIDTH:
if self.faceatleft:
self.faceatleft=False
self.image=pygame.transform.flip(self.image,True,False)
self.rect.centerx+=self.speed
else:
self.punched()
def blit(self):
self.screen.blit(self.image,self.rect)
def punched(self):
self.punch+=1
if self.punch>60:
self.punch=0
def eats(self,num):
self.eat+=num
if self.eat>=100:
self.eat=100
return "True"
elif self.eat<=0:
self.eat=0
return "False"
return "None"
def reset(self):
self.image=load_image("eatingface.png")
self.rect=self.image.get_rect()
self.rect.center=self.screen.get_rect().center
self.speed=3.7
self.eat=self.caneat
self.moveUp=False
self.moveDown=False
self.moveLeft=False
self.moveRight=False
self.faceatleft=False
self.punch=0
class Food(Sprite):
def __init__(self,screen,surface,tips,gameFont):
super(Food,self).__init__()
self.screen=screen
self.surface=surface
self.tips=tips
self.gameFont=gameFont
self.screenrect=self.screen.get_rect()
self.image=load_image("eatingfood.png")
self.rect=self.image.get_rect()
self.rectat=random.choice(["top","left","right","bottom"])
self.xspeed=round(random.uniform(1,2),2)
self.yspeed=round(random.uniform(1,2),2)
if self.rectat=="top":
self.rect.center=(random.randint(0,WIDTH),0)
elif self.rectat=="bottom":
self.rect.center=(random.randint(0,WIDTH),HEIGHT)
self.yspeed=-self.yspeed
elif self.rectat=="left":
self.rect.center=(0,random.randint(0,HEIGHT))
elif self.rectat=="right":
self.xspeed=-self.xspeed
self.rect.center=(WIDTH,random.randint(0,HEIGHT))
def update(self):
global toohungry,isfull
if self.surface.faceatleft:
if self.rect.left<self.surface.rect.left<=self.rect.right:
if self.surface.rect.top<self.rect.top<self.surface.rect.bottom or self.surface.rect.bottom>self.rect.bottom>self.surface.rect.top:
self.kill()
if self.surface.eats(2)=="True":
isfull=True
return
else:
if self.rect.right>self.surface.rect.right>=self.rect.left:
if self.surface.rect.top<self.rect.top<self.surface.rect.bottom or self.surface.rect.bottom>self.rect.bottom>self.surface.rect.top:
self.kill()
if self.surface.eats(2)=="True":
isfull=True
return
if collide_rect(self,self.surface):
self.surface.punched()
if self.surface.eats(-1)=="False":
toohungry=True
return
self.tips.add(Tip(self.screen,self.gameFont.render("Dizzy!",True,(255,255,255)),
60,self.surface.rect.center))
self.away()
self.rect.centerx+=self.xspeed
self.rect.centery+=self.yspeed
if self.rect.top>self.screenrect.height or self.rect.bottom<0:
self.kill()
elif self.rect.left>self.screenrect.width or self.rect.right<0:
self.kill()
def away(self):
self.xspeed=-self.xspeed
self.yspeed=-self.yspeed
WIDTH=700
HEIGHT=600
toohungry=False
isfull=False
def initmain():
pygame.init()
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Eater")
gameFont=pygame.font.SysFont("Arial",26,True)
fpstime=pygame.time.Clock()
surface=Surface(screen)
foods=Group()
tips=Group()
def mainit():
global toohungry,isfull
foods.empty()
tips.empty()
surface.reset()
rates=0
toohungry=False
isfull=False
while ((not isfull) and (not toohungry)):
fpstime.tick(100)
screen.fill((0,255,0))
screen.blit(gameFont.render("Full "+str(surface.eat)+"%",True,(0,0,0)),(2,2))
rates+=1
if rates%50==0:
foods.add(Food(screen,surface,tips,gameFont))
foods.draw(screen)
foods.update()
surface.blit()
surface.update()
tips.draw(screen)
tips.update()
for event in pygame.event.get():
if event.type==QUIT:
toohungry=True
isfull=True
elif event.type==KEYDOWN:
if event.key==K_RIGHT:
surface.moveRight=True
elif event.key==K_LEFT:
surface.moveLeft=True
elif event.key==K_UP:
surface.moveUp=True
elif event.key==K_DOWN:
surface.moveDown=True
elif event.key==K_SPACE:
surface.speed=5
elif event.type==KEYUP:
if event.key==K_RIGHT:
surface.moveRight=False
elif event.key==K_LEFT:
surface.moveLeft=False
elif event.key==K_UP:
surface.moveUp=False
elif event.key==K_DOWN:
surface.moveDown=False
elif event.key==K_SPACE:
surface.speed=3.5
pygame.display.flip()
notbreak=True
while notbreak:
screen.fill((0,255,0))
if toohungry and isfull:
screen.blit(gameFont.render("Esc To Exit!",True,(128,128,128)),(2,2))
elif toohungry:
screen.blit(gameFont.render("Too hungry!",True,(0,0,0)),(2,2))
elif isfull:
screen.blit(gameFont.render("Full!",True,(0,0,0)),(2,2))
screen.blit(gameFont.render("Space To Retry",True,(128,128,128)),(2,32))
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
__import__("sys").exit()
elif event.type==KEYUP:
if event.key==K_ESCAPE:
pygame.quit()
__import__("sys").exit()
elif event.key==K_SPACE:
notbreak=False
pygame.display.flip()
mainit()
mainit()
if __name__=="__main__":
initmain()Résumé
- Salut., C'est très simple. , Je ne vais pas le montrer. , Le bouton gauche de la souris se déplace tout le temps pour manger la nourriture tombée. !
GratuitBase de code source——
Petite compilation de messages privés06Ou cliquez sur la police bleue pour l'obtenir gratuitement!
Votre soutien est ma plus grande motivation.!!Souviens - toi de la troisième série.~mua Bienvenue à la lecture des articles précédents~
Recommandé dans certains articles de la période précédente ——
Projets1.5 PygamePetits jeux:Les Jeux botaniques ont vraiment“Poison.”?Je ne peux pas l'arrêter.~
Projets3.2 【PygamePetits jeux】Tout explose.、 Super bomber “Explosion”On y va., C'est ton enfance. ?
Résumé des articles——
Projets1.0 Python—2021 |Résumé des articles disponibles | Mise à jour continue,Ça suffit de lire ça
(Plus de détails+Le code source est résumé dans l'article.!!Bienvenue à la lecture~)
Résumé des articles——
Résumé: PythonCollection d'articles | (Démarrer sur le terrain、Le jeu、Turtle、Cas, etc.)
(Il y a d'autres cas à étudier.~Le code source peut me trouver gratuitement!)

边栏推荐
- [digital signal processing] discrete time signal (analog signal, discrete time signal, digital signal | sampling leads to time discrete | quantization leads to amplitude discrete)
- 泰山OFFICE技术讲座:第一难点是竖向定位
- Luogu_ P1007 single log bridge_ thinking
- Typescript learning materials
- 16 -- remove invalid parentheses
- Design of direct spread spectrum communication system based on FPGA (with main code)
- 专家:让你低分上好校的都是诈骗
- About tensorflow using GPU acceleration
- ICML 2022 ぷ the latest fedformer of the Dharma Institute of Afghanistan ⻓ surpasses SOTA in the whole process of time series prediction
- 专用发票和普通发票的区别
猜你喜欢

Google Earth Engine(GEE)——Export. image. The difference and mixing of toasset/todrive, correctly export classification sample data to asset assets and references

express

CNN convolutional neural network (the easiest to understand version in History)

How is the London Silver point difference calculated

Fundamentals of software engineering (I)

The latest development course of grain college in 2022: 8 - foreground login function

#27ES6的数值扩展

【kotlin】第二天

Teach you how to package and release the mofish Library

Sigkdd22 | graph generalization framework of graph neural network under the paradigm of "pre training, prompting and fine tuning"
随机推荐
SQL injection principle
Keep valid digits; Keep n digits after the decimal point;
16 -- remove invalid parentheses
带你认识图数据库性能和场景测试利器LDBC SNB
[issue 18] share a Netease go classic
Introduce you to ldbc SNB, a powerful tool for database performance and scenario testing
关于快速幂
2022-2-16 learning the imitated Niuke project - Section 6 adding comments
What should the ultimate LAN transmission experience be like
About tensorflow using GPU acceleration
事务的四大特性
Piblup test report 1- pedigree based animal model
MySQL中符号@的作用
CNN convolutional neural network (the easiest to understand version in History)
Li Chuang EDA learning notes 16: array copy and array distribution
Beginner level Luogu 1 [sequence structure] problem list solution
FPGA based analog I ² C protocol system design (with main code)
PolarDB-X现在版本的开源兼容什么?mysql8?
Google tool splits by specified length
请问阿里云实验中 k8s 对于3306端口转发,同时开启mysql客户端就会异常终止,是什么原因呢?