python简单小游戏代码(Python游戏开发,Python实现贪吃蛇小游戏与吃豆豆 附带源码)

本文目录
Python游戏开发,Python实现贪吃蛇小游戏与吃豆豆 附带源码
Python版本: 3.6.4
相关模块:
pygame模块;
以及一些Python自带的模块。
安装Python并添加到环境变量,pip安装需要的相关模块即可。
贪吃蛇的 游戏 规则应该不需要我多做介绍了吧T_T。写个贪吃蛇 游戏 其实还是很简单的。首先,我们进行一下 游戏 初始化:
然后定义一个贪吃蛇类:
其中head_coord用来记录蛇头所在位置,而tail_coords是一个二维数组,用来记录所有蛇身的位置。一开始,贪吃蛇长为3,并且位置是随机生成的。用户通过 键来控制贪吃蛇的行动:
需要注意的是,贪吃蛇不能180 大拐弯,只能90 地拐弯。例如正在向左行动的贪吃蛇不能瞬间变成向右行动。具体而言,代码实现如下:
然后,我们需要随机生成一个食物,且需要保证该食物的位置不与贪吃蛇的位置相同:
在更新贪吃蛇的时候,如果它吃到了食物,则蛇身长加一,否则只是简单的按照给定的方向行动而不改变蛇身长度:
同时,当贪吃蛇吃到食物时,需要重新生成一个新的食物:
最后,当贪吃蛇碰到墙壁或者蛇头碰到蛇身时, 游戏 结束:
并显示一下 游戏 结束界面:
玩家通过 键控制 游戏 的主角吃豆人吃掉藏在迷宫内的所有豆子,并且不能被鬼魂抓到。
若能顺利吃完迷宫内的所有豆子并且不被鬼魂抓到,则 游戏 胜利,否则 游戏 失败。
逐步实现:
Step1:定义 游戏 精灵类
首先,让我们先来明确一下该 游戏 需要哪些 游戏 精灵类。
① 墙类
② 食物类(即豆豆)
③ 角色类
角色类包括吃豆人和鬼魂,鬼魂由电脑控制其运动轨迹,吃豆人由玩家控制其运动轨迹。
显然,其均需具备更新角色位置和改变角色运动方向的能力,其源代码如下:
Step2:设计 游戏 地图
利用Step1中定义的 游戏 精灵类,我们就可以开始设计 游戏 地图了。由于时间有限,我只写了一个关卡的 游戏 地图,有兴趣的小伙伴可以在此基础上进行扩展(在我的源代码基础上进行扩展是很方便滴~)。 游戏 地图的设计包括以下四方面内容:
① 创建墙
② 创建门(一开始关幽灵用的)
image.gif
③ 创建角色
④ 创建食物
因为食物不能和墙、门以及角色的位置重叠,所以为了方便设计 游戏 地图,要先创建完墙、门以及角色后再创建食物:
Step3:设计 游戏 主循环
接下来开始设计 游戏 主循环。首先是初始化:
然后定义主函数:
其中startLevelGame函数用于开始某一关 游戏 ,其源代码如下:
showText函数用于在 游戏 结束或关卡切换时在 游戏 界面中显示提示性文字,其源代码如下:
可以玩游戏的代码
五子棋。
freegames.cannon1加农炮免费Python游戏五子棋python?-m?freegames.connect1五子棋。单击一行以放一枚。第一个垂直,水平或对角线连接四枚棋子的玩家获胜!连接4个免费Python游戏数字记忆数字记忆–数字对的益智游戏。单击磁贴以显示数字。匹配两个数字,图块将消失以显示图像。
用python写猜数字小游戏
核心代码给你,具体的功能还需要自己完善。
import time, random
class GuessNum:
def __init__(self):
self._num = ’’
self.input_num =
self.count = 1 #猜对所用次数
self.sec = 0 #猜对所用时间
self._generate_num()
def _generate_num(self): #产生不重复的四个数字
seq_zton = list(range(10))
for i in range(0, 4):
a = str(random.choice(seq_zton)) #选出一个数字
self._num += a
seq_zton.remove(int(a)) #注意a的类型
self.sec = time.clock() #开始计时
def check_answer(self):
return self._num
def check_input(self):
num_pos, num_value = 0, 0 #位置对和数值对的分别的个数
tmp = input("Please input the number you guess(No repetition),or ’c’ to check the answer:")
if tmp == ’c’:
print(self.check_answer())
tof = self.check_input()
return tof
elif not tmp.isalnum or not len(tmp) == 4:
print("Wrong format!")
tof = self.check_input() #需要优化
return tof
self.input_num = list(tmp)
lst_temp = list(self._num)
if self.input_num == lst_temp: #猜对
self.prt_vic()
return True
for i in lst_temp:
if i in self.input_num:
if lst_temp.index(i) == self.input_num.index(i): #位置也相同
num_pos += 1
num_value += 1
else:
num_value += 1
self.prt_state(num_pos, num_value)
self.count += 1
return False
def prt_state(self, num_pos, num_value):
print("You’ve got %d numbers with the right position and %d numbers with the right value only" % (num_pos, num_value))
def prt_vic(self):
t = time.clock()
self.sec = t - self.sec
print("Congratulations!You have successfully got the right number!")
print("%d times and %.2f sec in total to get the right answer" % (self.count, self.sec))
gn = GuessNum()
while True:
ss = gn.check_input()
if ss:
b = input("Continue? y/n:")
if b == ’n’:
break
else:
gn = GuessNum()
continue
球球各位大神怎么用python写一个猜词小游戏的代码
key = input(’请输入一个单词:’)
description = input(’输入单词描述:’)
chance = 5
mark = 5
print(’现在开始游戏’)
print(description + ’ ’+’\t 这是单词的描述,请你输入这个单词: ’)
for i in range(0, 5):
a = input(’请你输入单词:’)
if a == key:
print(’恭喜你答对了,您的分数%d’, mark)
else:
print(’对不起,你打错了,你还有 %d 次机会,你的分数%d’ % (chance-1, mark-1))
if chance == 0:
print(’很抱歉,你已经没有机会了,最后得分%d’ % mark)
chance -= 1
mark -= 1
python小游戏
idea +python3.8+pygame
《pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n5" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"》import random
rang1 = int(input("请设置本局游戏的最小值:"))
rang2 = int(input("请设置本局游戏的最大值:"))
num = random.randint(rang1,rang2)
guess = "guess"
print("数字猜谜游戏!")
i = 0
while guess != num:
i += 1
guess = int(input("请输入你猜的数字:"))
if guess == num:
print("恭喜,你猜对了!")
elif guess 《 num:
print("你猜的数小了...")
else:
print("你猜的数大了...")
print("你总共猜了%d" %i + "次",end = ’’)
print(",快和你朋友较量一下...")《/pre》
成果图
《pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n10" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"》import pygame
import random
from pygame.locals import *
WIDTH = 1200
HEIGHT = 600
class Peas:
def init (self):
self.image = pygame.image.load("./res/peas.gif")
self.image_rect = self.image.get_rect()
self.image_rect.top = 285
self.image_rect.left = 30
self.is_move_up = False
self.is_move_down = False
self.is_shout = False
def display(self):
"""显示豌豆的方法"""
screen.blit(self.image, self.image_rect)
def move_up(self):
"""豌豆向上移动"""
if self.image_rect.top 》 30:
self.image_rect.move_ip(0, -10)
else:
for z in Zombie.zombie_list:
if self.image_rect.colliderect(z.image_rect):
pygame.quit()
exit()
def move_down(self):
"""豌豆向下移动"""
if self.image_rect.bottom 《 HEIGHT - 10:
self.image_rect.move_ip(0, 10)
else:
for z in Zombie.zombie_list:
if self.image_rect.colliderect(z.image_rect):
pygame.quit()
exit()
def shout_bullet(self):
"""发射炮弹方法"""
bullet = Bullet(self)
Bullet.bullet_list.append(bullet)
class Bullet:
bullet_list =
interval = 0
def init (self, peas):
self.image = pygame.image.load("./res/bullet.gif")
self.image_rect = self.image.get_rect()
self.image_rect.top = peas.image_rect.top
self.image_rect.left = peas.image_rect.right
def display(self):
"""显示炮弹的方法"""
screen.blit(self.image, self.image_rect)
def move(self):
"""移动炮弹"""
self.image_rect.move_ip(8, 0)
if self.image_rect.right 》 WIDTH - 20:
Bullet.bullet_list.remove(self)
else:
for z in Zombie.zombie_list:
if self.image_rect.colliderect(z.image_rect):
Zombie.zombie_list.remove(z)
Bullet.bullet_list.remove(self)
break
class Zombie:
zombie_list =
interval = 0
def init (self):
self.image = pygame.image.load("./res/zombie.gif")
self.image = pygame.transform.scale(self.image, (70, 70))
self.image_rect = self.image.get_rect()
self.image_rect.top = random.randint(10, HEIGHT-70)
self.image_rect.left = WIDTH
def display(self):
"""显示炮弹的方法"""
screen.blit(self.image, self.image_rect)
def move(self):
"""移动僵尸"""
self.image_rect.move_ip(-2, 0)
if self.image_rect.left 《 0:
Zombie.zombie_list.remove(self)
else:
if self.image_rect.colliderect(peas.image_rect):
pygame.quit()
exit()
for b in Bullet.bullet_list:
if self.image_rect.colliderect(b.image_rect):
Bullet.bullet_list.remove(b)
Zombie.zombie_list.remove(self)
break
def key_control():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == KEYDOWN:
if event.key == K_UP:
peas.is_move_up = True
peas.is_move_down = False
elif event.key == K_DOWN:
peas.is_move_up = False
peas.is_move_down = True
elif event.key == K_SPACE:
peas.is_shout = True
if event.type == KEYUP:
if event.key == K_UP:
peas.is_move_up = False
elif event.key == K_DOWN:
peas.is_move_down = False
elif event.key == K_SPACE:
peas.is_shout = False
if name == ’ main ’:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
background_image = pygame.image.load("./res/background.png")
scale_background_image = pygame.transform.scale(background_image, (WIDTH, HEIGHT))
scale_background_image_rect = scale_background_image.get_rect()
clock = pygame.time.Clock()
peas = Peas()
while True:
screen.fill((0,0,0))
screen.blit(scale_background_image, scale_background_image_rect)
peas.display()
key_control()
if peas.is_move_up:
peas.move_up()
if peas.is_move_down:
peas.move_down()
Bullet.interval += 1
if peas.is_shout and Bullet.interval 》= 15:
Bullet.interval = 0
peas.shout_bullet()
Zombie.interval += 1
if Zombie.interval 》= 15:
Zombie.interval = 0
Zombie.zombie_list.append(Zombie())
for bullet in Bullet.bullet_list:
bullet.display()
bullet.move()
for zombie in Zombie.zombie_list:
zombie.display()
zombie.move()
pygame.display.update()
clock.tick(60)《/pre》
成果

更多文章:
中国建设银行手机银行app(中国建设银行app怎么免密登录)
2026年11月3日 18:30









