我目前正在业余时间与一个朋友合作进行他们的项目,这是一个像飞扬的小鸟一样的游戏。第一个任务是重写代码,以使其更具可伸缩性和易于阅读。我已经取得了一些进步,但是我无法获得游戏工作的动感部分。
在对如何组织代码进行了一些研究之后,我在下面的thread中发现了这一点,并且该代码对大多数项目都有效,下面是一个示例代码构造示例:
根项目上的game.py
仅通过执行游戏即可正常运行游戏。重写的代码由app.py
,entities
和screens
文件夹组成。
结构:
.
|-- app.py
|-- entities
| |-- lean.py
| `-- trapper.py
|-- game.py
|-- lean.py
|-- requirements.txt
|-- screens
| `-- game.py
`-- trapper.py
app.py:
import tkinter as tk
from screens import Game_screen
class Main_application(tk.Frame):
'''Creates the application frame
Args:
parent: The root of the application.
'''
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, *kwargs)
self.parent = parent
# <TODO: The rest of the application >
self.game_screen = Game_screen(self)
if __name__ == '__main__':
root = tk.Tk()
Main_application(root).pack(
side = 'top',
fill = 'both',
expand = True
)
root.mainloop()
screens / game.py
import tkinter as tk
from entities import Lean
from entities import Trapper
gravity = 10
height = 600
width = 400
speed = 35 # (0 == faster | 0 > slower)
class Game_screen(tk.Frame):
'''Generates the Game Screen.
Args:
master: The application frame.
'''
def __init__(self, master=None, *args, **kwargs):
# Background creation
self.canvas = tk.Canvas(
master,
width = width,
height = height,
bg ='cyan'
)
self.canvas.pack()
# Player instance
self.trapper = Trapper(
width,
height,
10,
10,
gravity
)
# Obstacle instance
self.lean = Lean(
height,
30,
150,
height
)
self.init = 0
self.speed = speed
self.score = 0
# Player creation
self.trapper_obj = self.canvas.create_oval(
self.trapper.x - self.trapper.size,
self.trapper.y - self.trapper.size,
self.trapper.x + self.trapper.size,
self.trapper.y + self.trapper.size,
fill="yellow",
tags="trapper"
)
master.bind('<Up>', self.comandoUp)
# Obstacle creation
self.lean_obj_top = self.canvas.create_polygon(
self.lean.get_lean_top(),
fill='purple',
tags='lean_top'
)
# Obstacle creation
self.lean_obj_bot = self.canvas.create_polygon(
self.lean.get_lean_bot(),
fill='purple',
tags='lean_bot'
)
# Score
self.canvas.create_text(
(width-60, 20),
text='score: {}'.format(
self.score
)
)
# Start game
if(self.init == 1):
self.trapper.moveUp()
self.trapper.moveDown()
self.lean.move(self.trapper.vHor)
# Side-scroller
if(self.lean.x < -self.lean.l):
self.lean = Lean(height, 30, 150, width)
# Collision
pos_t = self.canvas.bbox(self.trapper_obj)
collision = self.canvas.find_overlapping(
pos_t[0],
pos_t[1],
pos_t[2],
pos_t[3]
)
for x in collision:
tagx = self.canvas.gettags(x)[0]
if tagx == 'lean_top' or tagx == 'lean_bot':
print("Hit the pipe")
quit()
elif tagx == 'mid':
self.score += self.lean.score
if self.lean.score == 1:
print(self.score)
self.lean.score = 0
if self.trapper.y > height:
print("Fell off")
quit()
# Render and moves scenario
self.canvas.after(self.speed)
master.update_idletasks()
master.update()
def comandoUp(self, event):
self.trapper.up = 6
self.init = 1
大多数元素都显示在屏幕上,但是它们是静态的,整个周末我都找不到解决方案。如果所提供的信息还不够,我会提供指向我的repository的链接以更好地理解。