当前位置:网站首页>[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!)

边栏推荐
- Cesium uses mediastreamrecorder or mediarecorder to record screen and download video, as well as turn on camera recording. [transfer]
- What is the London Silver code
- 专家:让你低分上好校的都是诈骗
- The latest development course of grain college in 2022: 8 - foreground login function
- What are the characteristics of fixed income + products?
- Open source 23 things shardingsphere and database mesh have to say
- Piblup test report 1- pedigree based animal model
- What should the ultimate LAN transmission experience be like
- Design of UART controller based on FPGA (with code)
- 老师能给我说一下固收+产品主要投资于哪些方面?
猜你喜欢

A distribution fission activity is more than just a circle of friends!
![洛谷_P1008 [NOIP1998 普及组] 三连击_枚举](/img/9f/64b0b83211bd1c615f2db9273bb905.png)
洛谷_P1008 [NOIP1998 普及组] 三连击_枚举
![Beginner level Luogu 1 [sequence structure] problem list solution](/img/60/5e151ba31eb00374c73be52e3bfa7e.png)
Beginner level Luogu 1 [sequence structure] problem list solution

Jialichuang EDA professional edition all offline client release

Let's talk about the process of ES Indexing Documents
![[digital signal processing] discrete time signal (discrete time signal knowledge points | signal definition | signal classification | classification according to certainty | classification according t](/img/69/daff175c3c6a8971d631f9e681b114.jpg)
[digital signal processing] discrete time signal (discrete time signal knowledge points | signal definition | signal classification | classification according to certainty | classification according t

【Pygame小游戏】这款“吃掉一切”游戏简直奇葩了?通通都吃掉嘛?(附源码免费领)

Weekly snapshot of substrate technology 20220411
![[high concurrency] deeply analyze the callable interface](/img/24/33c3011752c8f04937ad68d85d4ece.jpg)
[high concurrency] deeply analyze the callable interface
MySQL中符号@的作用
随机推荐
Centos8 PostgreSQL initialization error: initdb: error: invalid locale settings; check LANG and LC_* environment
Can polardb-x be accessed through the client of related tools as long as the client supporting JDBC / ODBC protocol is afraid?
A distribution fission activity is more than just a circle of friends!
CNN convolutional neural network (the easiest to understand version in History)
Use redis to automatically cancel orders within 30 minutes
[issue 18] share a Netease go classic
Pisa-Proxy 之 SQL 解析实践
Today, Teng Xu came out with 37k during the interview. It's really a miracle. He showed me his skill
E ModuleNotFoundError: No module named ‘psycopg2‘(已解决)
Introduce you to ldbc SNB, a powerful tool for database performance and scenario testing
NFT双币质押流动性挖矿dapp合约定制
What are the characteristics of fixed income + products?
请问阿里云实验中 k8s 对于3306端口转发,同时开启mysql客户端就会异常终止,是什么原因呢?
[MySQL] query valid data based on time
R language error
Derivation of Halcon camera calibration principle
Eolink launched a support program for small and medium-sized enterprises and start-ups to empower enterprises!
开源二三事|ShardingSphere 与 Database Mesh 之间不得不说的那些事
Scrapy framework (I): basic use
PSS: you are only two convolution layers away from the NMS free+ point | 2021 paper