python 实现简单的吃豆人游戏
作者:tinytsunami 发布时间:2023-12-02 22:00:59
标签:python,吃豆人,游戏
效果展示:
程序简介
1.使用pygame模组
2.在material目录下有一些素材
3.吃豆人的游戏主体
4.吃豆人怪物的AI(未使用深度学习)
主要代码
main.py
import pygame, sys
from pygame.locals import *
from unit import user, enemy
import random
#constant initialize
FPS = 60
BLOCK_SIZE = 24
WIDTH = 29
HEIGHT = 15
WINDOW_WIDTH = WIDTH * BLOCK_SIZE
WINDOW_HEIGHT = HEIGHT * BLOCK_SIZE
MAP_NAME = "./material/map.maze"
BGM_NAME = "./material/bgm.ogg"
BLOCK_IMAGE = "./material/block.png"
FOOD_IMAGE = "./material/food.png"
GAMEOVER_IMAGE = "./material/gameover.png"
SERVER_PORT = 30000
ENEMY_COUNT = 4
OX = 1
OY = 1
DELAY = 8
#pygame initialize
pygame.init()
display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
clock = pygame.time.Clock()
block_image = pygame.image.load(BLOCK_IMAGE)
food_image = pygame.image.load(FOOD_IMAGE)
gameover_image = pygame.image.load(GAMEOVER_IMAGE)
bgm = pygame.mixer.music.load(BGM_NAME)
scene = "game"
unit_list = []
game_map = []
#map initialize
def load_map(filename):
global game_map
game_map.clear()
file = open(filename, 'r')
for line in file.readlines():
game_map.append(list(line.strip()))
pass
pass
#set passport
def through(position):
x = position[0]
y = position[1]
in_range = (x >= 0 and x < WIDTH) and (y >= 0 and y < HEIGHT)
in_space = (not game_map[y][x] == '1')
return (in_range and in_space)
pass
#gameover?
def check_gameover(user_pos, enemy_pos):
global scene
gameover = (enemy_pos[0] == user_pos[0] and enemy_pos[1] == user_pos[1])
if gameover:
scene = "gameover"
pass
return gameover
pass
#gameover
def gameover():
pygame.mixer.music.stop()
keys = pygame.key.get_pressed()
if keys[K_RETURN]:
initialize()
pass
display.fill((0, 0, 0))
x = (WINDOW_WIDTH-gameover_image.get_width())/2
y = (WINDOW_HEIGHT-gameover_image.get_height())/2
display.blit(gameover_image, (x, y))
pygame.display.update()
pass
#unit initialize
def initialize_unit():
unit_list.clear()
ox = random.randint(1, WIDTH - 2)
oy = random.randint(1, HEIGHT - 2)
while not through((ox, oy)):
ox = random.randint(1, WIDTH - 2)
oy = random.randint(1, HEIGHT - 2)
unit_list.append(user(OX, OY))
for i in range(0, ENEMY_COUNT):
enemy_color = i % 4
ox = random.randint(1, WIDTH - 2)
oy = random.randint(1, HEIGHT - 2)
while not through((ox, oy)):
ox = random.randint(1, WIDTH - 2)
oy = random.randint(1, HEIGHT - 2)
unit_list.append(enemy(enemy_color, ox, oy))
pass
pass
#initialize
def initialize():
global scene
load_map(MAP_NAME)
initialize_unit()
scene = "game"
pygame.mixer.music.play(-1)
#system update
def system_update():
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pass
#update control
control_clock = [0, DELAY]
def control_update():
#user control
if control_clock[0] > control_clock[1]:
user = unit_list[0]
keys = pygame.key.get_pressed()
passport = False
pos = user.position
if keys[K_UP]:
pos = user.move(through(user.next(0)))
elif keys[K_RIGHT]:
pos = user.move(through(user.next(1)))
elif keys[K_DOWN]:
pos = user.move(through(user.next(2)))
elif keys[K_LEFT]:
pos = user.move(through(user.next(3)))
pass
game_map[pos[1]][pos[0]] = '0'
#enemy control
u_pos = unit_list[0].position
for index in range(1, len(unit_list)):
enemy = unit_list[index]
if check_gameover(u_pos, enemy.position): break
enemy.track(u_pos)
passport = through(enemy.next())
enemy.move(passport)
while not passport:
enemy.clockwise()
passport = through(enemy.next())
enemy.move(passport)
pass
control_clock[0] = 0
pass
else:
control_clock[0] += 1
pass
pass
#update screen
def screen_update():
display.fill((0, 0, 0))
for i in range(0, HEIGHT):
for j in range(0, WIDTH):
x = j * BLOCK_SIZE
y = i * BLOCK_SIZE
if game_map[i][j] == '1':
display.blit(block_image, (x, y))
elif game_map[i][j] == '4':
display.blit(food_image, (x, y))
pass
pass
pass
for unit in unit_list:
unit.update()
x = unit.position[0] * BLOCK_SIZE
y = unit.position[1] * BLOCK_SIZE
display.blit(unit.image, (x, y), unit.image_rect())
pygame.display.update()
pass
#first
initialize()
#main loop
while True:
system_update()
if scene == "game":
control_update()
screen_update()
else:
gameover()
pass
pass
unit.py
import pygame
import math
import random
USER_IMAGE = "./material/user.png"
ENEMY_IMAGE = [("./material/enemy%d.png" % i) for i in range(1, 5)]
class unit():
def __init__(self, filename):
super(unit, self).__init__()
self.image = pygame.image.load(filename)
self.clock = [0, 5]
self.direction = 0
self.position = [1, 1, 1, 1]
self.index = 0
self.source_rect = 0
pass
def update(self):
self.animation_update()
pass
def animation_update(self):
self.clock[0] += 1
if self.clock[0] > self.clock[1]:
if self.index < 4:
self.index += 4
else:
self.index -= 4
self.source_rect = self.image_rect()
self.clock[0] = 0
pass
pass
def move(self, passport):
if passport:
pos = self.position[:]
self.position[0] = self.position[2]
self.position[1] = self.position[3]
else:
self.position[2] = self.position[0]
self.position[3] = self.position[1]
pos = self.position
pass
return pos
pass
def next(self):
self.ahead()
return (self.position[2], self.position[3])
pass
def turn(self, direction):
self.direction = direction % 4
self.index = self.direction
pass
def ahead(self):
if self.direction == 0:
self.position[3] -= 1
elif self.direction == 1:
self.position[2] += 1
elif self.direction == 2:
self.position[3] += 1
elif self.direction == 3:
self.position[2] -= 1
pass
def image_rect(self):
w = self.image.get_width()
h = self.image.get_height()
ox = math.floor(w / 4 * (self.index % 4))
oy = math.floor(h / 2 * math.floor(self.index / 4))
return pygame.Rect((ox, oy), (24, 24))
class user(unit):
def __init__(self, x, y):
super(user, self).__init__(USER_IMAGE)
self.position = [x, y, x, y]
pass
def next(self, direction):
self.turn(direction)
self.ahead()
return (self.position[2], self.position[3])
pass
class enemy(unit):
def __init__(self, id, x, y):
filename = ENEMY_IMAGE[id]
super(enemy, self).__init__(filename)
self.position = [x, y, x, y]
pass
def track(self, user_pos):
rand_dir = [1,2,3,4]
self.turn(random.choice(rand_dir))
pass
def clockwise(self):
self.turn(self.direction + 1)
pass
class enemy_user(unit):
def __init__(self, x, y):
filename = ENEMY_IMAGE[0]
super(enemy_user, self).__init__(filename)
self.position = [x, y, x, y]
pass
def move(self, x, y):
self.position[0] = x
self.position[1] = y
pass
总结:
程序还有许多地方可以完善,如怪物的AI,时间的判定等等,有兴趣的大佬可以加以修改完善。
完整项目下载:https://github.com/tinytsunami/Python-Game
来源:https://github.com/tinytsunami/Python-Game
0
投稿
猜你喜欢
- 如果在 Access 数据库中删除数据或对象,或者在 Access 项目中删除对象,Access 数据库或 Access 项目可能会产生碎片
- 导言:在前面的3章里我们为处理二进制数据添加了很多的功能。我们首先在表Categories里添加BrochurePath列,并更新了体系结构
- pytho的使用和分发完全是免费的,它是一种面向对象的语言,它的。它的类模块支持多态,操作符重载和多重继承等高级概念,并且以python特有
- 前段时日微软(Microsoft)正式发布了.NET Core 2.0,在很多开发社区中反响不错。但还是有一些开发者发出了疑问,.NET C
- 在产品开发中,由UED发起的项目越来越多,但是现在的问题是很难为其设定商业价值的目标。如果没有明确的商业价值目标,很多公司根本没办法花大成本
- 在软件项目实施的时候,数据导入一直是项目人员比较头疼的问题。其实,在SQL Server中集成了很多成批导入数据的方法。有些项目实施顾问头疼
- Web Standards Solutions The Markup and Style Handbook - Chapter 1 清单首发
- 1、元旦之前受赵晨之邀作为讨论嘉宾参加了ACM组织的“人与信息社会巡讲”。2、去之前赵晨发给了我大致的讨论提纲。咣当了好几下~说实话,我是硬
- 昨天我的电影网站在生成内容静态页面的时候出了问题,提示下标越界,以前从来没有遇到过的,所以根本不知道是什么东西,于是就到处在网上找答案,但是
- 本文详细讲述了Python2.7环境Flask框架安装方法。分享给大家供大家参考,具体如下:第1步:确保本机已经安装有python,下载ea
- 本文实例讲述了Python单元测试方法。分享给大家供大家参考,具体如下:Eric书中《Python编程从入门到实践》中的一个例子。《Pyth
- 在数据处理过程中比如从CSV文件中导入数据data_df = pd.read_csv("names.csv")在处理之前
- 一、变量1.变量•指在程序执行过程中,可变的量;•定义一个变量,就会伴随有3个特征,分别是内存ID、数据类型和变量值。•其他语言运行完之前,
- 定位篇UI 自动化很多时候的苦恼都是定位不到,其实说实话我到现在有时候也是莫名其妙的定位到或者定位不到。好在这个框架定位方式的上限非常以及特
- shell=True参数会让subprocess.call接受字符串类型的变量作为命令,并调用shell去执行这个字符串,当shell=Fa
- 首先我们看公式:这个是要拟合的函数然后我们求出它的损失函数, 注意:这里的n和m均为数据集的长度,写的时候忘了注意,前面的theta0-th
- 前面也讲过一次phar文件上传的东西,但是那都是过滤比较低,仅仅过滤了后缀。知道今天看到了一篇好的文章如果过滤了phar这个伪造协议的话,那
- 朋友的网站要计算机票的折扣价格,并且在最后的折扣价格上应对个位进行四舍五入,同时在ASP和Javasc
- 通过XSL转换XML文件 最近,我喜欢上了XML编程,但又苦于它的美观程度又不够,找了许多书才搞定。用XML好是蛮好,但它还是不太适合做显示
- 在介绍GROUP BY 和 HAVING 子句前,我们必需先讲讲sql语言中一种特殊的函数:聚合函数,例如SUM, COUNT, MAX,