python 당구 게임 구현 예시 코드
구현 코드
# -*- coding: utf-8 -*-
import tkinter as tkinter
import tkinter.messagebox as mb
import random,time
class Ball():
'''
Ball , , ,
init ,Python 。
'''
def __init__(self,canvas,paddle,score,color,init_x=100,init_y=100):
'''
Ball
:param canvas:
:param paddle:
:param score:
:param color:
:param init_x: , ,
:param init_y: , ,
'''
self.canvas = canvas
self.paddle = paddle
self.score = score
self.color = color
# tkinter id, ,
# :(10,10) x,y ,(30,30) x,y , 20
# fill
self.id = canvas.create_oval(10,10,30,30,fill=self.color)
# , ,
self.canvas.move(self.id,init_x,init_y)
# x (x y )
starts = [-3,-2,-1,1,2,3]
# shuffle()
random.shuffle(starts)
# , x, ,
self.x = starts[0]
# y , ,
self.y = -3
# winfo_height() ,
self.canvas_height = self.canvas.winfo_height()
# winfo_width() ,
self.canvas_width = self.canvas.winfo_width()
# , False,
self.hit_bottom = False
def draw(self):
'''
, , 、
'''
#
self.canvas.move(self.id,self.x,self.y)
# coords id ( , )
position = self.canvas.coords(self.id)
# , ,
if position[1] <= 0: # y 0, 3
self.y = 3
if position[3] >= self.canvas_height: # y , ,
self.hit_bottom = True
if self.hit_paddle(position) == True: # ,
self.y = -3
if position[0] <= 0: # x 0, 3
self.x = 3
if position[2] >= self.canvas_width: # x , 3
self.x = -3
def hit_paddle(self,position):
'''
, ,
:param position:
'''
# , ( , )
paddle_position = self.canvas.coords(self.paddle.id)
print ('paddle_position:',paddle_position[0],paddle_position[1],paddle_position[2],paddle_position[3])
# x x , x x
if position[2] >= paddle_position[0] and position[0] <= paddle_position[2]:
# y y , y
if position[3] >= paddle_position[1] and position[3] <= paddle_position[3]:
#
self.x += self.paddle.x
colors = ['red','green']
# shuffle() ,
random.shuffle(colors)
self.color= colors[0]
#
self.canvas.itemconfig(self.id,fill=colors[0])
# , 、
self.score.hit(ball_color = self.color)
self.canvas.itemconfig(self.paddle.id,fill=self.color)
#
self.adjust_paddle(paddle_position)
return True
return False
def adjust_paddle(self,paddle_position):
'''
:paddle_position:
'''
#
paddle_grow_length = 30
# = x - x
paddle_width = paddle_position[2] - paddle_position[0]
if self.color == 'red': #
if paddle_width > 30: # 60
if paddle_position[2] >= self.canvas_width: # x
# x = x -
paddle_position[2] = paddle_position[2] - paddle_grow_length
else:
# x = x +
paddle_position[0] = paddle_position[0] + paddle_grow_length
elif self.color == 'green': #
if paddle_width < 300: # 300
if paddle_position[2] >= self.canvas_width: # x
# x -
paddle_position[0] = paddle_position[0] - paddle_grow_length
else:
# x +
paddle_position[2]=paddle_position[2]+paddle_grow_length
class Paddle:
'''
'''
def __init__(self,canvas,color):
'''
:param canvas:
:param color:
'''
self.canvas = canvas
# winfo_width() ,
self.canvas_width = self.canvas.winfo_width()
# winfo_height() ,
self.canvas_height = self.canvas.winfo_height()
# tkinter id, ,
# create_rectangle ,fill
self.id = canvas.create_rectangle(0,0,180,15,fill=color)
#
self.canvas.move(self.id,200,self.canvas_height*0.75)
# x, 0.
self.x = 0
# , Flase,
self.started = False
# ,
self.continue_game = False
# ‘ '
self.canvas.bind_all('<KeyPress-Left>',self.turn_left)
# ‘ '
self.canvas.bind_all('<KeyPress-Right>',self.turn_right)
# ‘ Enter '
self.canvas.bind_all('<KeyPress-Enter>',self.continue_game)
#
self.canvas.bind_all('<Button-1>',self.start_game)
# ‘ space '
self.canvas.bind_all('<space>',self.pause_game)
def turn_left(self,event):
'''
,
'''
#
position = self.canvas.coords(self.id)
# x 0
if position[0] <= 0:
# , 0
self.x = 0
else:
# 3
self.x = -3
def turn_right(self,event):
#
position = self.canvas.coords(self.id)
# x
if position[2] >= self.canvas_width:
# , 0
self.x = 0
else:
# 3
self.x = 3
def start_game(self,evt):
self.started = True
def pause_game(self,evt):
if self.started:
self.started=False
else:
self.started=True
def draw(self):
'''
'''
#
self.canvas.move(self.id,self.x,0)
#
position = self.canvas.coords(self.id)
# x 0,
if position[0] <= 0:
self.x = 0
# x 0,
elif position[2] >= self.canvas_width:
self.x = 0
class Score():
'''
'''
def __init__(self,canvas,color):
'''
:param canvas:
:param color:
'''
# 0
self.score = 0
# canvas canvas
self.canvas = canvas
# winfo_width() ,
self.canvas_width = self.canvas.winfo_width()
# winfo_height() ,
self.canvas_height = self.canvas.winfo_height()
# ,
self.id = canvas.create_text(self.canvas_width-150,10,text='score:0',fill=color,font=(None, 18, "bold"))
#
self.note = canvas.create_text(self.canvas_width-70,10,text='--',fill='red',font=(None, 18, "bold"))
def hit(self,ball_color='grey'):
'''
, 、
:param ball_color: , 'grey'
'''
#
self.score += 1
#
self.canvas.itemconfig(self.id,text='score:{}'.format(self.score))
#
if ball_color == 'red':
self.canvas.itemconfig(self.note,text='{}-'.format('W'),fill='red')
elif ball_color=='green':
self.canvas.itemconfig(self.note,text='{}+'.format('W'),fill='green')
else:
self.canvas.itemconfig(self.note,text='--',fill='grey')
def main():
# tkinter.Tk() tk , ,
tk = tkinter.Tk()
# call back for Quit
def callback():
'''
, , , ,
,
'''
if mb.askokcancel("Quit", "Do you really wish to quit?"):
# Ball.flag = False
tk.destroy()
# protocol WM_DELETE_WINDOW callback , 'WM_DELETE_WINDOW'
tk.protocol("WM_DELETE_WINDOW", callback)
#
canvas_width = 600
#
canvas_hight = 500
#
tk.title("Ball Game V1.2")
# ,(0,0) “ ”
tk.resizable(0,0)
# wm_attributes, (-topmost), 1 0
tk.wm_attributes("-topmost",1)
# ,bd=0,highlightthickness=0 , 。 bd 。
canvas = tkinter.Canvas(tk,width=canvas_width,height=canvas_hight,bd=0,highlightthickness=0,bg='#00ffff')
#
canvas.pack()
# update ,
tk.update()
# ,
score = Score(canvas,'red')
# ,
paddle = Paddle(canvas,"red")
# ,
ball = Ball(canvas,paddle,score,"grey")
#
game_over_text = canvas.create_text(canvas_width/2,canvas_hight/2,text='Game over',state='hidden',fill='red',font=(None, 18, "bold"))
#
introduce = 'Welcome to Ball GameV1.2:
Click Any Key--Start
Stop--Enter
Continue-Enter
'
game_start_text = canvas.create_text(canvas_width/2,canvas_hight/2,text=introduce,state='normal',fill='magenta',font=(None, 18, "bold"))
# , tkinter
while True:
# ,
if (ball.hit_bottom == False) and ball.paddle.started:
canvas.itemconfig(game_start_text,state='hidden')
ball.draw()
paddle.draw()
# ,
if ball.hit_bottom == True:
time.sleep(0.1)
canvas.itemconfig(game_over_text,state='normal')
#
tk.update_idletasks()
#
tk.update()
time.sleep(0.01)
if __name__=='__main__':
main()
이상 은 python 이 당구 게임 을 실현 하 는 상세 한 내용 입 니 다.python 당구 게임 에 관 한 자 료 는 다른 관련 글 을 주목 하 세 요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.